answer stringlengths 17 10.2M |
|---|
package com.rockwellcollins.atc.resolute.analysis.execution;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.emf.ecore.EObject;
import org.osate.aadl2.AbstractNamedValue;
import org.osate.aadl2.BasicPropertyAssociation;
import org.osate.aadl2.BooleanLiteral;
import org.osate.aadl2.Classifier;
import org.osate.aadl2.ComponentCategory;
import org.osate.aadl2.ComponentClassifier;
import org.osate.aadl2.ComponentImplementation;
import org.osate.aadl2.ComponentType;
import org.osate.aadl2.DataAccess;
import org.osate.aadl2.DataPort;
import org.osate.aadl2.EnumerationLiteral;
import org.osate.aadl2.Feature;
import org.osate.aadl2.IntegerLiteral;
import org.osate.aadl2.ListValue;
import org.osate.aadl2.NamedElement;
import org.osate.aadl2.NamedValue;
import org.osate.aadl2.Property;
import org.osate.aadl2.PropertyConstant;
import org.osate.aadl2.PropertyExpression;
import org.osate.aadl2.RealLiteral;
import org.osate.aadl2.RecordValue;
import org.osate.aadl2.StringLiteral;
import org.osate.aadl2.Subcomponent;
import org.osate.aadl2.instance.ComponentInstance;
import org.osate.aadl2.instance.ConnectionInstance;
import org.osate.aadl2.instance.ConnectionReference;
import org.osate.aadl2.instance.FeatureInstance;
import org.osate.aadl2.instance.InstanceReferenceValue;
import org.osate.aadl2.instance.SystemInstance;
import org.osate.aadl2.properties.PropertyDoesNotApplyToHolderException;
import org.osate.aadl2.properties.PropertyNotPresentException;
import org.osate.aadl2.util.OsateDebug;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorTransition;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorPropagation;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorTypes;
import org.osate.xtext.aadl2.errormodel.errorModel.TypeToken;
import org.osate.xtext.aadl2.errormodel.util.EMV2Util;
import org.osate.xtext.aadl2.properties.util.GetProperties;
import org.osate.xtext.aadl2.properties.util.PropertyUtils;
import com.rockwellcollins.atc.resolute.analysis.values.BoolValue;
import com.rockwellcollins.atc.resolute.analysis.values.IntValue;
import com.rockwellcollins.atc.resolute.analysis.values.NamedElementValue;
import com.rockwellcollins.atc.resolute.analysis.values.RangeValue;
import com.rockwellcollins.atc.resolute.analysis.values.RealValue;
import com.rockwellcollins.atc.resolute.analysis.values.ResoluteRecordValue;
import com.rockwellcollins.atc.resolute.analysis.values.ResoluteValue;
import com.rockwellcollins.atc.resolute.analysis.values.SetValue;
import com.rockwellcollins.atc.resolute.analysis.values.StringValue;
import com.rockwellcollins.atc.resolute.resolute.BuiltInFnCallExpr;
public class ResoluteBuiltInFnCallEvaluator {
private static final BoolValue TRUE = new BoolValue(true);
private static final BoolValue FALSE = new BoolValue(false);
private final EvaluationContext context;
public ResoluteBuiltInFnCallEvaluator(EvaluationContext context) {
this.context = context;
}
public ResoluteValue evaluate(BuiltInFnCallExpr fnCallExpr, List<ResoluteValue> args) {
switch (fnCallExpr.getFn()) {
/*
* Primary type: aadl
*/
case "has_property": {
NamedElement element = args.get(0).getNamedElement();
Property prop = (Property) args.get(1).getNamedElement();
return bool(getPropertyExpression(element, prop) != null);
}
case "property": {
NamedElement element = args.get(0).getNamedElement();
Property prop = (Property) args.get(1).getNamedElement();
PropertyExpression expr = getPropertyExpression(element, prop);
if (expr == null) {
if (args.size() > 2) {
return args.get(2);
}
throw new ResoluteFailException("Property " + prop.getName() + " not defined on " + element.getName(),
fnCallExpr);
}
return exprToValue(expr);
}
case "property_member": {
ResoluteRecordValue record = (ResoluteRecordValue)args.get(0);
String fieldName = args.get(1).getString().toLowerCase();
ResoluteValue fieldValue = record.getField(fieldName);
if (fieldValue == null) {
throw new ResoluteFailException("Record Field " + fieldName + " not found", fnCallExpr);
}
return fieldValue;
}
case "has_parent": {
NamedElement element = args.get(0).getNamedElement();
EObject parent = element.eContainer();
return bool(parent instanceof NamedElement);
}
case "parent": {
NamedElement element = args.get(0).getNamedElement();
EObject parent = element.eContainer();
if (parent instanceof NamedElement) {
return new NamedElementValue((NamedElement) parent);
} else {
throw new ResoluteFailException("Unable to get parent of " + args.get(0), fnCallExpr);
}
}
case "name": {
return new StringValue(args.get(0).getNamedElement().getName());
}
case "type": {
NamedElement element = args.get(0).getNamedElement();
NamedElement type = builtinType(element);
if (type == null) {
throw new IllegalArgumentException("Unable to get type of: " + element);
}
return new NamedElementValue(type);
}
case "has_type": {
NamedElement element = args.get(0).getNamedElement();
NamedElement type = builtinType(element);
return bool(type != null);
}
case "is_bound_to": {
NamedElement ne = args.get(0).getNamedElement();
NamedElement resource = args.get(1).getNamedElement();
if ((ne instanceof ComponentInstance) && (resource instanceof ComponentInstance)) {
ComponentInstance componentInstance = (ComponentInstance) ne;
ComponentInstance resourceInstance = (ComponentInstance) resource;
/**
* Check the processor binding
*/
for (ComponentInstance binding : GetProperties.getActualProcessorBinding(componentInstance)) {
if (binding == resourceInstance) {
return bool(true);
}
}
/**
* Check the memory binding
*/
for (ComponentInstance binding : GetProperties.getActualMemoryBinding(componentInstance)) {
if (binding == resourceInstance) {
return bool(true);
}
}
}
if ((ne instanceof ConnectionInstance) && (resource instanceof ComponentInstance)) {
ConnectionInstance ci = (ConnectionInstance) ne;
ComponentInstance resourceInstance = (ComponentInstance) resource;
for (ComponentInstance binding : GetProperties.getActualConnectionBinding(ci)) {
if (binding == resourceInstance) {
return bool(true);
}
}
}
return bool(false);
}
case "is_of_type": {
NamedElement element = args.get(0).getNamedElement();
NamedElement type = args.get(1).getNamedElement();
if (element instanceof ComponentInstance) {
ComponentInstance ci;
ComponentType ct;
Classifier cl;
ci = (ComponentInstance) element;
if ((ci == null) || (ci.getSubcomponent() == null)) {
return bool(false);
}
ct = ci.getSubcomponent().getComponentType();
// cl = (Classifier) type;
// return bool ((ct == cl ) || (ct.isDescendentOf(cl)));
while (ct != null) {
if (ct == type) {
return bool(true);
}
ct = ct.getExtended();
}
}
return bool(false);
// return bool(false);
}
case "has_member": {
boolean hasMember;
String memberName;
NamedElement element;
hasMember = false;
element = args.get(0).getNamedElement();
memberName = args.get(1).getString();
if (element instanceof ComponentInstance) {
element = ((ComponentInstance) element).getComponentClassifier();
}
if (element instanceof ComponentClassifier) {
ComponentClassifier cc = (ComponentClassifier) element;
for (Feature f : cc.getAllFeatures()) {
if (f.getName().equalsIgnoreCase(memberName)) {
hasMember = true;
}
}
}
if (element instanceof ComponentImplementation) {
ComponentImplementation ci = (ComponentImplementation) element;
for (Subcomponent s : ci.getAllSubcomponents()) {
if (s.getName().equalsIgnoreCase(memberName)) {
hasMember = true;
}
}
}
return bool(hasMember);
}
case "features": {
NamedElement e = args.get(0).getNamedElement();
if (e instanceof ComponentInstance) {
ComponentInstance ci = (ComponentInstance) e;
return createSetValue(ci.getFeatureInstances());
} else if (e instanceof FeatureInstance) {
FeatureInstance fi = (FeatureInstance) e;
return createSetValue(fi.getFeatureInstances());
} else {
throw new ResoluteFailException("features not defined on object of type: " + args.get(0).getType(),
fnCallExpr);
}
}
case "connections": {
NamedElement e = args.get(0).getNamedElement();
if (e instanceof FeatureInstance) {
FeatureInstance feat = (FeatureInstance) e;
return new SetValue(context.getConnectionsForFeature(feat));
} else if (e instanceof ComponentInstance) {
ComponentInstance ci = (ComponentInstance) e;
List<ResoluteValue> result = new ArrayList<>();
// Include connections for all features on the component
for (FeatureInstance feat : ci.getFeatureInstances()) {
result.addAll(context.getConnectionsForFeature(feat));
}
// Include connections originating or terminating with the
// component
result.addAll(createSetValue(ci.getSrcConnectionInstances()).getSet());
result.addAll(createSetValue(ci.getDstConnectionInstances()).getSet());
return new SetValue(result);
} else {
throw new ResoluteFailException("connections not defined on object of type: " + args.get(0).getType(),
fnCallExpr);
}
}
/*
* Primary type: component
*/
case "subcomponents": {
ComponentInstance ci = (ComponentInstance) args.get(0).getNamedElement();
SetValue sv = createSetValue(ci.getComponentInstances());
return sv;
}
/*
* Primary type: connection
*/
case "source": {
ConnectionInstance conn = (ConnectionInstance) args.get(0).getNamedElement();
return new NamedElementValue(conn.getSource());
}
case "destination": {
ConnectionInstance conn = (ConnectionInstance) args.get(0).getNamedElement();
return new NamedElementValue(conn.getDestination());
}
/*
* Primary type: feature
*/
case "direction": {
FeatureInstance feat = (FeatureInstance) args.get(0).getNamedElement();
return new StringValue(feat.getDirection().toString());
}
case "is_processor":
{
ComponentInstance ci = (ComponentInstance) args.get(0).getNamedElement();
return new BoolValue(ci.getCategory() == ComponentCategory.PROCESSOR);
}
case "is_virtual_processor":
{
ComponentInstance ci = (ComponentInstance) args.get(0).getNamedElement();
return new BoolValue(ci.getCategory() == ComponentCategory.VIRTUAL_PROCESSOR);
}
case "is_system":
{
ComponentInstance ci = (ComponentInstance) args.get(0).getNamedElement();
return new BoolValue(ci.getCategory() == ComponentCategory.SYSTEM);
}
case "is_bus":
{
ComponentInstance ci = (ComponentInstance) args.get(0).getNamedElement();
return new BoolValue(ci.getCategory() == ComponentCategory.BUS);
}
case "is_virtual_bus":
{
ComponentInstance ci = (ComponentInstance) args.get(0).getNamedElement();
return new BoolValue(ci.getCategory() == ComponentCategory.VIRTUAL_BUS);
}
case "is_device":
{
ComponentInstance ci = (ComponentInstance) args.get(0).getNamedElement();
return new BoolValue(ci.getCategory() == ComponentCategory.DEVICE);
}
case "is_memory":
{
ComponentInstance ci = (ComponentInstance) args.get(0).getNamedElement();
return new BoolValue(ci.getCategory() == ComponentCategory.MEMORY);
}
case "is_thread":
{
ComponentInstance ci = (ComponentInstance) args.get(0).getNamedElement();
return new BoolValue(ci.getCategory() == ComponentCategory.THREAD);
}
case "is_process":
{
ComponentInstance ci = (ComponentInstance) args.get(0).getNamedElement();
return new BoolValue(ci.getCategory() == ComponentCategory.PROCESS);
}
case "is_event_port": {
NamedElement feat = args.get(0).getNamedElement();
if (feat instanceof FeatureInstance)
{
FeatureInstance fi = (FeatureInstance) feat;
if (fi.getCategory() == org.osate.aadl2.instance.FeatureCategory.EVENT_PORT)
{
return new BoolValue(true);
}
if (fi.getCategory() == org.osate.aadl2.instance.FeatureCategory.EVENT_DATA_PORT)
{
return new BoolValue(true);
}
}
return new BoolValue(false);
}
case "is_port": {
boolean ret;
ret = false;
NamedElement feat = args.get(0).getNamedElement();
if (feat instanceof FeatureInstance)
{
FeatureInstance fi = (FeatureInstance) feat;
if (fi.getCategory() == org.osate.aadl2.instance.FeatureCategory.DATA_PORT)
{
ret = true;
}
if (fi.getCategory() == org.osate.aadl2.instance.FeatureCategory.EVENT_DATA_PORT)
{
ret = true;
}
if (fi.getCategory() == org.osate.aadl2.instance.FeatureCategory.EVENT_PORT)
{
ret = true;
}
}
return new BoolValue(ret);
}
case "is_data_port": {
NamedElement feat = args.get(0).getNamedElement();
if (feat instanceof FeatureInstance)
{
FeatureInstance fi = (FeatureInstance) feat;
if (fi.getCategory() == org.osate.aadl2.instance.FeatureCategory.DATA_PORT)
{
return new BoolValue(true);
}
if (fi.getCategory() == org.osate.aadl2.instance.FeatureCategory.EVENT_DATA_PORT)
{
return new BoolValue(true);
}
}
return new BoolValue(false);
}
/*
* Primary type: range
*/
case "lower_bound": {
RangeValue rv = (RangeValue) args.get(0);
return rv.getMin();
}
case "upper_bound": {
RangeValue rv = (RangeValue) args.get(0);
return rv.getMax();
}
/*
* Primary type: set
*/
case "member": {
return bool(args.get(1).getSet().contains(args.get(0)));
}
case "size":
case "length": {
List<ResoluteValue> set = args.get(0).getSet();
int setsize = set.size();
return new IntValue(setsize);
}
case "sum": {
List<ResoluteValue> set = args.get(0).getSet();
if (set.isEmpty()) {
return new IntValue(0);
}
ResoluteValue first = set.iterator().next();
if (first.isInt()) {
long sum = 0;
for (ResoluteValue item : set) {
sum += item.getInt();
}
return new IntValue(sum);
} else {
double sum = 0;
for (ResoluteValue item : set) {
sum += item.getReal();
}
return new RealValue(sum);
}
}
case "union": {
List<ResoluteValue> set = new ArrayList<>();
set.addAll(args.get(0).getSet());
set.addAll(args.get(1).getSet());
return new SetValue(set);
}
case "intersect": {
List<ResoluteValue> set = new ArrayList<>();
for (ResoluteValue val1 : args.get(0).getSet()) {
for (ResoluteValue val2 : args.get(1).getSet()) {
if (val1.equals(val2)) {
set.add(val1);
}
}
}
return new SetValue(set);
}
/*
* Other
*/
case "analysis": {
String analysisName = args.get(0).getString();
List<ResoluteValue> analysisArgs = args.subList(1, args.size());
ResoluteValue value = EvaluateExternalAnalysis.evaluate(analysisName, context, analysisArgs);
if (value == null) {
throw new ResoluteFailException("External analysis '" + analysisName + "' failed", fnCallExpr);
} else {
return value;
}
}
case "is_data_access": {
NamedElement feat = args.get(0).getNamedElement();
if (feat instanceof ConnectionInstance) {
ComponentInstance accessedComponent = null;
ConnectionInstance ci = (ConnectionInstance) feat;
// OsateDebug.osateDebug("source=" + ci.getSource());
// OsateDebug.osateDebug("destination=" + ci.getDestination());
if (ci.getSource() instanceof ComponentInstance)
{
accessedComponent = (ComponentInstance) ci.getSource();
}
if (ci.getDestination() instanceof ComponentInstance)
{
accessedComponent = (ComponentInstance) ci.getDestination();
}
return new BoolValue((ci.getKind() == org.osate.aadl2.instance.ConnectionKind.ACCESS_CONNECTION) &&
(accessedComponent.getCategory() == ComponentCategory.DATA));
}
return new BoolValue(feat instanceof DataAccess);
}
case "instance": {
NamedElement decl = args.get(0).getNamedElement();
SystemInstance top = context.getThisInstance().getSystemInstance();
ComponentInstance result = null;
for (ComponentInstance ci : top.getAllComponentInstances()) {
if (isInstanceOf(ci, decl)) {
if (result == null) {
result = ci;
} else {
throw new ResoluteFailException("Found multiple instances of declarative element", fnCallExpr);
}
}
}
if (result != null) {
return new NamedElementValue(result);
} else {
throw new ResoluteFailException("Failed to find instance of declarative element", fnCallExpr);
}
}
case "debug": {
int i = 0;
String s = "";
for (ResoluteValue arg : args)
{
if (i > 0)
{
s += ",";
}
s += "#" + i + ": "+arg.toString();
i++;
}
OsateDebug.osateDebug(s);
return TRUE;
}
case "instances": {
NamedElement decl = args.get(0).getNamedElement();
SystemInstance top = context.getThisInstance().getSystemInstance();
List<NamedElementValue> result = new ArrayList<>();
for (ComponentInstance ci : top.getAllComponentInstances()) {
if (isInstanceOf(ci, decl)) {
result.add(new NamedElementValue(ci));
}
}
return new SetValue(result);
}
/*
* Error Annex
*/
case "error_state_reachable": {
ComponentInstance comp = (ComponentInstance) args.get(0).getNamedElement();
String stateName = args.get(1).getString();
for (ErrorBehaviorTransition ebt : EMV2Util.getAllErrorBehaviorTransitions(comp)) {
if (ebt.getTarget().getName().equalsIgnoreCase(stateName)) {
return TRUE;
}
}
return FALSE;
}
case "propagate_error": {
ComponentInstance comp = (ComponentInstance) args.get(0).getNamedElement();
String errorName = args.get(1).getString();
for (ErrorPropagation ep : EMV2Util.getAllOutgoingErrorPropagations(comp.getComponentClassifier())) {
for (TypeToken tt : ep.getTypeSet().getTypeTokens()) {
for (ErrorTypes et : tt.getType()) {
if (et.getName().equalsIgnoreCase(errorName)) {
return TRUE;
}
}
}
}
return FALSE;
}
default:
throw new IllegalArgumentException("Unknown function: " + fnCallExpr.getFn());
}
}
private static ResoluteValue bool(boolean bool) {
return bool ? TRUE : FALSE;
}
private static SetValue createSetValue(Iterable<? extends NamedElement> iterable) {
List<ResoluteValue> result = new ArrayList<ResoluteValue>();
for (NamedElement ne : iterable) {
result.add(new NamedElementValue(ne));
}
return new SetValue(result);
}
private static boolean isInstanceOf(ComponentInstance instance, NamedElement declarative) {
ComponentClassifier cc = instance.getComponentClassifier();
if (cc.equals(declarative)) {
return true;
}
if (cc instanceof ComponentImplementation) {
ComponentImplementation ci = (ComponentImplementation) cc;
return (ci.getType().equals(declarative));
}
return false;
}
private static ResoluteValue exprToValue(PropertyExpression expr) {
if (expr instanceof StringLiteral) {
StringLiteral value = (StringLiteral) expr;
return new StringValue(value.getValue());
} else if (expr instanceof NamedValue) {
NamedValue namedVal = (NamedValue) expr;
if (namedVal.getNamedValue() instanceof PropertyConstant) {
PropertyConstant pc = (PropertyConstant) namedVal.getNamedValue();
return exprToValue(pc.getConstantValue());
}
AbstractNamedValue absVal = namedVal.getNamedValue();
EnumerationLiteral enVal = (EnumerationLiteral) absVal;
return new StringValue(enVal.getName());
} else if (expr instanceof BooleanLiteral) {
BooleanLiteral value = (BooleanLiteral) expr;
return bool(value.getValue());
} else if (expr instanceof IntegerLiteral) {
IntegerLiteral value = (IntegerLiteral) expr;
return new IntValue((long) value.getScaledValue());
} else if (expr instanceof RealLiteral) {
RealLiteral value = (RealLiteral) expr;
return new RealValue(value.getValue());
} else if (expr instanceof org.osate.aadl2.RangeValue) {
org.osate.aadl2.RangeValue value = (org.osate.aadl2.RangeValue) expr;
return new RangeValue(exprToValue(value.getMinimum()), exprToValue(value.getMaximum()));
} else if (expr instanceof InstanceReferenceValue) {
InstanceReferenceValue value = (InstanceReferenceValue) expr;
return new NamedElementValue(value.getReferencedInstanceObject());
} else if (expr instanceof ListValue) {
ListValue value = (ListValue) expr;
List<ResoluteValue> result = new ArrayList<>();
for (PropertyExpression element : value.getOwnedListElements()) {
result.add(exprToValue(element));
}
return new SetValue(result);
} else if (expr instanceof RecordValue) {
Stream<BasicPropertyAssociation> fieldsStream = ((RecordValue)expr).getOwnedFieldValues().stream();
Map<String, ResoluteValue> fieldsMap = fieldsStream.collect(Collectors.toMap(field -> {
return field.getProperty().getName().toLowerCase();
}, field -> {
return exprToValue(field.getOwnedValue());
}));
return new ResoluteRecordValue(fieldsMap);
} else {
throw new IllegalArgumentException("Unknown property expression type: " + expr.getClass().getName());
}
}
private static NamedElement builtinType(NamedElement ne) {
if (ne instanceof ConnectionInstance) {
ConnectionInstance ci = (ConnectionInstance) ne;
if (ci.getSource() instanceof FeatureInstance) {
FeatureInstance src = (FeatureInstance) ci.getSource();
return (NamedElement) src.getFeature().getFeatureClassifier();
} else if (ci.getDestination() instanceof FeatureInstance) {
FeatureInstance src = (FeatureInstance) ci.getDestination();
return (NamedElement) src.getFeature().getFeatureClassifier();
}
} else if (ne instanceof DataPort) {
DataPort dp = (DataPort) ne;
return dp.getDataFeatureClassifier();
} else if (ne instanceof FeatureInstance) {
FeatureInstance fi = (FeatureInstance) ne;
if (fi.getFeature() instanceof DataPort) {
DataPort dp = (DataPort) fi.getFeature();
return dp.getDataFeatureClassifier();
}
return (NamedElement) fi.getFeature().getFeatureClassifier();
} else if (ne instanceof ComponentInstance) {
ComponentInstance ci = (ComponentInstance) ne;
return ci.getComponentClassifier();
}
return null;
}
private static PropertyExpression getPropertyExpression(NamedElement comp, Property prop) {
PropertyExpression result;
if (comp instanceof ConnectionInstance) {
PropertyExpression expr;
ConnectionInstance conn = (ConnectionInstance) comp;
for (ConnectionReference ref : conn.getConnectionReferences()) {
expr = getPropertyExpression(ref, prop);
if (expr != null) {
result = expr;
}
}
}
try {
comp.getPropertyValue(prop); // this just checks to see if the
// property is associated
result = PropertyUtils.getSimplePropertyValue(comp, prop);
} catch (PropertyDoesNotApplyToHolderException propException) {
return null;
} catch (PropertyNotPresentException propNotPresentException) {
return null;
}
return result;
}
} |
package org.scijava.io.handle;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Date;
import org.scijava.io.location.FileLocation;
import org.scijava.plugin.Plugin;
/**
* {@link DataHandle} for a {@link FileLocation}.
*
* @author Curtis Rueden
*/
@Plugin(type = DataHandle.class)
public class FileHandle extends AbstractDataHandle<FileLocation> {
// -- Fields --
/** The {@link RandomAccessFile} backing this file handle. */
private RandomAccessFile raf;
/** The mode of the {@link RandomAccessFile}. */
private String mode;
/** True iff the {@link #close()} has already been called. */
private boolean closed;
// -- FileHandle methods --
/**
* Gets the random access file object backing this FileHandle. If the
* underlying file does not exist yet, it will be created.
*/
public RandomAccessFile getRandomAccessFile() throws IOException {
return writer();
}
public String getMode() {
return mode;
}
public void setMode(final String mode) {
if (raf != null) {
throw new IllegalStateException("File already initialized");
}
this.mode = mode;
}
// -- DataHandle methods --
@Override
public boolean isReadable() {
return getMode().contains("r");
}
@Override
public boolean isWritable() {
return getMode().contains("w");
}
@Override
public boolean exists() {
return get().getFile().exists();
}
@Override
public Date lastModified() {
final long lastModified = get().getFile().lastModified();
return lastModified == 0 ? null : new Date(lastModified);
}
@Override
public long offset() throws IOException {
return exists() ? reader().getFilePointer() : 0;
}
@Override
public long length() throws IOException {
return exists() ? reader().length() : -1;
}
@Override
public void setLength(final long length) throws IOException {
writer().setLength(length);
}
@Override
public int read() throws IOException {
return reader().read();
}
@Override
public int read(final byte[] b) throws IOException {
return reader().read(b);
}
@Override
public int read(final byte[] b, final int off, final int len)
throws IOException
{
return reader().read(b, off, len);
}
@Override
public void seek(final long pos) throws IOException {
reader().seek(pos);
}
// -- DataInput methods --
@Override
public boolean readBoolean() throws IOException {
return reader().readBoolean();
}
@Override
public byte readByte() throws IOException {
return reader().readByte();
}
@Override
public void readFully(final byte[] b) throws IOException {
reader().readFully(b);
}
@Override
public void readFully(final byte[] b, final int off, final int len)
throws IOException
{
reader().readFully(b, off, len);
}
@Override
public String readLine() throws IOException {
return reader().readLine();
}
@Override
public int readUnsignedByte() throws IOException {
return reader().readUnsignedByte();
}
@Override
public String readUTF() throws IOException {
return reader().readUTF();
}
@Override
public int skipBytes(final int n) throws IOException {
return reader().skipBytes(n);
}
// -- DataOutput methods --
@Override
public void write(final byte[] b) throws IOException {
writer().write(b);
}
@Override
public void write(final byte[] b, final int off, final int len)
throws IOException
{
writer().write(b, off, len);
}
@Override
public void write(final int b) throws IOException {
writer().write(b);
}
@Override
public void writeBoolean(final boolean v) throws IOException {
writer().writeBoolean(v);
}
@Override
public void writeByte(final int v) throws IOException {
writer().writeByte(v);
}
@Override
public void writeBytes(final String s) throws IOException {
writer().writeBytes(s);
}
@Override
public void writeChars(final String s) throws IOException {
writer().writeChars(s);
}
@Override
public void writeUTF(final String str) throws IOException {
writer().writeUTF(str);
}
// -- Closeable methods --
@Override
public synchronized void close() throws IOException {
if (raf != null) raf.close();
closed = true;
}
// -- WrapperPlugin methods --
@Override
public void set(FileLocation loc) {
super.set(loc);
final File file = loc.getFile();
String mode;
if (file.exists()) {
final Path path = loc.getFile().toPath();
mode = "";
if (Files.isReadable(path)) mode += "r";
if (Files.isWritable(path)) mode += "w";
}
else {
// Non-existent file; assume the intent is to create it.
mode = "rw";
}
setMode(mode);
}
// -- Typed methods --
@Override
public Class<FileLocation> getType() {
return FileLocation.class;
}
// -- Helper methods --
/**
* Access method for the internal {@link RandomAccessFile}, that succeeds
* independently of the underlying file existing on disk. This allows us to
* create a new file for writing.
*
* @return the internal {@link RandomAccessFile} creating a new file on disk
* if needed.
* @throws IOException if the {@link RandomAccessFile} could not be created.
*/
private RandomAccessFile writer() throws IOException {
if (raf == null) initRAF(true);
return raf;
}
/**
* Access method for the internal {@link RandomAccessFile}, that only succeeds
* if the underlying file exists on disk. This prevents accidental creation of
* an empty file when calling read operations on a non-existent file.
*
* @return the internal {@link RandomAccessFile}.
* @throws IOException if the {@link RandomAccessFile} could not be created,
* or the backing file does not exists.
*/
private RandomAccessFile reader() throws IOException {
if (raf == null) initRAF(false);
return raf;
}
/**
* Initializes the {@link RandomAccessFile}.
*
* @param create whether to create the {@link RandomAccessFile} if the
* underlying file does not exist yet.
* @throws IOException if the {@link RandomAccessFile} could not be created,
* or the backing file does not exist and the {@code create}
* parameter was set to {@code false}.
*/
private synchronized void initRAF(final boolean create) throws IOException {
if (!create && !exists()) {
throw new IOException("Trying to read from non-existent file!");
}
if (closed) throw new IOException("Handle already closed");
if (raf != null) return;
raf = new RandomAccessFile(get().getFile(), getMode());
}
} |
package de.prob2.ui.eclipse;
import org.eclipse.swt.SWT;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;
import de.prob.webconsole.WebConsole;
import de.prob.webconsole.servlets.visualizations.IRefreshListener;
public class BrowserView extends ViewPart implements IRefreshListener {
private final int port;
private Composite canvas;
private Browser browser;
protected String url;
public BrowserView(String url) {
this.url = url;
port = WebConsole.getPort();
}
/**
* This is a callback that will allow us to create the viewer and initialize
* it.
*/
@Override
public void createPartControl(final Composite parent) {
createSWTBrowser(parent);
}
private void createSWTBrowser(Composite parent) {
Browser b = new Browser(parent, SWT.NONE);
this.browser = b;
load(getUrl());
canvas = b;
}
public void refresh() {
browser.refresh();
}
public void load(String url) {
if (url == null) {
// FIXME log error?
return;
}
if (url.startsWith("http:
browser.setUrl(url);
} else {
browser.setUrl("http://localhost:" + port + "/" + url);
}
}
protected String getUrl() {
return url;
}
/**
* Passing the focus request to the viewer's control.
*/
@Override
public void setFocus() {
canvas.setFocus();
}
} |
package me.coley.recaf.ui.component;
import org.controlsfx.control.PropertySheet.Item;
import javafx.scene.Parent;
import javafx.stage.Stage;
import me.coley.recaf.ui.component.ReflectivePropertySheet.CustomEditor;
import me.coley.recaf.util.JavaFX;
import me.coley.recaf.util.Lang;
/**
* CustomEditor with for displaying external stages, without duplication.
*
* @author Matt
*
* @param <T>
*/
public abstract class StagedCustomEditor<T> extends CustomEditor<T> {
/**
* Cached stage, allows the same instance to be saved after <>"closing"</> the window.
*/
protected Stage stage;
public StagedCustomEditor(Item item) {
super(item);
}
/**
* Bring window to front is stage exists.
*
* @return
*/
protected boolean staged() {
// Don't make duplicate windows if not needed
if (stage != null) {
stage.toFront();
if (!stage.isShowing()) {
stage.show();
}
return true;
}
return false;
}
/**
* Setup stage.
*
* @param key
* Translation key for title.
* @param node
* Content.
* @param width
* @param height
*/
protected void setStage(String key, Parent node, int width, int height) {
stage = JavaFX.stage(JavaFX.scene(node, width, height), Lang.get(key), true);
stage.setOnCloseRequest(e -> stage = null);
stage.show();
}
} |
package org.smoothbuild.record.spec;
import java.util.Objects;
import org.smoothbuild.db.hashed.Hash;
import org.smoothbuild.db.hashed.HashedDb;
import org.smoothbuild.record.base.MerkleRoot;
import org.smoothbuild.record.base.Record;
import org.smoothbuild.record.base.RecordImpl;
import org.smoothbuild.record.db.RecordDb;
public abstract class Spec implements Record {
private final SpecKind kind;
private final RecordImpl record;
protected final HashedDb hashedDb;
protected final RecordDb recordDb;
protected Spec(MerkleRoot merkleRoot, SpecKind kind, HashedDb hashedDb,
RecordDb recordDb) {
this.kind = kind;
this.record = new RecordImpl(merkleRoot, hashedDb);
this.hashedDb = hashedDb;
this.recordDb = recordDb;
}
/**
* Creates new java object Record represented by merkleRoot.
*/
public abstract Record newJObject(MerkleRoot merkleRoot);
@Override
public Hash hash() {
return record.hash();
}
@Override
public Hash dataHash() {
return record.dataHash();
}
@Override
public Spec spec() {
return record.spec();
}
@Override
public boolean equals(Object object) {
return (object instanceof Spec that) && Objects.equals(hash(), that.hash());
}
@Override
public int hashCode() {
return hash().hashCode();
}
@Override
public String toString() {
return valueToString() + ":" + hash();
}
@Override
public String valueToString() {
return name();
}
public String name() {
return kind.name();
}
public SpecKind kind() {
return kind;
}
public Class<? extends Record> jType() {
return kind.jType();
}
public boolean isArray() {
return this instanceof ArraySpec;
}
public boolean isNothing() {
return kind == SpecKind.NOTHING;
}
} |
package pl.pw.edu.mini.dos.master;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import pl.pw.edu.mini.dos.communication.ErrorEnum;
import pl.pw.edu.mini.dos.communication.ErrorHandler;
import pl.pw.edu.mini.dos.communication.Services;
import pl.pw.edu.mini.dos.communication.clientmaster.ClientMasterInterface;
import pl.pw.edu.mini.dos.communication.clientmaster.ExecuteSQLRequest;
import pl.pw.edu.mini.dos.communication.clientmaster.ExecuteSQLResponse;
import pl.pw.edu.mini.dos.communication.masternode.ExecuteSQLOnNodeRequest;
import pl.pw.edu.mini.dos.communication.masternode.ExecuteSQLOnNodeResponse;
import pl.pw.edu.mini.dos.communication.masternode.MasterNodeInterface;
import pl.pw.edu.mini.dos.communication.nodemaster.*;
import pl.pw.edu.mini.dos.communication.nodenode.NodeNodeInterface;
import pl.pw.edu.mini.dos.master.rmi.RMIServer;
import pl.pw.edu.mini.dos.master.node.Node;
import java.io.Serializable;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Master extends UnicastRemoteObject
implements NodeMasterInterface, ClientMasterInterface, Serializable {
/** Logger */
private static final Logger logger = LoggerFactory.getLogger(Master.class);
private RMIServer server;
private final List<Node> nodes;
public Master(String host, int port) throws RemoteException {
nodes = new ArrayList<>();
server = new RMIServer(host, port);
server.startService(Services.MASTER, this);
logger.info("Master listening at (" + host + ":" + port + ")");
}
/**
* @param args = {"localhost", "1099"}
*/
public static void main(String[] args) throws RemoteException {
Master master = new Master(args[0], Integer.valueOf(args[1]));
Scanner scanner = new Scanner (System.in);
System.out.println("*Enter 'q' to stop master or 'd' to show the data of nodes:");
while(scanner.hasNext()) {
String text = scanner.next();
if(text.equals("q")) {
break;
} else if(text.equals("d")){
master.showNodesData();
}
}
master.stopMaster();
logger.info("Master stopped!");
}
public List<Node> getNodes() {
return nodes;
}
public void showNodesData(){
for (int i = 0; i < nodes.size(); i++) {
try {
System.out.println("Data from Node " + i + ": "
+ nodes.get(i).getInterface().executeSQLOnNode(
new ExecuteSQLOnNodeRequest("SELECT * FROM *;")
).getResult());
} catch (RemoteException e) {
ErrorHandler.handleError(e, false);
}
}
}
public void stopMaster(){
server.stopService(Services.MASTER, this);
}
@Override
public RegisterResponse register(RegisterRequest registerRequest) throws RemoteException {
ErrorEnum ok;
// Create node
Node newNode = new Node(registerRequest.getNode());
// Check status (uncomment when it's implemented in node)
// ok = newNode.checkStatus();
// if(!ok.equals(ErrorEnum.NO_ERROR)){
// return new RegisterResponse(ok);
synchronized (nodes) {
nodes.add(newNode);
}
logger.info("Node added.");
return new RegisterResponse(ErrorEnum.NO_ERROR);
}
@Override
public InsertMetadataResponse insertMetadata(InsertMetadataRequest insertMetadataRequest)
throws RemoteException {
List<NodeNodeInterface> nodes = new ArrayList<>(this.getNodes().size());
// Insert in all nodes (example)
for(Node n : this.getNodes()){
nodes.add((NodeNodeInterface) n.getInterface());
}
return new InsertMetadataResponse(nodes, ErrorEnum.NO_ERROR);
}
@Override
public SelectMetadataResponse selectMetadata(SelectMetadataRequest selectMetadataRequest)
throws RemoteException {
return null;
}
@Override
public UpdateMetadataResponse updateMetadata(UpdateMetadataRequest updateMetadataRequest)
throws RemoteException {
return null;
}
@Override
public DeleteMetadataResponse deleteMetadata(DeleteMetadataRequest deleteMetadataRequest)
throws RemoteException {
return null;
}
@Override
public TableMetadataResponse tableMetadata(TableMetadataRequest tableMetadataRequest)
throws RemoteException {
return null;
}
@Override
public ExecuteSQLResponse executeSQL(ExecuteSQLRequest executeSQLRequest) throws RemoteException {
String query = executeSQLRequest.getSql();
MasterNodeInterface node = nodes.get(selectNode()).getInterface();
ExecuteSQLOnNodeResponse result = node.executeSQLOnNode(
new ExecuteSQLOnNodeRequest(query));
ExecuteSQLResponse response;
if(result.getError().equals(ErrorEnum.NO_ERROR)){
response = new ExecuteSQLResponse(result.getResult());
} else {
response = new ExecuteSQLResponse(result.getError().toString());
}
return response;
}
/**
* Load balancer
* @return node chosen to run the query
*/
private synchronized int selectNode(){
Random random = new Random();
return random.nextInt(nodes.size());
}
} |
package pokeraidbot.domain;
import me.xdrop.fuzzywuzzy.model.ExtractedResult;
import org.apache.commons.lang3.StringUtils;
import pokeraidbot.domain.errors.GymNotFoundException;
import pokeraidbot.domain.errors.UserMessedUpException;
import java.util.*;
import java.util.stream.Collectors;
import static me.xdrop.fuzzywuzzy.FuzzySearch.extractTop;
import static org.apache.commons.lang3.StringUtils.containsIgnoreCase;
public class GymRepository {
private Map<String, Set<Gym>> gymsPerRegion = new HashMap<>();
private final LocaleService localeService;
public GymRepository(Map<String, Set<Gym>> gyms, LocaleService localeService) {
this.localeService = localeService;
for (String region : gyms.keySet()) {
Set<Gym> gymsForRegion = gyms.get(region);
this.gymsPerRegion.put(region, gymsForRegion);
}
}
public Gym search(String userName, String query, String region) {
if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(query)) {
throw new UserMessedUpException(userName, localeService.getMessageFor(LocaleService.GYM_SEARCH,
LocaleService.DEFAULT));
}
final Set<Gym> gyms = getAllGymsForRegion(region);
final Locale localeForUser = localeService.getLocaleForUser(userName);
final Optional<Gym> gym = get(query, region);
if (gym.isPresent()) {
return gym.get();
} else {
//70 seems like a reasonable cutoff here...
List<ExtractedResult> candidates = extractTop(query, gyms.stream().map(s -> s.getName()).collect(Collectors.toList()), 6, 70);
if (candidates.size() == 1) {
return findByName(candidates.iterator().next().getString(), region);
} else if (candidates.size() < 1) {
throw new GymNotFoundException(query, localeService, LocaleService.SWEDISH);
} else {
List<Gym> matchingPartial = getMatchingPartial(query, region, candidates);
if (matchingPartial.size() == 1) {
return matchingPartial.get(0);
}
if (candidates.size() <= 5) {
String possibleMatches = candidates.stream().map(s -> findByName(s.getString(), region).getName()).collect(Collectors.joining(", "));
throw new UserMessedUpException(userName,
localeService.getMessageFor(LocaleService.GYM_SEARCH_OPTIONS, localeForUser, possibleMatches));
} else {
throw new UserMessedUpException(userName, localeService.getMessageFor(LocaleService.GYM_SEARCH_MANY_RESULTS, localeForUser));
}
}
}
}
public Gym findByName(String name, String region) {
final Optional<Gym> gym = get(name, region);
if (!gym.isPresent()) {
throw new GymNotFoundException(name, localeService, LocaleService.SWEDISH);
}
return gym.get();
}
public Gym findById(String id, String region) {
for (Gym gym : getAllGymsForRegion(region)) {
if (gym.getId().equals(id))
return gym;
}
throw new GymNotFoundException("[No entry]", localeService, LocaleService.SWEDISH);
}
public Set<Gym> getAllGymsForRegion(String region) {
final Set<Gym> gyms = gymsPerRegion.get(region);
if (gyms == null || gyms.size() < 1) {
throw new RuntimeException(localeService.getMessageFor(LocaleService.GYM_CONFIG_ERROR, LocaleService.DEFAULT));
}
return gyms;
}
private Optional<Gym> get(String name, String region) {
return getAllGymsForRegion(region).stream().filter(s -> s.getName().equalsIgnoreCase(name)).findFirst();
}
private List<Gym> getMatchingPartial(String query, String region, List<ExtractedResult> candidates) {
List<Gym> mathingGyms = new ArrayList<>();
for (ExtractedResult result : candidates) {
if (containsIgnoreCase(result.getString(), query)) {
mathingGyms.add(findByName(result.getString(), region));
}
}
return mathingGyms;
}
} |
package scotty.database.parser;
import scotty.database.Context;
import scotty.database.Database;
import scotty.database.Instance;
import scotty.database.Type;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
/**
* Utility methods used by the database portions of Scotty.
*/
public final class Utilities {
private static final Logger LOGGER = Logger.getLogger(Utilities.class.getName());
private Utilities() {
}
/**
* Query a context for all the contexts within it that match a criteria.
*
* @param context The context to query.
* @param criteria The criteria to match.
* @return the list of matches in ranked order
*/
public static List<Context> query(Context context, Context criteria) {
List<Context> contexts = new LinkedList<>();
List<Ranked<Context>> results = rankedQuery(context, criteria);
for (Ranked<Context> ranked : results) {
contexts.add(ranked.getData());
}
return contexts;
}
/**
* Query a context for all the contexts within it that match a criteria.
*
* @param context The context to query
* @param criteria the criteria to match
* @return the results, with their associated ranks in ranked order
*/
public static List<Ranked<Context>> rankedQuery(Context context, Context criteria) {
List<Ranked<Context>> results = new LinkedList<>();
if (context.isContainer()) {
for (Context child : context.getContained().values()) {
results.addAll(rankedQuery(child, criteria));
}
} else {
float rank = context.similarity(criteria);
if (rank > Similarity.NOT_SIMILAR) {
results.add(new Ranked<>(rank, context.getAge(), context));
}
}
Collections.sort(results);
return results;
}
/**
* Print out the contents of a database, flattening all the inheritance to the instance level.
*
* @param database the database
* @param printStream the output stream
*/
public static void print(final Database database, final PrintStream printStream) {
print(database, printStream, null);
}
/**
* Print out the contents of a database, flattening all the inheritance to the instance level and
* showing the similarity score with the context passed in. Zero similarity matches are discarded.
*
* @param database the database
* @param printStream the output stream
* @param context the Context to compare instances to.
*/
public static void print(final Database database, final PrintStream printStream, final Context context) {
if (context != null) {
printStream.println("Context:");
List<String> attrNames = new LinkedList<>(context.keySet());
Collections.sort(attrNames);
for (String key : attrNames) {
printStream.format("%20s: %s\n", key, context.get(key));
}
}
List<Context> types = new LinkedList<>(database.getContained().values());
Collections.sort(types);
for (Context type : types) {
printStream.format("Type: %s\n", ((Type) type).getName());
List<Context> instances = new LinkedList<>(type.getContained().values());
Collections.sort(instances);
for (Context instance : instances) {
if (context == null) {
printStream.format("\tInstance: %s\n", ((Instance) instance).getName());
} else {
final float similarity = instance.similarity(context);
if (similarity == 0.0) {
continue;
}
printStream.format("\tInstance: %s\n", ((Instance) instance).getName());
printStream.format("\tSimilarity Score: %f\n", similarity);
}
List<String> attrNames = new LinkedList<>(instance.keySet());
Collections.sort(attrNames);
for (String key : attrNames) {
printStream.format("\t\t%20s: %s\n", key, instance.get(key));
}
}
}
}
/**
* Look up a resource as either file or failing that a resource from the jar.
*
* @param resource item name to look for
* @return return input stream or null if not found
*/
public static InputStream getResourceAsStream(String resource) {
try {
return new FileInputStream(resource);
} catch (FileNotFoundException e) {
LOGGER.fine("File not found: " + e);
}
InputStream inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream(resource);
if (inputStream == null) {
LOGGER.info("Failed to find " + resource + " as resource or file.");
}
return inputStream;
}
} |
package org.topcased.requirement.generic.importrequirement.ui;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormText;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;
import org.topcased.requirement.generic.importrequirement.Activator;
import org.topcased.requirement.generic.importrequirement.elements.Attribute;
import org.topcased.requirement.generic.importrequirement.elements.AttributeRequirement;
import org.topcased.requirement.generic.importrequirement.elements.AttributeSysml;
import org.topcased.requirement.generic.importrequirement.elements.AttributeUml;
import org.topcased.requirement.generic.importrequirement.elements.IStructuredContentProviderTree;
import org.topcased.requirement.generic.importrequirement.elements.Mapping;
import org.topcased.requirement.generic.importrequirement.elements.OwnerElement;
import org.topcased.requirement.generic.importrequirement.elements.RecognizedElement;
import org.topcased.requirement.generic.importrequirement.elements.RecognizedTree;
import org.topcased.requirement.generic.importrequirement.utils.Constants;
import org.topcased.requirement.generic.importrequirement.utils.Serializer;
/**
* The Class ImportRequirementWizardPageMapping.
*/
public class ImportRequirementWizardPageMapping extends WizardPage
{
/** The Constants PREFERENCE. */
public static final String PREFERENCE_FOR_LIST_ATTRIBUT = "value for list of attribut";
/** The Constant PREFERENCE_FOR_LIST_MAPPING. */
public static final String PREFERENCE_FOR_LIST_MAPPING = "value for list of mapping";
/** Page components *. */
private FormToolkit toolkit;
/** The form. */
private Form form;
/** The section. */
private Composite section;
/** The button remove attribute. */
private Button buttonRemoveAttribute;
/** The button map. */
private Button buttonMap;
/** The button remove mapping. */
private Button buttonRemoveMapping;
/** The button add attribute. */
private Button buttonAddAttribute;
/** The list for input format. */
private TreeViewer listFormat;
/** The tree. */
private RecognizedTree tree;
/** The List for attributes *. */
private ListViewer listViewerAttributes;
/** The list attributes. */
private Collection<Attribute> listAttributes;
/** The List for mapping*. */
private ListViewer listViewerMapping;
/** The list mapping. */
private Collection<Mapping> listMapping = new LinkedList<Mapping>();
/** Behavior Elements *. */
private RecognizedElement selectedRule;
/** The selected attribute. */
private Attribute selectedAttribute;
/** The selected mapping. */
private Mapping selectedMapping;
/** The model type. */
private String modelType;
/** The image add. */
private static Image imageAdd;
/** The image remove. */
private static Image imageRemove;
static
{
try
{
imageAdd = new Image(Display.getDefault(), Activator.getDefault().getBundle().getResource("icons/add.gif").openStream());
imageRemove = new Image(Display.getDefault(), Activator.getDefault().getBundle().getResource("icons/remove.gif").openStream());
}
catch (IOException e)
{
}
}
/**
* Instantiates a new import requirement wizard page mapping.
*
* @param pageName the page name
* @param t the t
* @param listAttributes the list attributes
* @param model the model
*/
protected ImportRequirementWizardPageMapping(String pageName, RecognizedTree t, Collection<Attribute> listAttributes, String model)
{
super(pageName);
tree = t;
this.listAttributes = listAttributes;
modelType = model;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.dialogs.IDialogPage#createControl(org.eclipse.swt.widgets.Composite)
*/
public void createControl(Composite parent)
{
Composite composite = new Composite(parent, SWT.NONE);
composite.setLayout(new FillLayout());
// setImageDescriptor(workbench.getSharedImages().getImageDescriptor(Wizard.DEFAULT_IMAGE));
this.setDescription("Requirement import from csv, docx, odt, ods or xlsx");
toolkit = new FormToolkit(composite.getDisplay());
form = toolkit.createForm(composite);
// create the base form
form.setText("Maping");
toolkit.decorateFormHeading(form);
GridLayout layout = new GridLayout(1, false);
layout.marginHeight = 5;
layout.marginWidth = 5;
form.getBody().setLayout(layout);
createSection();
setControl(composite);
}
/**
* Creates the section.
*/
private void createSection()
{
createDescriptionText(form.getBody());
section = createSection(form, "Mapping Requirement attributes", 4);
createRowForlabels(section);
createListFormat(section);
createMapButton(section);
createListAttributes(section);
createButtonsAttributes(section);
createListMapping(section);
createButtonRemoveMapping(section);
}
/**
* Creates the section.
*
* @param mform the mform
* @param title the title
* @param numColumns the num columns
*
* @return the composite
*/
private Composite createSection(Form mform, String title, int numColumns)
{
// Create section
Section section = toolkit.createSection(mform.getBody(), Section.TITLE_BAR | Section.EXPANDED);
section.setText(title);
// Create composite
Composite client = toolkit.createComposite(section);
section.setLayoutData(new GridData(GridData.FILL_BOTH));
// Add a grid layout
GridLayout layout = new GridLayout(numColumns, false);
layout.marginWidth = 1;
layout.marginHeight = 1;
client.setLayout(layout);
section.setClient(client);
return client;
}
/**
* Creates the description text.
*
* @param section2 the section2
*/
private void createDescriptionText(Composite section2)
{
FormText text = toolkit.createFormText(section2, false);
text.setText("<form><p>Use this page to <b>map</b> the section of your <b>document</b> with the <b>attributes</b> of the target model</p><p/></form>", true, true);
}
/**
* Creates the row forlabels.
*
* @param section the section
*/
private void createRowForlabels(Composite section)
{
// Create First Label
Label label = toolkit.createLabel(section, "Requirement identification");
label.setData(new GridData(SWT.FILL, SWT.TOP, true, false, 1, 1));
toolkit.createLabel(section, "");
// Create Second Label
Label label2 = toolkit.createLabel(section, "Attributes");
label2.setData(new GridData(SWT.FILL, SWT.TOP, true, false, 1, 1));
toolkit.createLabel(section, "");
}
/**
* Creates the list stereotypes.
*
* @param section2 the section2
*/
private void createListFormat(Composite section2)
{
// Create treeViewer
listFormat = new TreeViewer(section2, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
GridData data = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 2);
listFormat.getTree().setLayoutData(data);
// Set the label provider
listFormat.setLabelProvider(new LabelProvider()
{
public String getText(Object element)
{
// Return the label.
if (element instanceof String)
{
return (String) element;
}
else if (element instanceof RecognizedElement)
{
return ((RecognizedElement) element).getText();
}
else if (element instanceof RecognizedTree)
{
return "root";
}
return null;
}
});
// Set the content provider
listFormat.setContentProvider(new IStructuredContentProviderTree(false));
// Add inputs
listFormat.setInput(tree);
listFormat.refresh();
listFormat.addSelectionChangedListener(new ISelectionChangedListener()
{
private ISelection selection;
public void selectionChanged(SelectionChangedEvent event)
{
selection = listFormat.getSelection();
if (selection instanceof IStructuredSelection)
{
IStructuredSelection stru = (IStructuredSelection) selection;
// Get the selection
if (stru.getFirstElement() instanceof RecognizedElement)
{
selectedRule = (RecognizedElement) stru.getFirstElement();
}
}
}
});
}
/**
* Creates the map button.
*
* @param section the section
*/
private void createMapButton(Composite section)
{
buttonMap = toolkit.createButton(section, "<- Map ->", SWT.PUSH);
buttonMap.setLayoutData(new GridData(SWT.CENTER, SWT.CENTER, false, false, 1, 2));
buttonMap.addSelectionListener(new SelectionListener()
{
public void widgetDefaultSelected(SelectionEvent e)
{
}
public void widgetSelected(SelectionEvent e)
{
if (selectedAttribute != null && selectedRule != null && !selectedRule.isSelected() && selectedRule.getChildren() == null && listFormat.getSelection() != null
&& listViewerAttributes.getSelection() != null)
{
addMapping(selectedRule, selectedAttribute);
refreshLists();
listViewerMapping.refresh();
// Delete entry from lists
// if (tree.getChildren().contains(selectedRule))
// tree.getChildren().remove(selectedRule);
// listFormat.refresh();
// listAttributes.remove(selectedAttribute);
// listViewerAttributes.refresh();
}
}
});
}
/**
* Creates the buttons attributes.
*
* @param section the section
*/
private void createButtonsAttributes(Composite section)
{
// Create add button
buttonAddAttribute = toolkit.createButton(section, "", SWT.PUSH);
buttonAddAttribute.setLayoutData(new GridData(SWT.CENTER, SWT.BOTTOM, false, false));
buttonAddAttribute.setImage(imageAdd);
buttonAddAttribute.addSelectionListener(new SelectionListener()
{
public void widgetDefaultSelected(SelectionEvent e)
{
}
public void widgetSelected(SelectionEvent e)
{
NewAttributePopup dialog = new NewAttributePopup(getShell());
if (dialog.open() == Dialog.OK)
{
if (Constants.UML_EXTENSION.equals(modelType))
{
listAttributes.add(new AttributeUml(dialog.getAttributeName(), dialog.isReference(), "Requirement"));
}
else if (Constants.SYSML_EXTENSION.equals(modelType))
{
listAttributes.add(new AttributeSysml(dialog.getAttributeName(), dialog.isReference(), "Requirement"));
}
else
{
listAttributes.add(new AttributeRequirement(dialog.getAttributeName() == null || dialog.getAttributeName().length() == 0 ? "Text" : dialog.getAttributeName(), dialog.isReference(),dialog.getAttributeName() == null || dialog.getAttributeName().length() == 0, "Requirement"));
}
listViewerAttributes.refresh();
}
}
});
// Create remove button
buttonRemoveAttribute = toolkit.createButton(section, "", SWT.PUSH);
buttonRemoveAttribute.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, false, false));
buttonRemoveAttribute.setImage(imageRemove);
buttonRemoveAttribute.addSelectionListener(new SelectionListener()
{
public void widgetDefaultSelected(SelectionEvent e)
{
}
public void widgetSelected(SelectionEvent e)
{
listAttributes.remove(selectedAttribute);
listViewerAttributes.refresh();
buttonRemoveAttribute.setEnabled(false);
}
});
buttonRemoveAttribute.setEnabled(false);
}
/**
* Refresh lists.
*/
public void refreshLists()
{
this.listFormat.refresh();
this.listViewerAttributes.refresh();
}
/**
* Creates the list attributes.
*
* @param parent the parent
*/
protected void createListAttributes(Composite parent)
{
listViewerAttributes = new ListViewer(parent, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
GridData data = new GridData(SWT.FILL, SWT.FILL, true, false, 1, 2);
listViewerAttributes.getList().setLayoutData(data);
// Set the label provider
listViewerAttributes.setLabelProvider(new LabelProvider()
{
public String getText(Object element)
{
// Return the resolution's label.
if (element instanceof Attribute)
{
return ((Attribute) element).getName();
}
return null;
}
});
// Set the content provider
listViewerAttributes.setContentProvider(new IStructuredContentProvider()
{
public Object[] getElements(Object inputElement)
{
if (inputElement instanceof Collection)
{
List<Attribute> result = new LinkedList<Attribute>();
Collection< ? > collec = (Collection< ? >) inputElement;
// for all stereotypes
for (Object o : collec)
{
if (o instanceof Attribute)
{
result.add((Attribute) o);
}
}
return result.toArray();
}
return null;
}
public void dispose()
{
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput)
{
}
});
listViewerAttributes.addSelectionChangedListener(new ISelectionChangedListener()
{
private ISelection selection;
public void selectionChanged(SelectionChangedEvent event)
{
selection = listViewerAttributes.getSelection();
if (selection instanceof IStructuredSelection)
{
IStructuredSelection stru = (IStructuredSelection) selection;
if (stru.getFirstElement() instanceof Attribute)
{
// Get the selection
selectedAttribute = (Attribute) stru.getFirstElement();
// Enable remove button
buttonRemoveAttribute.setEnabled(true);
}
}
getWizard().getContainer().updateMessage();
getWizard().getContainer().updateButtons();
}
});
listViewerAttributes.setInput(listAttributes);
}
/**
* Creates the list mapping.
*
* @param section the section
*/
private void createListMapping(Composite section)
{
// Create label
Label label = toolkit.createLabel(section, "Mapping");
label.setData(new GridData(SWT.FILL, SWT.TOP, true, false, 4, 1));
toolkit.createLabel(section, "");
toolkit.createLabel(section, "");
toolkit.createLabel(section, "");
// Create list mapping
listViewerMapping = new ListViewer(section, SWT.SINGLE | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER);
GridData data = new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1);
listViewerMapping.getList().setLayoutData(data);
// Set the label provider
listViewerMapping.setLabelProvider(new LabelProvider()
{
public String getText(Object element)
{
// Return the resolution's label.
if (element instanceof Mapping)
{
return ((Mapping) element).toString();
}
return null;
}
});
// Set the content provider
listViewerMapping.setContentProvider(new IStructuredContentProvider()
{
public Object[] getElements(Object inputElement)
{
if (inputElement instanceof Collection)
{
List<Mapping> result = new LinkedList<Mapping>();
Collection< ? > collec = (Collection< ? >) inputElement;
// for all stereotypes
for (Object o : collec)
{
if (o instanceof Mapping)
{
result.add((Mapping) o);
}
}
return result.toArray();
}
return null;
}
public void dispose()
{
}
public void inputChanged(Viewer viewer, Object oldInput, Object newInput)
{
}
});
listViewerMapping.addSelectionChangedListener(new ISelectionChangedListener()
{
private ISelection selection;
public void selectionChanged(SelectionChangedEvent event)
{
selection = listViewerMapping.getSelection();
if (selection instanceof IStructuredSelection)
{
IStructuredSelection stru = (IStructuredSelection) selection;
if (stru.getFirstElement() instanceof Mapping)
{
// Get the selection
selectedMapping = (Mapping) stru.getFirstElement();
// Enable remove button
buttonRemoveMapping.setEnabled(true);
}
}
getWizard().getContainer().updateMessage();
getWizard().getContainer().updateButtons();
}
});
listViewerMapping.setInput(listMapping);
}
/**
* Creates the button remove mapping.
*
* @param section2 the section2
*/
private void createButtonRemoveMapping(Composite section2)
{
// Create remove button
buttonRemoveMapping = toolkit.createButton(section, "", SWT.PUSH);
buttonRemoveMapping.setLayoutData(new GridData(SWT.CENTER, SWT.TOP, false, false));
buttonRemoveMapping.setImage(imageRemove);
buttonRemoveMapping.addSelectionListener(new SelectionListener()
{
public void widgetDefaultSelected(SelectionEvent e)
{
}
public void widgetSelected(SelectionEvent e)
{
selectedMapping.getElement().setSelected(false);
listAttributes.add(selectedMapping.getAttribute());
listMapping.remove(selectedMapping);
listViewerMapping.refresh();
refreshLists();
buttonRemoveMapping.setEnabled(false);
// Add removed elements to inputs list
// tree.getChildren().add(selectedMapping.getElement());
// listFormat.refresh();
// listAttributes.add(selectedMapping.getAttribute());
// listViewerAttributes.refresh();
}
});
buttonRemoveMapping.setEnabled(false);
}
/**
* The mapping preferences are loaded only if the inputs are the same from last use if the input document type, the
* output model type, the profile or the stereotype Load Preferences from a previous use.
*/
public void loadPreferecencesMapping()
{
// Load preferences for attributes list
String pref = Activator.getDefault().getPluginPreferences().getString(PREFERENCE_FOR_LIST_MAPPING);
if (pref != null && pref.length() > 0)
{
Serializer<Collection<Mapping>> serializer = new Serializer<Collection<Mapping>>();
Collection<Mapping> paramDecoded = serializer.unSerialize(pref);
if (paramDecoded != null && paramDecoded.size() > 0)
{
listMapping.clear();
for (Iterator<Mapping> iterator = paramDecoded.iterator(); iterator.hasNext();)
{
Mapping mapping = iterator.next();
for (Iterator<Attribute> j = listAttributes.iterator(); j.hasNext();)
{
Attribute a = j.next();
for (Iterator<RecognizedElement> k = tree.getChildren().iterator(); k.hasNext();)
{
RecognizedElement r = k.next();
if (a.equals(mapping.getAttribute()) && r.getText().equals(mapping.getElement().getText()))
{
listMapping.add(new Mapping(r, a));
j.remove();
r.setSelected(true);
}
}
}
}
listViewerMapping.refresh();
listFormat.refresh();
listViewerAttributes.refresh();
}
}
}
/**
* This method will make visible or not the button according to the output model type.
*
* @param isRequirementModel the is requirement model
*/
public void setIsRequirementModel(boolean isRequirementModel)
{
if (isRequirementModel)
{
buttonAddAttribute.setVisible(true);
buttonRemoveAttribute.setVisible(true);
}
else
{
buttonAddAttribute.setVisible(false);
buttonRemoveAttribute.setVisible(false);
}
}
/**
* Clear list attributes.
*/
public void clearListAttributes()
{
listAttributes.clear();
listViewerAttributes.refresh();
}
/**
* Clear list mapping.
*/
public void clearListMapping()
{
listMapping.clear();
listViewerMapping.refresh();
}
// /// Getters
/**
* Gets the list attributes pref.
*
* @return the list attributes pref
*/
public String getListAttributesPref()
{
Serializer<Collection<Attribute>> serializer = new Serializer<Collection<Attribute>>();
return serializer.serialize(listAttributes);
}
/**
* Gets the list attributes.
*
* @return the list attributes
*/
public Collection<Attribute> getListAttributes()
{
return listAttributes;
}
/**
* Gets the list mapping pref.
*
* @return the list mapping pref
*/
public String getListMappingPref()
{
Serializer<Collection<Mapping>> serializer = new Serializer<Collection<Mapping>>();
return serializer.serialize(listMapping);
}
/**
* Gets the list mapping.
*
* @return the list mapping
*/
public Collection<Mapping> getListMapping()
{
return listMapping;
}
/**
* Load preference attributes.
*/
public void loadPreferenceAttributes()
{
// Load preferences for list of attributes
String pref = Activator.getDefault().getPluginPreferences().getString(PREFERENCE_FOR_LIST_ATTRIBUT);
if (pref != null && pref.length() > 0)
{
Serializer<Collection<Attribute>> serializer = new Serializer<Collection<Attribute>>();
Collection<Attribute> paramDecoded = serializer.unSerialize(pref);
if (paramDecoded != null && paramDecoded.size() > 0)
{
for (Iterator<Attribute> iterator = paramDecoded.iterator(); iterator.hasNext();)
{
Attribute next = (Attribute) iterator.next();
if ((Constants.SYSML_EXTENSION.equals(modelType) && "Requirement".equals(next.getSource())) || (Constants.UML_EXTENSION.equals(modelType) && "Class".equals(next.getSource()))
|| next instanceof AttributeRequirement)
{
listAttributes.add(next);
}
}
}
}
}
/**
* Adds the mapping.
*
* @param selectedRule the selected rule
* @param a the a
*/
private void addMapping(RecognizedElement selectedRule, Attribute a)
{
listMapping.add(new Mapping(selectedRule, a));
listAttributes.remove(a);
selectedRule.setSelected(true);
if (selectedRule.getParent() != null)
{
OwnerElement parent = selectedRule.getParent();
boolean toSelect = true;
if (parent instanceof RecognizedElement)
{
RecognizedElement rParent = (RecognizedElement) parent;
if (rParent.getChildren() != null)
{
for (RecognizedElement r : rParent.getChildren())
{
toSelect &= r.isSelected();
}
}
if (toSelect)
{
rParent.setSelected(true);
}
}
}
}
} |
package seedu.address.model;
import java.util.Set;
import java.util.Stack;
import java.util.logging.Logger;
import javafx.collections.transformation.FilteredList;
import seedu.address.commons.core.ComponentManager;
import seedu.address.commons.core.LogsCenter;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.commons.events.model.AddressBookChangedEvent;
import seedu.address.commons.util.CollectionUtil;
import seedu.address.commons.util.StringUtil;
import seedu.address.model.task.ReadOnlyTask;
import seedu.address.model.task.Task;
import seedu.address.model.task.UniqueTaskList;
import seedu.address.model.task.UniqueTaskList.TaskNotFoundException;
/**
* Represents the in-memory model of the address book data.
* All changes to any model should be synchronized.
*/
public class ModelManager extends ComponentManager implements Model {
private static final Logger logger = LogsCenter.getLogger(ModelManager.class);
private final AddressBook addressBook;
private final FilteredList<ReadOnlyTask> filteredTasks;
private final Stack<String> stackOfUndo;
private final Stack<ReadOnlyTask> stackOfDeletedTasksAdd;
private final Stack<ReadOnlyTask> stackOfDeletedTasks;
private final Stack<Integer> stackOfDeletedTaskIndex;
/**
* Initializes a ModelManager with the given addressBook and userPrefs.
*/
public ModelManager(ReadOnlyAddressBook addressBook, UserPrefs userPrefs) {
super();
assert !CollectionUtil.isAnyNull(addressBook, userPrefs);
stackOfUndo = new Stack<>();
stackOfDeletedTasksAdd = new Stack<>();
stackOfDeletedTasks = new Stack<>();
stackOfDeletedTaskIndex = new Stack<>();
logger.fine("Initializing with address book: " + addressBook + " and user prefs " + userPrefs);
this.addressBook = new AddressBook(addressBook);
filteredTasks = new FilteredList<>(this.addressBook.getTaskList());
}
public ModelManager() {
this(new AddressBook(), new UserPrefs());
}
@Override
public void resetData(ReadOnlyAddressBook newData) {
addressBook.resetData(newData);
indicateAddressBookChanged();
}
@Override
public ReadOnlyAddressBook getAddressBook() {
return addressBook;
}
/** Raises an event to indicate the model has changed */
private void indicateAddressBookChanged() {
raise(new AddressBookChangedEvent(addressBook));
}
@Override
public synchronized int deleteTask(ReadOnlyTask target) throws TaskNotFoundException {
int indexRemoved = addressBook.removeTask(target);
indicateAddressBookChanged();
return indexRemoved;
}
@Override
public synchronized void addTask(Task task) throws UniqueTaskList.DuplicateTaskException {
addressBook.addTask(task);
updateFilteredListToShowAll();
indicateAddressBookChanged();
}
@Override
public void updateTask(int filteredTaskListIndex, ReadOnlyTask editedTask)
throws UniqueTaskList.DuplicateTaskException {
assert editedTask != null;
int taskIndex = filteredTasks.getSourceIndex(filteredTaskListIndex);
addressBook.updateTask(taskIndex, editedTask);
indicateAddressBookChanged();
}
@Override
public Stack<String> getUndoStack() {
return stackOfUndo;
}
@Override
public Stack<ReadOnlyTask> getDeletedStackOfTasksAdd() {
return stackOfDeletedTasksAdd;
}
@Override
public Stack<ReadOnlyTask> getDeletedStackOfTasks() {
return stackOfDeletedTasks;
}
@Override
public Stack<Integer> getDeletedStackOfTasksIndex() {
return stackOfDeletedTaskIndex;
}
@Override
public UnmodifiableObservableList<ReadOnlyTask> getFilteredTaskList() {
return new UnmodifiableObservableList<>(filteredTasks);
}
@Override
public void updateFilteredListToShowAll() {
filteredTasks.setPredicate(null);
}
@Override
public void updateFilteredTaskList(Set<String> keywords) {
updateFilteredTaskList(new PredicateExpression(new NameQualifier(keywords)));
}
private void updateFilteredTaskList(Expression expression) {
filteredTasks.setPredicate(expression::satisfies);
}
interface Expression {
boolean satisfies(ReadOnlyTask task);
@Override
String toString();
}
private class PredicateExpression implements Expression {
private final Qualifier qualifier;
PredicateExpression(Qualifier qualifier) {
this.qualifier = qualifier;
}
@Override
public boolean satisfies(ReadOnlyTask task) {
return qualifier.run(task);
}
@Override
public String toString() {
return qualifier.toString();
}
}
interface Qualifier {
boolean run(ReadOnlyTask task);
@Override
String toString();
}
private class NameQualifier implements Qualifier {
private Set<String> nameKeyWords;
NameQualifier(Set<String> nameKeyWords) {
this.nameKeyWords = nameKeyWords;
}
@Override
public boolean run(ReadOnlyTask task) {
return nameKeyWords.stream()
.filter(keyword -> StringUtil.containsWordIgnoreCase(task.getContent().fullContent, keyword))
.findAny()
.isPresent();
}
@Override
public String toString() {
return "name=" + String.join(", ", nameKeyWords);
}
}
} |
package tbax.baxshops.commands;
import org.bukkit.inventory.ItemStack;
import org.jetbrains.annotations.NotNull;
import tbax.baxshops.*;
import tbax.baxshops.errors.PrematureAbortException;
import tbax.baxshops.serialization.ItemNames;
public final class CmdRemove extends BaxShopCommand
{
@Override
public @NotNull String getName()
{
return "remove";
}
@Override
public @NotNull String[] getAliases()
{
return new String[]{"remove","rm"};
}
@Override
public String getPermission()
{
return "shops.owner";
}
@Override
public CommandHelp getHelp(@NotNull ShopCmdActor actor) throws PrematureAbortException
{
CommandHelp help = super.getHelp(actor);
help.setDescription("remove an item from the shop");
help.setArgs(
new CommandHelpArgument("item", "the name or entry number of the item to remove", true)
);
return help;
}
@Override
public boolean hasValidArgCount(@NotNull ShopCmdActor actor)
{
return actor.getNumArgs() == 2;
}
@Override
public boolean requiresSelection(@NotNull ShopCmdActor actor)
{
return true;
}
@Override
public boolean requiresOwner(@NotNull ShopCmdActor actor)
{
return true;
}
@Override
public boolean requiresPlayer(@NotNull ShopCmdActor actor)
{
return true;
}
@Override
public boolean requiresItemInHand(@NotNull ShopCmdActor actor)
{
return false;
}
@Override
public void onCommand(@NotNull ShopCmdActor actor) throws PrematureAbortException // tested OK 3/30/19
{
BaxShop shop = actor.getShop();
BaxEntry entry = actor.getArgEntry(1);
if (entry == null) {
actor.exitError(Resources.NOT_FOUND_SHOPITEM);
}
assert shop != null;
if (!shop.hasFlagInfinite() && entry.getAmount() > 0) {
ItemStack stack = entry.toItemStack();
int overflow = actor.giveItem(stack, false);
entry.subtract(stack.getAmount() - overflow);
if (overflow > 0) {
actor.sendMessage(Resources.SOME_ROOM, stack.getAmount() - overflow, entry.getName());
}
else {
actor.sendMessage("%s %s added to your inventory.",
Format.itemName(stack.getAmount(), ItemNames.getName(entry)),
stack.getAmount() == 1 ? "was" : "were");
}
}
if (entry.getAmount() > 0) {
actor.sendWarning("The shop entry was not removed");
}
else {
shop.remove(entry);
actor.sendMessage("The shop entry was removed.");
}
}
} |
package com.mygdx.seabattle.views;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
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.*;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.mygdx.seabattle.SeaBattle;
public class MainMenuScreen implements Screen{
private SpriteBatch batch;
private Stage stage;
private TextField nickNameField;
private SeaBattle seaBattleGame;
private Skin skin;
private int width, height;
private String defaultNickname = randomNickname();
public MainMenuScreen(SeaBattle seaBattleGame) {
this.seaBattleGame = seaBattleGame;
width = seaBattleGame.getWidth();
height = seaBattleGame.getHeight();
skin = seaBattleGame.getSkin();
}
@Override
public void show() {
batch = new SpriteBatch();
stage = new Stage();
Gdx.input.setInputProcessor(stage); // So that the stage can receive input-events like button-clicks
/** Create menu elements **/
Label nickNameLabel = new Label("Enter nickname:", skin);
nickNameField = new TextField("", skin);
TextButton playButton = new TextButton("Find match", skin);
TextButton exitButton = new TextButton("Exit", skin);
TextButton howToPlayButton = new TextButton("How to play", skin);
/** Calculate and set element sizes **/
double nickNameFieldWidth = nickNameLabel.getWidth(), nickNameFieldHeight = height/38.4;
nickNameField.setSize((float) nickNameFieldWidth, (float) nickNameFieldHeight);
double bW = width/2.4, bH = (height - (7* seaBattleGame.getBorder()) - seaBattleGame.getTitleImg().getHeight() - seaBattleGame.getShipImg().getHeight() - nickNameLabel.getHeight())/3;
float btnSizeW = (float) bW;
float btnSizeH = (float) bH;
playButton.setSize(btnSizeW, btnSizeH);
exitButton.setSize(btnSizeW, btnSizeH);
howToPlayButton.setSize(btnSizeW, btnSizeH);
/** Calculate and set element positions **/
float nickNameLabelPosX = (width/2) - nickNameLabel.getWidth() - (seaBattleGame.getBorder()/2);
float nickNameLabelPosY = seaBattleGame.getShipImg().getY() - seaBattleGame.getBorder() - nickNameLabel.getHeight();
nickNameLabel.setPosition(nickNameLabelPosX, nickNameLabelPosY);
float nickNameFieldPosX = (width/2) + (seaBattleGame.getBorder()/2);
float nickNameFieldPosY = nickNameLabelPosY + 5;
nickNameField.setPosition(nickNameFieldPosX, nickNameFieldPosY);
float playButtonPosX = (width/2) - (btnSizeW/2);
float playButtonPosY = nickNameLabelPosY - (seaBattleGame.getBorder()) - btnSizeH;
playButton.setPosition(playButtonPosX, playButtonPosY);
float howToPlayButtonPosY = playButtonPosY - seaBattleGame.getBorder() - btnSizeH;
howToPlayButton.setPosition(playButtonPosX, howToPlayButtonPosY);
float exitButtonPosY = howToPlayButtonPosY - seaBattleGame.getBorder() - btnSizeH;
exitButton.setPosition(playButtonPosX, exitButtonPosY);
/** Add groups and elements to the stage **/
stage.addActor(seaBattleGame.getBackground());
seaBattleGame.getBackground().setFillParent(true);
stage.addActor(seaBattleGame.getTitleImg());
stage.addActor(seaBattleGame.getShipImg());
stage.addActor(nickNameLabel);
stage.addActor(nickNameField);
nickNameField.setMessageText(defaultNickname);
stage.addActor(playButton);
stage.addActor(howToPlayButton);
stage.addActor(exitButton);
/** Add listeners **/
playButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
String nickName = nickNameField.getText();
if (nickName.length() == 0) {
nickName = defaultNickname;
}
seaBattleGame.findMatch(nickName);
}
});
howToPlayButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
seaBattleGame.setTutorialScreen();
}
});
exitButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
seaBattleGame.exit();
}
});
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.enableBlending();
batch.begin();
stage.draw();
batch.end();
}
@Override
public void dispose() {
stage.dispose();
batch.dispose();
}
@Override
public void resize(int width, int height) {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
dispose();
}
private String randomNickname() {
String[] adjectives = {"Awesome", "Mighty", "Dark", "Mean", "Fearsome", "Big", "Cowardly", "Smart", "Hot", "Evil", "Angry", "Sweet"};
String[] nouns = {"Beaver", "Captain", "Anchovy", "Pirate", "Gangster", "Boy", "Tim", "Knight", "Sirloin", "Mama", "Viking", "Champion"};
return adjectives[(int) (Math.random() * adjectives.length)] + nouns[(int) (Math.random() * nouns.length)] + (int) (Math.random() * 100);
}
} |
package org.eclipse.birt.report.item.crosstab.ui.views.attributes.provider;
import java.util.Iterator;
import java.util.List;
import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter;
import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler;
import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.AggregateOnBindingsFormHandleProvider;
import org.eclipse.birt.report.designer.util.DEUtil;
import org.eclipse.birt.report.item.crosstab.core.ICrosstabConstants;
import org.eclipse.birt.report.item.crosstab.core.de.CrosstabReportItemHandle;
import org.eclipse.birt.report.item.crosstab.core.de.DimensionViewHandle;
import org.eclipse.birt.report.item.crosstab.core.de.LevelViewHandle;
import org.eclipse.birt.report.item.crosstab.core.de.MeasureViewHandle;
import org.eclipse.birt.report.item.crosstab.core.de.internal.CrosstabModelUtil;
import org.eclipse.birt.report.item.crosstab.internal.ui.editors.model.CrosstabAdaptUtil;
import org.eclipse.birt.report.item.crosstab.ui.i18n.Messages;
import org.eclipse.birt.report.model.api.CommandStack;
import org.eclipse.birt.report.model.api.ExtendedItemHandle;
import org.eclipse.birt.report.model.api.activity.SemanticException;
import org.eclipse.birt.report.model.api.extension.IReportItem;
import org.eclipse.birt.report.model.api.olap.CubeHandle;
import org.eclipse.birt.report.model.api.olap.DimensionHandle;
import org.eclipse.birt.report.model.api.olap.LevelHandle;
import org.eclipse.birt.report.model.api.olap.TabularDimensionHandle;
public class CrosstabBindingsFormHandleProvider extends
AggregateOnBindingsFormHandleProvider
{
public CrosstabBindingsFormHandleProvider( )
{
super( );
}
public CrosstabBindingsFormHandleProvider( boolean bShowAggregation )
{
super( bShowAggregation );
}
private ExtendedItemHandle getExtendedItemHandle( )
{
return (ExtendedItemHandle) DEUtil.getInputFirstElement( input );
}
public void generateAllBindingColumns( )
{
CommandStack stack = SessionHandleAdapter.getInstance( )
.getCommandStack( );
stack.startTrans( Messages.getString( "CrosstabBindingRefresh.action.message" ) ); //$NON-NLS-1$
try
{
ExtendedItemHandle handle = getExtendedItemHandle( );
CrosstabReportItemHandle crosstab = (CrosstabReportItemHandle) handle.getReportItem( );
if ( handle.getCube( ) != null )
{
CubeHandle cube = getExtendedItemHandle( ).getCube( );
List dimensions = cube.getContents( CubeHandle.DIMENSIONS_PROP );
for ( Iterator iterator = dimensions.iterator( ); iterator.hasNext( ); )
{
DimensionHandle dimension = (DimensionHandle) iterator.next( );
//only generate used dimension
if(!isUsedDimension(crosstab,dimension))
{
continue;
}
if ( dimension instanceof TabularDimensionHandle
&& !dimension.isTimeType( ) )
{
generateDimensionBindings( handle,
dimension,
ICrosstabConstants.ROW_AXIS_TYPE );
}
else
{
generateDimensionBindings( handle,
dimension,
ICrosstabConstants.COLUMN_AXIS_TYPE );
}
}
for ( int i = 0; i < crosstab.getMeasureCount( ); i++ )
{
MeasureViewHandle measureView = crosstab.getMeasure( i );
String function = CrosstabModelUtil.getAggregationFunction( crosstab,
measureView.getCell( ) );
LevelHandle rowLevel = measureView.getCell( )
.getAggregationOnRow( );
LevelHandle colLevel = measureView.getCell( )
.getAggregationOnColumn( );
String aggregateRowName = rowLevel == null ? null
: rowLevel.getQualifiedName( );
String aggregateColumnName = colLevel == null ? null
: colLevel.getQualifiedName( );
CrosstabModelUtil.generateAggregation( crosstab,
measureView.getCell( ),
measureView,
function,
null,
aggregateRowName,
null,
aggregateColumnName );
}
}
stack.commit( );
}
catch ( SemanticException e )
{
stack.rollback( );
ExceptionHandler.handle( e );
}
}
private boolean isUsedDimension(CrosstabReportItemHandle crosstab,DimensionHandle dimension)
{
boolean result = true;
DimensionViewHandle viewHandle = crosstab.getDimension(dimension.getName());
if(viewHandle == null)
{
result = false;
}
return result;
}
private void generateDimensionBindings( ExtendedItemHandle handle,
DimensionHandle dimensionHandle, int type )
throws SemanticException
{
if ( dimensionHandle.getDefaultHierarchy( ).getLevelCount( ) > 0 )
{
IReportItem reportItem = handle.getReportItem( );
CrosstabReportItemHandle xtabHandle = (CrosstabReportItemHandle) reportItem;
LevelHandle[] levels = getLevelHandles( dimensionHandle );
for ( int j = 0; j < levels.length; j++ )
{
//only generate used
if(!isUsedLevelHandle(xtabHandle, levels[j]) )
{
continue;
}
CrosstabAdaptUtil.createColumnBinding( (ExtendedItemHandle) xtabHandle.getModelHandle( ),
levels[j] );
}
}
}
private boolean isUsedLevelHandle(CrosstabReportItemHandle xtabHandle,LevelHandle levelHandle)
{
boolean result = true;
LevelViewHandle viewHandle = xtabHandle.getLevel(levelHandle.getFullName());
if(viewHandle == null)
{
result = false;
}
return result;
}
private LevelHandle[] getLevelHandles( DimensionHandle dimensionHandle )
{
LevelHandle[] dimensionLevelHandles = new LevelHandle[dimensionHandle.getDefaultHierarchy( )
.getLevelCount( )];
for ( int i = 0; i < dimensionLevelHandles.length; i++ )
{
dimensionLevelHandles[i] = dimensionHandle.getDefaultHierarchy( )
.getLevel( i );
}
return dimensionLevelHandles;
}
} |
package io.spine.client;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.CanIgnoreReturnValue;
import io.spine.core.ActorContext;
import io.spine.core.CommandContext;
import io.spine.core.TenantId;
import io.spine.core.UserId;
import io.spine.time.ZoneOffset;
import io.spine.time.ZoneOffsets;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
import static io.spine.time.Time.getCurrentTime;
/**
* A factory for the various requests fired from the client-side by an actor.
*
* @author Alex Tymchenko
* @author Alexander Yevsyukov
*/
public class ActorRequestFactory {
private final UserId actor;
/**
* In case the zone offset is not defined, the current time zone offset value is set by default.
*/
private final ZoneOffset zoneOffset;
/**
* The ID of the tenant in a multitenant application.
*
* <p>This field is null in a single tenant application.
*/
@Nullable
private final TenantId tenantId;
protected ActorRequestFactory(Builder builder) {
this.actor = builder.actor;
this.zoneOffset = builder.zoneOffset;
this.tenantId = builder.tenantId;
}
public static Builder newBuilder() {
return new Builder();
}
public UserId getActor() {
return actor;
}
public ZoneOffset getZoneOffset() {
return zoneOffset;
}
@Nullable
public TenantId getTenantId() {
return tenantId;
}
/**
* Creates new factory with the same user and tenant ID, but with new time zone offset.
*
* @param zoneOffset the offset of the time zone
* @return new factory at new time zone
*/
public ActorRequestFactory switchTimezone(ZoneOffset zoneOffset) {
final ActorRequestFactory result = newBuilder().setActor(getActor())
.setZoneOffset(zoneOffset)
.setTenantId(getTenantId())
.build();
return result;
}
/**
* Retrieves an instance of {@link QueryFactory} for the actor configured for this
* {@code ActorRequestFactory}.
*
* @return an instance of {@link QueryFactory}
*/
public QueryFactory query() {
return new QueryFactory(this);
}
/**
* Retrieves an instance of {@link TopicFactory} for the actor configured for this
* {@code ActorRequestFactory}.
*
* @return an instance of {@link TopicFactory}
*/
public TopicFactory topic() {
return new TopicFactory(this);
}
/**
* Retrieves an instance of {@link CommandFactory} for the actor configured for this
* {@code ActorRequestFactory}.
*
* @return an instance of {@link CommandFactory}
*/
public CommandFactory command() {
return new CommandFactory(this);
}
/**
* @see CommandFactory#createContext()
*/
@VisibleForTesting
protected CommandContext createCommandContext() {
return command().createContext();
}
/**
* Creates an {@linkplain ActorContext actor context}, based on the factory properties.
*
* <p>Sets the timestamp value to the
* {@linkplain io.spine.time.Time#getCurrentTime() current time}.
*/
ActorContext actorContext() {
final ActorContext.Builder builder = ActorContext.newBuilder()
.setActor(actor)
.setTimestamp(getCurrentTime())
.setZoneOffset(zoneOffset);
if (tenantId != null) {
builder.setTenantId(tenantId);
}
return builder.build();
}
/**
* A builder for {@code ActorRequestFactory}.
*/
public static class Builder {
private UserId actor;
private ZoneOffset zoneOffset;
@Nullable
private TenantId tenantId;
public UserId getActor() {
return actor;
}
/**
* Sets the ID for the user generating commands.
*
* @param actor the ID of the user generating commands
*/
public Builder setActor(UserId actor) {
this.actor = checkNotNull(actor);
return this;
}
@Nullable
public ZoneOffset getZoneOffset() {
return zoneOffset;
}
/**
* Sets the time zone in which the user works.
*
* @param zoneOffset the offset of the timezone the user works in
*/
public Builder setZoneOffset(ZoneOffset zoneOffset) {
this.zoneOffset = checkNotNull(zoneOffset);
return this;
}
@Nullable
public TenantId getTenantId() {
return tenantId;
}
/**
* Sets the ID of a tenant in a multi-tenant application to which this user belongs.
*
* @param tenantId the ID of the tenant or null for single-tenant applications
*/
public Builder setTenantId(@Nullable TenantId tenantId) {
this.tenantId = tenantId;
return this;
}
/**
* Ensures that all the {@code Builder} parameters are set properly.
*
* <p>Returns {@code null}, as it is expected to be overridden by descendants.
*
* @return {@code null}
*/
@SuppressWarnings("ReturnOfNull") // It's fine for an abstract Builder.
@CanIgnoreReturnValue
public ActorRequestFactory build() {
checkNotNull(actor, "`actor` must be defined");
if (zoneOffset == null) {
setZoneOffset(ZoneOffsets.getDefault());
}
return new ActorRequestFactory(this);
}
}
} |
package org.gemoc.executionframework.engine.core;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Set;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EClassifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EOperation;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EcoreFactory;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.transaction.RecordingCommand;
import org.eclipse.emf.transaction.RollbackException;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.emf.transaction.impl.EMFCommandTransaction;
import org.eclipse.emf.transaction.impl.InternalTransactionalEditingDomain;
import org.eclipse.emf.transaction.util.TransactionUtil;
import org.gemoc.executionframework.engine.Activator;
import org.gemoc.executionframework.engine.mse.MseFactory;
import org.gemoc.executionframework.engine.mse.GenericMSE;
import org.gemoc.executionframework.engine.mse.LogicalStep;
import org.gemoc.executionframework.engine.mse.MSE;
import org.gemoc.executionframework.engine.mse.MSEModel;
import org.gemoc.executionframework.engine.mse.MSEOccurrence;
import org.gemoc.xdsmlframework.api.core.EngineStatus;
import org.gemoc.xdsmlframework.api.core.IExecutionContext;
import org.gemoc.xdsmlframework.api.core.ISequentialExecutionEngine;
import org.gemoc.xdsmlframework.api.engine_addon.IEngineAddon;
import fr.inria.diverse.trace.gemoc.api.IMultiDimensionalTraceAddon;
public abstract class AbstractSequentialExecutionEngine extends AbstractExecutionEngine implements ISequentialExecutionEngine {
private Runnable _runnable;
private MSEModel _actionModel;
private EMFCommandTransaction currentTransaction;
private Deque<LogicalStep> currentLogicalSteps = new ArrayDeque<LogicalStep>();
protected InternalTransactionalEditingDomain editingDomain;
private IMultiDimensionalTraceAddon traceAddon;
@Override
public void initialize(IExecutionContext executionContext) {
super.initialize(executionContext);
this.editingDomain = getEditingDomain(executionContext.getResourceModel().getResourceSet());
Set<IMultiDimensionalTraceAddon> traceManagers = this.getAddonsTypedBy(IMultiDimensionalTraceAddon.class);
if (!traceManagers.isEmpty())
this.traceAddon = traceManagers.iterator().next();
_runnable = new Runnable() {
@Override
public void run() {
try {
Runnable initializeModel = getInitializeModel();
if (initializeModel != null) {
initializeModel.run();
}
getEntryPoint().run();
Activator.getDefault().info("Execution finished");
notifyAboutToStop();
} finally {
setEngineStatus(EngineStatus.RunStatus.Stopped);
notifyEngineStopped();
// We always try to commit the last remaining transaction
commitCurrentTransaction();
}
}
};
}
private void cleanCurrentTransactionCommand() {
if (this.currentTransaction.getCommand() != null)
this.currentTransaction.getCommand().dispose();
}
@Override
public Deque<MSEOccurrence> getCurrentStack() {
Deque<MSEOccurrence> result = new ArrayDeque<MSEOccurrence>();
for (LogicalStep ls : currentLogicalSteps) {
result.add(ls.getMseOccurrences().get(0));
}
return result;
}
@Override
public MSEOccurrence getCurrentMSEOccurrence() {
if (currentLogicalSteps.size() > 0)
return currentLogicalSteps.getFirst().getMseOccurrences().get(0);
else
return null;
}
private static InternalTransactionalEditingDomain getEditingDomain(ResourceSet rs) {
TransactionalEditingDomain edomain = org.eclipse.emf.transaction.TransactionalEditingDomain.Factory.INSTANCE.getEditingDomain(rs);
if (edomain instanceof InternalTransactionalEditingDomain)
return (InternalTransactionalEditingDomain) edomain;
else
return null;
}
@Override
protected Runnable getRunnable() {
return _runnable;
}
private void notifyMSEOccurenceExecuted(MSEOccurrence occurrence) {
for (IEngineAddon addon : getExecutionContext().getExecutionPlatform().getEngineAddons()) {
try {
addon.mseOccurrenceExecuted(this, occurrence);
} catch (EngineStoppedException ese) {
Activator.getDefault().info("Addon has received stop command (" + addon + "), " + ese.getMessage(), ese);
stop();
} catch (Exception e) {
Activator.getDefault().error("Exception in Addon (" + addon + "), " + e.getMessage(), e);
}
}
}
private void notifyMSEOccurrenceAboutToStart(MSEOccurrence occurrence) {
for (IEngineAddon addon : getExecutionContext().getExecutionPlatform().getEngineAddons()) {
try {
addon.aboutToExecuteMSEOccurrence(this, occurrence);
} catch (EngineStoppedException ese) {
Activator.getDefault().info("Addon has received stop command (" + addon + "), " + ese.getMessage(), ese);
stop();
} catch (Exception e) {
Activator.getDefault().error("Exception in Addon (" + addon + "), " + e.getMessage(), e);
}
}
}
private EMFCommandTransaction createTransaction(InternalTransactionalEditingDomain editingDomain, RecordingCommand command) {
return new EMFCommandTransaction(command, editingDomain, null);
}
private void commitCurrentTransaction() {
if (currentTransaction != null) {
try {
currentTransaction.commit();
} catch (RollbackException t) {
cleanCurrentTransactionCommand();
// Extracting the real error from the RollbackException
Throwable realT = t.getStatus().getException();
// And we put it inside our own sort of exception, as a cause
SequentialExecutionException enclosingException = new SequentialExecutionException(getCurrentMSEOccurrence(), realT);
enclosingException.initCause(realT);
throw enclosingException;
}
currentTransaction = null;
}
}
private void startNewTransaction(InternalTransactionalEditingDomain editingDomain, RecordingCommand command) {
currentTransaction = createTransaction(editingDomain, command);
try {
currentTransaction.start();
} catch (InterruptedException e) {
cleanCurrentTransactionCommand();
command.dispose();
SequentialExecutionException enclosingException = new SequentialExecutionException(getCurrentMSEOccurrence(), e);
enclosingException.initCause(e);
throw enclosingException;
}
}
private LogicalStep createLogicalStep(EObject caller, String className, String methodName) {
LogicalStep logicalStep = MseFactory.eINSTANCE.createLogicalStep();
MSE mse = findOrCreateMSE(caller, className, methodName);
MSEOccurrence occurrence = null;
if (traceAddon == null) {
occurrence = MseFactory.eINSTANCE.createMSEOccurrence();
occurrence.setLogicalStep(logicalStep);
occurrence.setMse(mse);
} else {
occurrence = traceAddon.getFactory().createMSEOccurrence(mse, new ArrayList<Object>(), new ArrayList<Object>());
occurrence.setLogicalStep(logicalStep);
}
currentLogicalSteps.push(logicalStep);
return logicalStep;
}
private boolean isInLogicalStep() {
boolean containsNotNull = false;
for (LogicalStep ls : currentLogicalSteps) {
if (ls != null && ls.getMseOccurrences().get(0) != null) {
containsNotNull = true;
break;
}
}
return !currentLogicalSteps.isEmpty() && containsNotNull;
}
private static String getFQN(EClassifier c, String separator) {
EPackage p = c.getEPackage();
if (p != null) {
return getEPackageFQN(p, separator) + separator + c.getName();
} else {
return c.getName();
}
}
private static String getEPackageFQN(EPackage p, String separator) {
EPackage superP = p.getESuperPackage();
if (superP != null) {
return getEPackageFQN(superP, separator) + separator + p.getName();
} else {
return p.getName();
}
}
private EOperation findOperation(EObject object, String className, String methodName) {
// We try to find the corresponding EOperation in the execution
// metamodel
for (EOperation operation : object.eClass().getEAllOperations()) {
// TODO !!! this is not super correct yet as overloading allows the
// definition of 2 methods with the same name !!!
if (operation.getName().equalsIgnoreCase(methodName)) {
return operation;
}
}
// If we didn't find it, we try to find the class that should contain
// this operation
EClass containingEClass = null;
if (getFQN(object.eClass(), "").equalsIgnoreCase(className))
containingEClass = object.eClass();
else
for (EClass candidate : object.eClass().getEAllSuperTypes()) {
if (getFQN(candidate, "").equalsIgnoreCase(className))
containingEClass = candidate;
}
// Then we create the missing operation (VERY approximatively)
EOperation operation = EcoreFactory.eINSTANCE.createEOperation();
if (containingEClass != null)
containingEClass.getEOperations().add(operation);
operation.setName(methodName);
return operation;
}
public MSE findOrCreateMSE(EObject caller, String className, String methodName) {
EOperation operation = findOperation(caller, className, methodName);
// TODO Should be created somewhere before...
// at some point didier had written some code to serialize it... I think
if (_actionModel == null) {
_actionModel = MseFactory.eINSTANCE.createMSEModel();
}
if (_actionModel != null) {
for (MSE existingMSE : _actionModel.getOwnedMSEs()) {
if (existingMSE.getCaller().equals(caller) && ((existingMSE.getAction() != null && existingMSE.getAction().equals(operation)) || (existingMSE.getAction() == null && operation == null))) {
// no need to create one, we already have it
return existingMSE;
}
}
}
// let's create a MSE
final GenericMSE mse = MseFactory.eINSTANCE.createGenericMSE();
mse.setCallerReference(caller);
mse.setActionReference(operation);
if (operation != null)
mse.setName("MSE_" + caller.getClass().getSimpleName() + "_" + operation.getName());
else
mse.setName("MSE_" + caller.getClass().getSimpleName() + "_" + methodName);
// and add it for possible reuse
if (_actionModel != null) {
if (_actionModel.eResource() != null) {
TransactionUtil.getEditingDomain(_actionModel.eResource());
RecordingCommand command = new RecordingCommand(TransactionUtil.getEditingDomain(_actionModel.eResource()), "Saving new MSE ") {
@Override
protected void doExecute() {
_actionModel.getOwnedMSEs().add(mse);
try {
_actionModel.eResource().save(null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
TransactionUtil.getEditingDomain(_actionModel.eResource()).getCommandStack().execute(command);
}
} else {
_actionModel.getOwnedMSEs().add(mse);
}
return mse;
}
/**
* To be called just before each execution step by an implementing engine.
*/
protected void beforeExecutionStep(Object caller, String className, String operationName) {
// We will trick the transaction with an empty command. This most
// probably make rollbacks impossible, but at least we can manage
// transactions the way we want.
RecordingCommand rc = new RecordingCommand(editingDomain) {
@Override
protected void doExecute() {
}
};
beforeExecutionStep(caller, className, operationName, rc);
rc.execute();
}
private void stopExecutionIfAsked() {
// If the engine is stopped, we use this call to stop the execution
if (_isStopped) {
// notification occurs only if not already stopped
notifyAboutToStop();
throw new EngineStoppedException("Execution stopped.");
}
}
/**
* To be called just after each execution step by an implementing engine. If
* the step was done through a RecordingCommand, it can be given.
*/
protected void beforeExecutionStep(Object caller, String className, String operationName, RecordingCommand rc) {
try {
stopExecutionIfAsked();
// We end any running transaction
commitCurrentTransaction();
if (caller != null && caller instanceof EObject && editingDomain != null) {
// Call expected to be done from an EMF model, hence EObjects
EObject caller_cast = (EObject) caller;
// We create a logical step with a single mse occurrence
LogicalStep logicalStep = createLogicalStep(caller_cast, className, operationName);
// We notify addons
notifyAboutToExecuteLogicalStep(logicalStep);
notifyMSEOccurrenceAboutToStart(logicalStep.getMseOccurrences().get(0));
}
// We start a new transaction
startNewTransaction(editingDomain, rc);
}
// In case of error, we dispose recording commands to be sure to remove
// notifiers
catch (Throwable t) {
cleanCurrentTransactionCommand();
rc.dispose();
throw t;
}
}
/**
* To be called just after each execution step by an implementing engine.
*/
protected void afterExecutionStep() {
RecordingCommand emptyrc = null;
try {
LogicalStep logicalStep = currentLogicalSteps.pop();
// We commit the transaction (which might be a different one
// than the one created earlier, or null if two operations
// end successively)
commitCurrentTransaction();
// We notify addons that the MSE occurrence ended.
notifyMSEOccurenceExecuted(logicalStep.getMseOccurrences().get(0));
notifyLogicalStepExecuted(logicalStep);
// If we are still in the middle of a step, we start a new
// transaction with an empty command (since we can't have command
// containing the remainder of the previous step),
if (isInLogicalStep()) {
emptyrc = new RecordingCommand(editingDomain) {
@Override
protected void doExecute() {
}
};
startNewTransaction(editingDomain, emptyrc);
emptyrc.execute();
}
engineStatus.incrementNbLogicalStepRun();
stopExecutionIfAsked();
}
// In case of error, we dispose recording commands to be sure to remove
// notifiers
catch (Throwable t) {
cleanCurrentTransactionCommand();
if (emptyrc != null)
emptyrc.dispose();
throw t;
}
}
} |
package io.spine.client;
import com.google.common.testing.NullPointerTester;
import com.google.protobuf.DoubleValue;
import com.google.protobuf.StringValue;
import com.google.protobuf.Timestamp;
import io.spine.client.ColumnFilter.Operator;
import io.spine.protobuf.AnyPacker;
import org.junit.Test;
import java.util.Calendar;
import java.util.concurrent.atomic.AtomicInteger;
import static io.spine.base.Time.getCurrentTime;
import static io.spine.client.ColumnFilter.Operator.EQUAL;
import static io.spine.client.ColumnFilter.Operator.GREATER_OR_EQUAL;
import static io.spine.client.ColumnFilter.Operator.GREATER_THAN;
import static io.spine.client.ColumnFilter.Operator.LESS_OR_EQUAL;
import static io.spine.client.ColumnFilter.Operator.LESS_THAN;
import static io.spine.client.ColumnFilters.all;
import static io.spine.client.ColumnFilters.either;
import static io.spine.client.ColumnFilters.eq;
import static io.spine.client.ColumnFilters.ge;
import static io.spine.client.ColumnFilters.gt;
import static io.spine.client.ColumnFilters.le;
import static io.spine.client.ColumnFilters.lt;
import static io.spine.client.CompositeColumnFilter.CompositeOperator;
import static io.spine.client.CompositeColumnFilter.CompositeOperator.ALL;
import static io.spine.client.CompositeColumnFilter.CompositeOperator.EITHER;
import static io.spine.protobuf.AnyPacker.pack;
import static io.spine.protobuf.TypeConverter.toAny;
import static io.spine.test.Tests.assertHasPrivateParameterlessCtor;
import static io.spine.test.Verify.assertContainsAll;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* @author Dmytro Dashenkov
*/
public class ColumnFiltersShould {
private static final String COLUMN_NAME = "preciseColumn";
private static final Timestamp COLUMN_VALUE = getCurrentTime();
private static final String ENUM_COLUMN_NAME = "enumColumn";
private static final Operator ENUM_COLUMN_VALUE = EQUAL;
@Test
public void have_private_util_ctor() {
assertHasPrivateParameterlessCtor(ColumnFilters.class);
}
@Test
public void not_accept_nulls() {
new NullPointerTester()
.setDefault(Timestamp.class, Timestamp.getDefaultInstance())
.setDefault(ColumnFilter.class, ColumnFilter.getDefaultInstance())
.testAllPublicStaticMethods(ColumnFilters.class);
}
@Test
public void create_EQUALS_instances() {
checkCreatesInstance(eq(COLUMN_NAME, COLUMN_VALUE), EQUAL);
}
@Test
public void create_GREATER_THAN_instances() {
checkCreatesInstance(gt(COLUMN_NAME, COLUMN_VALUE), GREATER_THAN);
}
@Test
public void create_GREATER_OR_EQUAL_instances() {
checkCreatesInstance(ge(COLUMN_NAME, COLUMN_VALUE), GREATER_OR_EQUAL);
}
@Test
public void create_LESS_THAN_instances() {
checkCreatesInstance(lt(COLUMN_NAME, COLUMN_VALUE), LESS_THAN);
}
@Test
public void create_LESS_OR_EQUAL_instances() {
checkCreatesInstance(le(COLUMN_NAME, COLUMN_VALUE), LESS_OR_EQUAL);
}
@Test
public void create_EQUALS_instances_for_enums() {
final ColumnFilter filter = eq(ENUM_COLUMN_NAME, ENUM_COLUMN_VALUE);
assertEquals(ENUM_COLUMN_NAME, filter.getColumnName());
assertEquals(toAny(ENUM_COLUMN_VALUE), filter.getValue());
assertEquals(EQUAL, filter.getOperator());
}
@Test
public void create_ALL_grouping_instances() {
final ColumnFilter[] filters = {
le(COLUMN_NAME, COLUMN_VALUE),
ge(COLUMN_NAME, COLUMN_VALUE)
};
checkCreatesInstance(all(filters[0], filters[1]), ALL, filters);
}
@Test
public void create_EITHER_grouping_instances() {
final ColumnFilter[] filters = {
lt(COLUMN_NAME, COLUMN_VALUE),
gt(COLUMN_NAME, COLUMN_VALUE)
};
checkCreatesInstance(either(filters[0], filters[1]), EITHER, filters);
}
@Test
public void create_ordering_filters_for_numbers() {
final double number = 3.14;
final ColumnFilter filter = le("doubleColumn", number);
assertNotNull(filter);
assertEquals(LESS_OR_EQUAL, filter.getOperator());
final DoubleValue value = AnyPacker.unpack(filter.getValue());
assertEquals(number, value.getValue(), 0.0);
}
@Test
public void create_ordering_filters_for_strings() {
final String string = "abc";
final ColumnFilter filter = gt("stringColumn", string);
assertNotNull(filter);
assertEquals(GREATER_THAN, filter.getOperator());
final StringValue value = AnyPacker.unpack(filter.getValue());
assertEquals(string, value.getValue());
}
@Test(expected = IllegalArgumentException.class)
public void fail_to_create_ordering_filters_for_enums() {
ge(ENUM_COLUMN_NAME, ENUM_COLUMN_VALUE);
}
@Test(expected = IllegalArgumentException.class)
public void fail_to_create_ordering_filters_for_non_primitive_numbers() {
final AtomicInteger number = new AtomicInteger(42);
ge("atomicColumn", number);
}
@Test(expected = IllegalArgumentException.class)
public void fail_to_create_ordering_filters_for_not_supported_types() {
final Comparable<?> value = Calendar.getInstance(); // Comparable but not supported
le("invalidColumn", value);
}
private static void checkCreatesInstance(ColumnFilter filter,
Operator operator) {
assertEquals(COLUMN_NAME, filter.getColumnName());
assertEquals(pack(COLUMN_VALUE), filter.getValue());
assertEquals(operator, filter.getOperator());
}
private static void checkCreatesInstance(CompositeColumnFilter filter,
CompositeOperator operator,
ColumnFilter[] groupedFilters) {
assertEquals(operator, filter.getOperator());
assertContainsAll(filter.getFilterList(), groupedFilters);
}
} |
package uk.co.CyniCode.CyniChat;
import java.util.logging.Logger;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import uk.co.CyniCode.CyniChat.Chatting.ServerChatListener;
import uk.co.CyniCode.CyniChat.Command.AfkCommand;
import uk.co.CyniCode.CyniChat.Command.ChCommand;
import uk.co.CyniCode.CyniChat.Command.MeCommand;
import uk.co.CyniCode.CyniChat.Command.MsgCommand;
import uk.co.CyniCode.CyniChat.Command.QmCommand;
import uk.co.CyniCode.CyniChat.Command.RCommand;
import uk.co.CyniCode.CyniChat.bungee.BungeeChannelProxy;
import uk.co.CyniCode.CyniChat.routing.ChatRouter;
/**
* Base class for CyniChat. Main parts are the onEnable(), onDisable(), and the print areas at the moment.
* @author Matthew Ball
*
*/
public class CyniChat extends JavaPlugin{
public Logger log = Logger.getLogger("Minecraft");
public static IRCManager PBot;
public static String version;
public static String name;
public static String Server;
public static CyniChat self = null;
public static Permission perms = null;
public static Boolean JSON = false;
public static Boolean SQL = false;
public static Boolean IRC = false;
public static Boolean bungee = false;
public static BungeeChannelProxy bungeeInstance = null;
public static String host;
public static String username;
public static String password ;
public static int port;
public static String database;
public static String prefix;
public static String def_chan;
public static boolean debug;
private static PluginManager pm;
public static int counter;
/**
* Is this command being used by bukkit as far as it knows?
* @param comm : The command we're checking off
* @return true if it does exist, false if it doesn't
*/
public static boolean ifCommandExists( String comm ) {
if ( self.getServer().getPluginCommand( comm ) == null )
return false;
return true;
}
/**
* This is the onEnable class for when the plugin starts up. Basic checks are run for the version, name and information of the plugin, then startup occurs.
*/
@Override
public void onEnable(){
//Lets get the basics ready.
version = this.getDescription().getVersion();
name = this.getDescription().getName();
self = this;
log.info(name + " version " + version + " has started...");
//Start up the managers and the configs and all that
pm = getServer().getPluginManager();
getConfig().options().copyDefaults(true);
saveConfig();
//Collect config data
def_chan = getConfig().getString("CyniChat.channels.default").toLowerCase();
if ( getConfig().getString("CyniChat.other.debug").equalsIgnoreCase("true") ) {
debug = true;
printInfo("Debugging enabled!");
} else {
debug = false;
printInfo("Debugging disabled!");
}
if ( getConfig().getString("CyniChat.other.data").equalsIgnoreCase("mysql") ) {
SQL = true;
printInfo("MySQL storage enabled!");
} else {
JSON = true;
printInfo("JSON storage enabled!");
}
if ( getConfig().getString( "CyniChat.other.bungee" ).equalsIgnoreCase( "true" ) ) {
bungee = true;
printInfo( "Bungee has been enabled" );
bungeeInstance = new BungeeChannelProxy( this );
ChatRouter.addRouter(ChatRouter.EndpointType.BUNGEE, bungeeInstance);
} else {
bungee = false;
printInfo( "Bungee has been disabled" );
}
DataManager.start( this );
DataManager.channelTable();
/*if ( getConfig().getString("CyniChat.other.irc").equalsIgnoreCase("true") ) {
printInfo( "Starting IRC..." );
try {
PBot = new IRCManager( this );
PBot.loadChannels( DataManager.returnAllChannels() );
IRC = true;
ChatRouter.addRouter(ChatRouter.EndpointType.IRC,PBot);
printInfo( "IRC has started." );
} catch ( Exception e ) {
printSevere( "IRC has failed. Switching off..." );
e.printStackTrace();
}
}*/
//Start the command
this.getCommand("ch").setExecutor(new ChCommand(this));
this.getCommand("afk").setExecutor(new AfkCommand() );
this.getCommand("qm").setExecutor(new QmCommand() );
this.getCommand("me").setExecutor(new MeCommand() );
this.getCommand("msg").setExecutor(new MsgCommand() );
this.getCommand("r").setExecutor(new RCommand() );
counter = 1;
if ( PermissionManager.setupPermissions( this ) == false ) {
killPlugin();
return;
}
//Register the listeners.
ServerChatListener listener = new ServerChatListener();
ChatRouter.addRouter(ChatRouter.EndpointType.PLAYER,listener);
pm.registerEvents(listener, this);
printInfo("CyniChat has been enabled!");
}
/**
* The routine to kill the connection cleanly and show that it has been done.
*/
@Override
public void onDisable() {
DataManager.saveChannels();
DataManager.saveUsers();
//if ( IRC == true ) PBot.stop();
printInfo("CyniChat has been disabled!");
}
/**
* Prints a SEVERE warning to the console.
* @param line : This is the error message
*/
public static void printSevere(String line) {
self.log.severe("[CyniChat] " + line);
}
/**
* Prints a WARNING to the console.
* @param line : This is the error message
*/
public static void printWarning(String line) {
self.log.warning("[CyniChat] " + line);
}
/**
* Prints INFO to the console
* @param line : This is the information
*/
public static void printInfo(String line) {
self.log.info("[CyniChat] " + line);
}
/**
* Prints DEBUG info to the console
* @param line : This contains the information to be outputted
*/
public static void printDebug(String line) {
if ( debug == true ) {
self.log.info("[CyniChat DEBUG] " + line);
}
}
/**
* Reload the plugin completely, disabling it before re-enabling it
*/
public static void reload() {
try {
self.onDisable();
self.onEnable();
} catch (NullPointerException e) {
printSevere("Failiure of epic proportions!");
e.printStackTrace();
}
}
/**
* Kill the plugin ungracefully.
*/
public static void killPlugin() {
printSevere("Fatal error has occured...");
printSevere("Killing...");
if ( IRC == true ) PBot.stop();
pm.disablePlugin( self );
}
} |
package views.btsrender;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import calculations.BTS;
import calculations.Location;
import calculations.Terrain;
public class BtsImageRenderer implements IBtsRenderer {
private final BufferedImage btsImage;
public BtsImageRenderer() throws IOException {
// default BTS image
btsImage = ImageIO.read(Thread.currentThread().getContextClassLoader()
.getResourceAsStream("bts.png"));
}
@Override
public void setTerrain(Terrain terrain) {
}
@Override
public void drawBts(Graphics g, BTS bts) {
Location location = bts.getLocation();
double x = location.getX();
double y = location.getY();
int range = bts.getRange();
g.drawImage(btsImage, (int) x - range, (int) y - range, range * 2, range * 2, null);
}
} |
package xyz.exemplator.exemplator;
import ratpack.exec.Blocking;
import ratpack.jackson.Jackson;
import ratpack.server.RatpackServer;
import ratpack.server.ServerConfig;
import xyz.exemplator.exemplator.data.ICodeSearch;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.sun.javafx.tools.resource.DeployResource.Type.data;
import static ratpack.jackson.Jackson.fromJson;
import static ratpack.jackson.Jackson.json;
import static ratpack.jackson.Jackson.jsonNode;
/**
* @author LeanderK
* @version 1.0
*/
public class Router {
private final int port;
private final ICodeSearch codeSearch;
public Router(int port, ICodeSearch codeSearch) {
this.port = port;
this.codeSearch = codeSearch;
}
public void init() throws Exception {
RatpackServer.start(server -> server
.serverConfig(ServerConfig.embedded().port(port))
.handlers(chain ->
chain.all(ctx -> {
ctx.getResponse().getHeaders().add("access-control-allow-origin", "*");
ctx.getResponse().getHeaders().add("access-control-allow-methods", "GET,PUT,POST,PATCH,DELETE,OPTIONS");
ctx.getResponse().getHeaders().add("access-control-allow-credentials", "true");
ctx.getResponse().getHeaders().add("access-control-allow-headers", "Authorization,Content-Type");
ctx.getResponse().getHeaders().add("access-control-expose-headers", "Link,Location");
ctx.getResponse().getHeaders().add("access-control-max-age", "86400");
ctx.next();
})
.post("search", ctx -> {
if (!ctx.getRequest().getContentType().isJson()) {
ctx.getResponse().status(500);
ctx.render("Expected Content-Type: application/json");
return;
}
ctx.render(ctx.parse(fromJson(Request.class))
.flatMap(request -> {
if (!request.getToken().isPresent()
&& !request.getClassName().isPresent() && !request.getMethodName().isPresent()) {
throw new IllegalArgumentException("token, methodName or classname must be present");
}
List<String> searchTerms = Stream.of(request.getClassName(), request.getMethodName(), request.getPackageName(), request.getToken())
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList());
return Blocking.get(() -> codeSearch.fetch(searchTerms, request.getPage()));
})
.map(list -> list.stream()
.map(sample -> {
Response.Position position = new Response.Position(1, 1);
List<Response.Position> positions = new ArrayList<>();
positions.add(position);
return new Response.Occurrence(sample.getUrl(), "", "", positions);
})
.collect(Collectors.toList())
)
.map(Response::new)
.map(Jackson::json));
})
)
);
}
} |
package net.hillsdon.reviki.wiki.renderer;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.exceptions.InvalidFormatException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.openpackaging.parts.WordprocessingML.NumberingDefinitionsPart;
import org.docx4j.wml.*;
import com.google.common.base.Optional;
import com.google.common.base.Supplier;
import net.hillsdon.reviki.vc.PageStore;
import net.hillsdon.reviki.web.urls.URLOutputFilter;
import net.hillsdon.reviki.wiki.renderer.creole.LinkPartsHandler;
import net.hillsdon.reviki.wiki.renderer.creole.ast.*;
import net.hillsdon.reviki.wiki.renderer.macro.Macro;
/**
* Render a docx file. The output is all styled with Styles (with the exception
* of runs of bold, italic, or strikethrough text) to enable easy editing of the
* resultant document.
*
* @author msw
*/
public class DocxRenderer extends CreoleBasedRenderer<InputStream> {
public DocxRenderer(final PageStore pageStore, final LinkPartsHandler linkHandler, final LinkPartsHandler imageHandler, final Supplier<List<Macro>> macros) {
super(pageStore, linkHandler, imageHandler, macros);
}
@Override
public InputStream render(ASTNode ast, URLOutputFilter urlOutputFilter) {
DocxVisitor visitor = new DocxVisitor(urlOutputFilter);
return visitor.visit(ast);
}
@Override
public String getContentType() {
return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
}
/*
* Generating a docx is very side-effectful - so all the methods return null,
* except for visitPage which bundles the generated document into a stream.
*/
protected static final class DocxVisitor extends ASTRenderer<InputStream> {
/** Styles for headings. We only go up to h6 in the ast. */
public static final String HEADING1_STYLE = "Heading 1";
public static final String HEADING2_STYLE = "Heading 2";
public static final String HEADING3_STYLE = "Heading 3";
public static final String HEADING4_STYLE = "Heading 4";
public static final String HEADING5_STYLE = "Heading 5";
public static final String HEADING6_STYLE = "Heading 6";
/** The default text style. */
public static final String TEXT_BODY_STYLE = "Text Body";
/** Styles for tables. */
public static final String TABLE_STYLE = "Padded Table";
public static final String TABLE_HEADER_STYLE = "Table Heading";
public static final String TABLE_CONTENTS_STYLE = "Table Contents";
/** Style for block code. */
public static final String CODE_STYLE = "Preformatted Text";
/** Font for block and inline code. */
public static final String CODE_FONT = "Courier New";
/** Style for paragraphs-turned-into-horizontal rules. */
public static final String HORIZONTAL_RULE_STYLE = "Horizontal Line";
/** The number style IDs for ordered and unordered lists. */
public static final BigInteger ORDERED_LIST_ID = BigInteger.valueOf(2);
public static final BigInteger UNORDERED_LIST_ID = BigInteger.valueOf(1);
/** The numbering definitions. */
public static final Numbering CUSTOM_NUMBERING;
/** Custom styles. */
public static final List<Style> CUSTOM_STYLES;
/** Docx files are arranged into a "package" of smaller xml files. */
protected final WordprocessingMLPackage _package;
/** The "main" part of the document, which has reference to other parts. */
protected final MainDocumentPart _mainPart;
/** This is the actual document being rendered. */
protected final Document _document;
/** And this is the body of the document! */
protected final Body _body;
/** All objects have to come from a factory. */
protected final ObjectFactory _factory;
/** The stack of containing contexts for new inline objects. */
protected final Stack<ContentAccessor> _contexts = new Stack<ContentAccessor>();
/** The stack of containing contexts for new block objects. */
protected final Stack<ContentAccessor> _blockContexts = new Stack<ContentAccessor>();
/** The stack of numbering styles for nested lists. */
protected final Stack<PPrBase.NumPr> _numberings = new Stack<PPrBase.NumPr>();
/*
* We can't nest bold/italic/strikethrough/etc text - so we need to keep
* track of which bits are active when we generate "runs" - bits of plain
* text.
*/
protected BooleanDefaultTrue _bold;
protected BooleanDefaultTrue _italic;
protected BooleanDefaultTrue _strike;
/** Style to apply to all paragraphs, if set. */
protected String _paragraphStyle = null;
/**
* Set up numbering and styles
*/
static {
ObjectFactory factory = new ObjectFactory();
/* ***** Lists. */
CUSTOM_NUMBERING = factory.createNumbering();
// Construct the ordered lists
NumberFormat[] orderedFmats = new NumberFormat[] { NumberFormat.DECIMAL, NumberFormat.LOWER_LETTER, NumberFormat.LOWER_ROMAN };
String[] orderedStrs = new String[] { "%C)" }; // "C" is replaced with the
// appropriate number
// counter.
Numbering.AbstractNum ordered = constructAbstractNumbering(ORDERED_LIST_ID, orderedFmats, orderedStrs);
Numbering.Num orderedNum = constructConcreteNumbering(ORDERED_LIST_ID);
// Construct the unordered lists
NumberFormat[] unorderedFmats = new NumberFormat[] { NumberFormat.BULLET };
String[] unorderedStrs = new String[] { "•", "", "" };
Numbering.AbstractNum unordered = constructAbstractNumbering(UNORDERED_LIST_ID, unorderedFmats, unorderedStrs);
Numbering.Num unorderedNum = constructConcreteNumbering(UNORDERED_LIST_ID);
// Add the lists to the numbering.
CUSTOM_NUMBERING.getAbstractNum().add(ordered);
CUSTOM_NUMBERING.getNum().add(orderedNum);
CUSTOM_NUMBERING.getAbstractNum().add(unordered);
CUSTOM_NUMBERING.getNum().add(unorderedNum);
/* ***** Styles. */
CUSTOM_STYLES = new ArrayList<Style>();
// Spacing for normal text, values from libreoffice
PPrBase.Spacing spacing = factory.createPPrBaseSpacing();
spacing.setAfter(BigInteger.valueOf(140));
spacing.setLine(BigInteger.valueOf(288));
spacing.setLineRule(STLineSpacingRule.AUTO);
spacing.setBefore(BigInteger.ZERO);
Style textBody = constructStyle(TEXT_BODY_STYLE, "Normal", "paragraph", Optional.<JcEnumeration> absent(), Optional.of(spacing), false);
Style code = constructStyle(CODE_STYLE, TEXT_BODY_STYLE, "paragraph", Optional.<JcEnumeration> absent(), Optional.of(spacing), false);
Style tableContents = constructStyle(TABLE_CONTENTS_STYLE, TEXT_BODY_STYLE, "paragraph", Optional.<JcEnumeration> absent(), Optional.<PPrBase.Spacing> absent(), false);
Style tableHeader = constructStyle(TABLE_HEADER_STYLE, TABLE_CONTENTS_STYLE, "paragraph", Optional.of(JcEnumeration.CENTER), Optional.<PPrBase.Spacing> absent(), true);
Style horizontalRule = constructStyle(HORIZONTAL_RULE_STYLE, "Normal", "paragraph", Optional.<JcEnumeration> absent(), Optional.<PPrBase.Spacing> absent(), false);
// Set code font
code.setRPr(factory.createRPr());
runFont(code.getRPr(), CODE_FONT);
// Set horizontal rule bottom border
CTBorder border = factory.createCTBorder();
border.setVal(STBorder.SINGLE);
border.setColor("black");
border.setSz(BigInteger.valueOf(2));
horizontalRule.setPPr(factory.createPPr());
horizontalRule.getPPr().setPBdr(factory.createPPrBasePBdr());
horizontalRule.getPPr().getPBdr().setBottom(border);
// The table style is very different to text styles, so it's just
// constructed here.
Style tblstyle = factory.createStyle();
tblstyle.setStyleId(styleNameToId(TABLE_STYLE));
tblstyle.setName(factory.createStyleName());
tblstyle.getName().setVal(TABLE_STYLE);
tblstyle.setBasedOn(factory.createStyleBasedOn());
tblstyle.getBasedOn().setVal("TableGrid");
tblstyle.setTblPr(factory.createCTTblPrBase());
// Set the cell margins
TblWidth margin = factory.createTblWidth();
margin.setW(BigInteger.valueOf(55)); // 55 twentieths of a point, seems to
// look nice.
tblstyle.getTblPr().setTblCellMar(factory.createCTTblCellMar());
tblstyle.getTblPr().getTblCellMar().setTop(margin);
tblstyle.getTblPr().getTblCellMar().setBottom(margin);
tblstyle.getTblPr().getTblCellMar().setLeft(margin);
tblstyle.getTblPr().getTblCellMar().setRight(margin);
// Finally, save the styles so they can be added to documents.
CUSTOM_STYLES.add(textBody);
CUSTOM_STYLES.add(code);
CUSTOM_STYLES.add(tableContents);
CUSTOM_STYLES.add(tableHeader);
CUSTOM_STYLES.add(horizontalRule);
}
public DocxVisitor(URLOutputFilter urlOutputFilter) {
super(urlOutputFilter);
try {
_package = WordprocessingMLPackage.createPackage();
_mainPart = _package.getMainDocumentPart();
}
catch (InvalidFormatException e) {
throw new RuntimeException(e);
}
_factory = new ObjectFactory();
_document = _mainPart.getContents();
_body = _factory.createBody();
_document.setBody(_body);
enterContext(_body, true);
// Set-up the formatting
_bold = _factory.createBooleanDefaultTrue();
_bold.setVal(Boolean.FALSE);
_italic = _factory.createBooleanDefaultTrue();
_italic.setVal(Boolean.FALSE);
_strike = _factory.createBooleanDefaultTrue();
_strike.setVal(Boolean.FALSE);
// Apply the statically-constructed numbering definitions.
try {
NumberingDefinitionsPart ndp = new NumberingDefinitionsPart();
ndp.setJaxbElement(CUSTOM_NUMBERING);
_mainPart.addTargetPart(ndp);
}
catch (Exception e) {
throw new RuntimeException(e);
}
// Apply the statically-constructed style definitions.
_mainPart.getStyleDefinitionsPart().getJaxbElement().getStyle().addAll(CUSTOM_STYLES);
}
/**
* Construct a new concrete numbering. A concrete numbering links a
* numbering ID to an abstract numbering - which defines what it actually
* looks like.
*
* @param id The ID of the abstract numbering.
* @return A new concrete numbering with a matching ID.
*/
protected static Numbering.Num constructConcreteNumbering(final BigInteger id) {
ObjectFactory factory = new ObjectFactory();
Numbering.Num num = factory.createNumberingNum();
num.setAbstractNumId(factory.createNumberingNumAbstractNumId());
num.getAbstractNumId().setVal(id);
num.setNumId(id);
return num;
}
/**
* Construct a new abstract numbering. An abstract numbering defines what
* symbols and indentation the various sublists have.
*
* @param id The ID of the numbering, this is used to relate a paragraph to
* the numbering.
* @param fmats Array of number formats to cycle through.
* @param strs Array of bullet strings to cycle through. In these strings,
* "C" will be replaced with the appropriate counter number,
* allowing ordered lists to be produced.
* @return A new abstract numbering, with up to 10 levels of list nesting.
*/
protected static Numbering.AbstractNum constructAbstractNumbering(final BigInteger id, final NumberFormat[] fmats, final String[] strs) {
ObjectFactory factory = new ObjectFactory();
Numbering.AbstractNum abstractNum = factory.createNumberingAbstractNum();
abstractNum.setAbstractNumId(id);
abstractNum.setMultiLevelType(factory.createNumberingAbstractNumMultiLevelType());
abstractNum.getMultiLevelType().setVal("multilevel");
// Construct all the numbering levels, cycling through the formats and
// display strings.
for (int ilvl = 0; ilvl < 10; ilvl++) {
long counter = ilvl + 1;
NumberFormat fmat = fmats[ilvl % fmats.length];
String str = strs[ilvl % strs.length];
Lvl lvl = constructNumberingLevel(fmat, ilvl, str.replace("C", "" + counter));
abstractNum.getLvl().add(lvl);
}
return abstractNum;
}
/**
* Construct a new numbering level. A numbering level defines the symbol and
* indentation to use at this particular nesting, when following its
* containing abstract numbering.
*
* @param fmat The number format.
* @param ilvl The indentation level (0-based).
* @param str The bullet string.
* @return A new numbering level, for this level of indentation.
*/
protected static Lvl constructNumberingLevel(final NumberFormat fmat, final long ilvl, final String str) {
ObjectFactory factory = new ObjectFactory();
Lvl lvl = factory.createLvl();
// Set the nesting level
lvl.setIlvl(BigInteger.valueOf(ilvl));
// Numbering starts from 1
lvl.setStart(factory.createLvlStart());
lvl.getStart().setVal(BigInteger.ONE);
// Set the numbering format
lvl.setNumFmt(factory.createNumFmt());
lvl.getNumFmt().setVal(fmat);
// Set the display text
lvl.setLvlText(factory.createLvlLvlText());
lvl.getLvlText().setVal(str);
// Set the justification
lvl.setLvlJc(factory.createJc());
lvl.getLvlJc().setVal(JcEnumeration.LEFT);
// Set the indentation
BigInteger indent = BigInteger.valueOf(360 * (ilvl + 1));
BigInteger hanging = BigInteger.valueOf(360);
CTTabStop tabstop = factory.createCTTabStop();
tabstop.setVal(STTabJc.NUM);
tabstop.setPos(indent);
lvl.setPPr(factory.createPPr());
lvl.getPPr().setTabs(factory.createTabs());
lvl.getPPr().getTabs().getTab().add(tabstop);
lvl.getPPr().setInd(factory.createPPrBaseInd());
lvl.getPPr().getInd().setLeft(indent);
lvl.getPPr().getInd().setHanging(hanging);
return lvl;
}
protected static Style constructStyle(final String name, final String basedOn, final String type, final Optional<JcEnumeration> justification, final Optional<PPrBase.Spacing> spacing, final boolean bold) {
ObjectFactory factory = new ObjectFactory();
// Create the style
Style style = factory.createStyle();
style.setStyleId(styleNameToId(name));
style.setBasedOn(factory.createStyleBasedOn());
style.getBasedOn().setVal(styleNameToId(basedOn));
style.setName(factory.createStyleName());
style.getName().setVal(name);
style.setType(type);
// Paragraph formatting
if (justification.isPresent() || spacing.isPresent()) {
style.setPPr(factory.createPPr());
if (justification.isPresent()) {
style.getPPr().setJc(factory.createJc());
style.getPPr().getJc().setVal(justification.get());
}
if (spacing.isPresent()) {
style.getPPr().setSpacing(spacing.get());
}
}
// Run formatting
if (bold) {
style.setRPr(factory.createRPr());
style.getRPr().setB(new BooleanDefaultTrue());
}
return style;
}
/**
* Style IDs are names with no spaces.
*/
protected static String styleNameToId(final String name) {
return name.replace(" ", "");
}
/** Style a paragraph. */
protected static void paraStyle(final P paragraph, final String style) {
ObjectFactory factory = new ObjectFactory();
if (paragraph.getPPr() == null) {
paragraph.setPPr(factory.createPPr());
}
if (paragraph.getPPr().getPStyle() == null) {
paragraph.getPPr().setPStyle(factory.createPPrBasePStyle());
}
paragraph.getPPr().getPStyle().setVal(styleNameToId(style));
}
/** Set the text of a run. */
protected static void runText(final R run, final String str) {
ObjectFactory factory = new ObjectFactory();
Text text = factory.createText();
text.setValue(str);
run.getContent().add(factory.createRT(text));
}
/** Set the font of some run properties. */
protected static void runFont(RPr props, final String font) {
ObjectFactory factory = new ObjectFactory();
props.setRFonts(factory.createRFonts());
props.getRFonts().setAscii(font);
props.getRFonts().setHAnsi(font);
}
/** Apply alignment to a table cell. */
protected static void applyValign(final Tc tablecell, final String valign) {
ObjectFactory factory = new ObjectFactory();
tablecell.setTcPr(factory.createTcPr());
tablecell.getTcPr().setVAlign(factory.createCTVerticalJc());
if (valign.equals("top")) {
tablecell.getTcPr().getVAlign().setVal(STVerticalJc.TOP);
}
else if (valign.equals("middle") || valign.equals("center") || valign.equals("centre")) {
tablecell.getTcPr().getVAlign().setVal(STVerticalJc.CENTER);
}
else if (valign.equals("bottom")) {
tablecell.getTcPr().getVAlign().setVal(STVerticalJc.BOTTOM);
}
}
/**
* Build the document by visiting the children, and then serialise it to an
* input stream.
*/
@Override
public InputStream visitPage(final Page node) {
// Build document
visitASTNode(node);
// And turn it into a bytestream
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
_package.save(out);
}
catch (Docx4JException e) {
System.err.println("Error outputting document: " + e);
}
return new ByteArrayInputStream(out.toByteArray());
}
/** Set some formatting, visit children, and unset the formatting. */
protected InputStream withFormatting(final BooleanDefaultTrue fmat, final ASTNode node) {
fmat.setVal(true);
visitASTNode(node);
fmat.setVal(false);
return nullval();
}
/**
* Like withContextSimple, but also adds the context to the containing
* block.
*/
protected InputStream withContext(final ContentAccessor ctx, final ASTNode node, final boolean block) {
commitBlock(ctx);
return withContextSimple(ctx, node, block);
}
/** Push a context, visit children, and pop the context. */
protected InputStream withContextSimple(final ContentAccessor ctx, final ASTNode node, final boolean block) {
enterContext(ctx, block);
visitASTNode(node);
exitContext(block);
return nullval();
}
/** Push a context. */
protected void enterContext(final ContentAccessor ctx, final boolean block) {
_contexts.push(ctx);
if (block) {
_blockContexts.push(ctx);
}
}
/** Pop a context. */
protected void exitContext(final boolean block) {
if (block) {
_blockContexts.pop();
}
_contexts.pop();
}
/** Construct a new numbering, push it, visit children, and pop. */
protected InputStream withNumbering(final BigInteger type, final ASTNode node) {
enterListContext(type);
visitASTNode(node);
exitListContext();
return nullval();
}
/** Construct and push a new list context. */
protected void enterListContext(final BigInteger type) {
// Construct a new list context at the appropriate indentation level and
// push it to the stack.
PPrBase.NumPr numpr = _factory.createPPrBaseNumPr();
numpr.setIlvl(_factory.createPPrBaseNumPrIlvl());
numpr.setNumId(_factory.createPPrBaseNumPrNumId());
numpr.getNumId().setVal(type);
if (_numberings.isEmpty()) {
numpr.getIlvl().setVal(BigInteger.ZERO);
}
else {
BigInteger last = _numberings.peek().getIlvl().getVal();
numpr.getIlvl().setVal(last.add(BigInteger.ONE));
}
_numberings.push(numpr);
}
/** Leave a list context. */
protected void exitListContext() {
_numberings.pop();
}
/** Make a new run, adding it to the current context. */
public R constructRun(final boolean applyFormatting) {
R run = _factory.createR();
commitInline(run);
if (applyFormatting) {
run.setRPr(_factory.createRPr());
run.getRPr().setB(new BooleanDefaultTrue());
run.getRPr().setI(new BooleanDefaultTrue());
run.getRPr().setStrike(new BooleanDefaultTrue());
run.getRPr().getB().setVal(_bold.isVal());
run.getRPr().getI().setVal(_italic.isVal());
run.getRPr().getStrike().setVal(_strike.isVal());
}
return run;
}
/** Save a block to the top block context. */
protected void commitBlock(Object o) {
_blockContexts.peek().getContent().add(o);
}
/** Save an inline element to the top context. */
protected void commitInline(Object o) {
_contexts.peek().getContent().add(o);
}
@Override
public InputStream visitBold(final Bold node) {
return withFormatting(_bold, node);
}
@Override
public InputStream visitCode(final Code node) {
P code = _factory.createP();
paraStyle(code, CODE_STYLE);
R run = constructRun(false);
runText(run, node.getText());
code.getContent().add(run);
commitBlock(code);
return nullval();
}
@Override
public InputStream visitHeading(final Heading node) {
P heading = _factory.createP();
// Apply the style
switch (node.getLevel()) {
case 1:
paraStyle(heading, HEADING1_STYLE);
break;
case 2:
paraStyle(heading, HEADING2_STYLE);
break;
case 3:
paraStyle(heading, HEADING3_STYLE);
break;
case 4:
paraStyle(heading, HEADING4_STYLE);
break;
case 5:
paraStyle(heading, HEADING5_STYLE);
break;
default:
paraStyle(heading, HEADING6_STYLE);
}
// Finally render the contents of the heading
return withContext(heading, node, false);
}
@Override
public InputStream visitHorizontalRule(final HorizontalRule node) {
P hrule = _factory.createP();
commitBlock(hrule);
paraStyle(hrule, HORIZONTAL_RULE_STYLE);
return nullval();
}
@Override
public InputStream renderImage(final String target, final String title, final Image node) {
// First we get a relation pointing to the image
BinaryPartAbstractImage imagePart;
org.docx4j.dml.wordprocessingDrawing.Inline inline;
try {
imagePart = BinaryPartAbstractImage.createLinkedImagePart(_package, new URL(target));
inline = imagePart.createImageInline(target, title, 1, 2, true);
}
catch (Exception e) {
// This shouldn't happen because we were able to successfully construct
// the URL in the first place.
return nullval();
}
// Then we add it to the current paragraph.
R run = constructRun(false);
Drawing drawing = _factory.createDrawing();
run.getContent().add(drawing);
drawing.getAnchorOrInline().add(inline);
return nullval();
}
@Override
public InputStream visitInlineCode(final InlineCode node) {
R run = constructRun(false);
run.setRPr(_factory.createRPr());
runFont(run.getRPr(), CODE_FONT);
runText(run, node.getText());
return nullval();
}
@Override
public InputStream visitItalic(final Italic node) {
return withFormatting(_italic, node);
}
@Override
public InputStream visitLinebreak(final Linebreak node) {
R run = constructRun(false);
run.getContent().add(_factory.createBr());
return nullval();
}
@Override
public InputStream renderLink(final String target, final String title, final Link node) {
P.Hyperlink hyperlink = _factory.createPHyperlink();
hyperlink.setAnchor(target);
R run = _factory.createR();
hyperlink.getContent().add(run);
runText(run, title);
commitInline(hyperlink);
return nullval();
}
@Override
public InputStream visitListItem(final ListItem node) {
// A list item is just a paragraph with some numbering applied.
P listitem = _factory.createP();
listitem.setPPr(_factory.createPPr());
listitem.getPPr().setNumPr(_numberings.peek());
return withContext(listitem, node, false);
}
@Override
public InputStream visitMacroNode(final MacroNode node) {
// If in block position, render to a new paragraph.
if (node.isBlock()) {
P para = _factory.createP();
commitBlock(para);
_contexts.push(para);
}
visitTextNode(node);
// And then remove the paragraph afterwards.
if (node.isBlock()) {
_contexts.pop();
}
return nullval();
}
@Override
public InputStream visitOrderedList(final OrderedList node) {
return withNumbering(ORDERED_LIST_ID, node);
}
@Override
public InputStream visitParagraph(final Paragraph node) {
P paragraph = _factory.createP();
// If there's a paragraph style currently in effect, apply it.
if (_paragraphStyle == null) {
paraStyle(paragraph, TEXT_BODY_STYLE);
}
else {
paraStyle(paragraph, _paragraphStyle);
}
return withContext(paragraph, node, false);
}
@Override
public InputStream visitStrikethrough(final Strikethrough node) {
return withFormatting(_strike, node);
}
@Override
public InputStream visitTable(final Table node) {
Tbl table = _factory.createTbl();
// Set the style to our custom one.
table.setTblPr(_factory.createTblPr());
table.getTblPr().setTblStyle(_factory.createCTTblPrBaseTblStyle());
table.getTblPr().getTblStyle().setVal(styleNameToId(TABLE_STYLE));
// Set the preferred width to 9638 twentieths of a point - the width of a
// page with default margins.
// The default width if unspecified is 0, which is interpreted as
// "grow the table until everything fits", as all widths are preferred.
// HOWEVER, libreoffice does not cope well with this, producing a table so
// wide as to go off the right edge of the page. The weird behaviour
// doesn't stop there, though, it's also dependent on units - dxa is the
// default, but the results of setting the width to 1 and 1dxa are very
// different.
// There is a bug report on the libreoffice bugzilla about this, but it's
// been open since 2013 with no progress.
// for details on the correct interpretation of width.
table.getTblPr().setTblW(_factory.createTblWidth());
table.getTblPr().getTblW().setW(BigInteger.valueOf(9638));
table.getTblPr().getTblW().setType("dxa");
return withContext(table, node, true);
}
/**
* Apply the vertical alignment directive to table cells.
*/
protected void valign(final Tc tablecell) {
if (isEnabled(TABLE_ALIGNMENT_DIRECTIVE)) {
applyValign(tablecell, unsafeGetArgs(TABLE_ALIGNMENT_DIRECTIVE).get(0));
}
}
@Override
public InputStream visitTableCell(final TableCell node) {
Tc tablecell = _factory.createTc();
commitBlock(tablecell);
valign(tablecell);
P para = _factory.createP();
tablecell.getContent().add(para);
paraStyle(para, TABLE_CONTENTS_STYLE);
return withContextSimple(para, node, false);
}
@Override
public InputStream visitTableHeaderCell(final TableHeaderCell node) {
Tc tablecell = _factory.createTc();
commitBlock(tablecell);
valign(tablecell);
P para = _factory.createP();
tablecell.getContent().add(para);
paraStyle(para, TABLE_HEADER_STYLE);
return withContextSimple(para, node, false);
}
@Override
public InputStream visitTableRow(final TableRow node) {
return withContext(_factory.createTr(), node, true);
}
@Override
public InputStream visitTextNode(final TextNode node) {
R run = constructRun(true);
// Docx is linebreak sensitive - despite being an XML-based format.
runText(run, node.getText().replace("\r", "").replace("\n", ""));
return nullval();
}
@Override
public InputStream visitUnorderedList(final UnorderedList node) {
return withNumbering(UNORDERED_LIST_ID, node);
}
}
} |
package io.subutai.core.hubmanager.impl.environment.state.build;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang.StringUtils;
import io.subutai.common.command.CommandCallback;
import io.subutai.common.command.CommandException;
import io.subutai.common.command.CommandResult;
import io.subutai.common.command.RequestBuilder;
import io.subutai.common.command.Response;
import io.subutai.common.environment.Environment;
import io.subutai.common.peer.EnvironmentContainerHost;
import io.subutai.common.peer.Host;
import io.subutai.common.peer.HostNotFoundException;
import io.subutai.core.hubmanager.api.RestClient;
import io.subutai.core.hubmanager.api.exception.HubManagerException;
import io.subutai.core.hubmanager.impl.environment.state.Context;
import io.subutai.core.hubmanager.impl.environment.state.StateHandler;
import io.subutai.core.identity.api.IdentityManager;
import io.subutai.hub.share.dto.ansible.AnsibleDto;
import io.subutai.hub.share.dto.ansible.Group;
import io.subutai.hub.share.dto.environment.EnvironmentPeerDto;
public class ConfigureEnvironmentStateHandler extends StateHandler
{
private static final String ENV_APPS_URL = "/rest/v1/environments/%s/apps";
private static final String TMP_DIR = "/root/";
private static final String EXTRA_VARS_FILE_NAME = "extra-vars.json";
private static final String CREATE_EXTRA_VARS_FILE_CMD = "cd %s; cat > %s <<EOL\n" + "%s" + "\n" + "EOL\n";
private static final String RUN_PLAYBOOK_CMD = "cd %s; ansible-playbook %s -e \"@%s\" -i %s";
private long commandTimeout = 5L;
public final RestClient restClient;
public ConfigureEnvironmentStateHandler( Context ctx )
{
super( ctx, "Configure environment" );
restClient = ctx.restClient;
}
@Override
protected Object doHandle( EnvironmentPeerDto peerDto ) throws HubManagerException
{
logStart();
AnsibleDto ansibleDto = peerDto.getAnsibleDto();
if ( ansibleDto != null )
{
startConfiguration( ansibleDto, peerDto );
}
logEnd();
return peerDto;
}
private void startConfiguration( AnsibleDto ansibleDto, EnvironmentPeerDto peerDto )
{
if ( ansibleDto.getCommandTimeout() != null )
{
commandTimeout = ansibleDto.getCommandTimeout();
}
final String fileName = getBPFilename( ansibleDto.getRepoLink() );
prepareHostsFile( fileName, ansibleDto.getAnsibleContainerId(), ansibleDto.getGroups() );
copyRepoUnpack( ansibleDto.getAnsibleContainerId(), ansibleDto.getRepoLink() );
runAnsibleScript( fileName, ansibleDto, peerDto.getEnvironmentInfo().getId() );
try
{
//authorize once again, Ansible script may run more than auth session timeout
String token = getToken( peerDto );
ctx.identityManager.login( IdentityManager.TOKEN_ID, token );
//invalidate desktop information cache
Environment environment = ctx.envManager.loadEnvironment( peerDto.getEnvironmentInfo().getId() );
for ( EnvironmentContainerHost host : environment.getContainerHostsByPeerId( peerDto.getPeerId() ) )
{
ctx.desktopManager.invalidate( host.getId() );
}
}
catch ( Exception e )
{
log.info( e.getMessage() );
}
}
private void runAnsibleScript( String fileName, AnsibleDto ansibleDto, String envSubutaiId )
{
final String containerId = ansibleDto.getAnsibleContainerId();
final String inventoryFile = "/etc/ansible/" + fileName + ".hosts";
final String mainAnsibleScript = ansibleDto.getAnsibleRootFile();
String extraVars = ansibleDto.getVars();
if ( StringUtils.isEmpty( ansibleDto.getVars() ) )
{
extraVars = "{}";
}
String extraVarsCmd =
String.format( CREATE_EXTRA_VARS_FILE_CMD, TMP_DIR + fileName, EXTRA_VARS_FILE_NAME, extraVars );
String cmd = String.format( RUN_PLAYBOOK_CMD, TMP_DIR + fileName, mainAnsibleScript, EXTRA_VARS_FILE_NAME,
inventoryFile );
try
{
runCmd( containerId, extraVarsCmd );
runCmdAsync( containerId, cmd, envSubutaiId );
}
catch ( Exception e )
{
log.error( "Error configuring environment", e );
}
}
private String getBPFilename( String repoLink )
{
repoLink = repoLink.replaceAll( "https://github.com/", "" );
repoLink = repoLink.replaceAll( "/archive/", "-" );
repoLink = repoLink.replaceAll( ".zip", "" );
return repoLink.split( "/" )[1];
}
private void copyRepoUnpack( final String containerId, final String repoLink )
{
try
{
int count = 1;
boolean reachable = isGithubReachable( containerId );
while ( !reachable && count < 5 ) //break after 5th try
{
TimeUnit.SECONDS.sleep( count * 2 );
reachable = isGithubReachable( containerId );
count++;
log.info( "No internet connection on container host {}", containerId );
}
String cmd = String.format( "cd %s; bash get_unzip.sh %s", TMP_DIR, repoLink );
runCmd( containerId, cmd );
}
catch ( Exception e )
{
log.error( "Error configuring environment", e );
}
}
private boolean isGithubReachable( String containerId ) throws Exception
{
Host host = ctx.localPeer.getContainerHostById( containerId );
CommandResult result =
host.execute( new RequestBuilder( "ping" ).withCmdArgs( "-w", "10", "-c", "3", "www.github.com" ) );
return result.hasSucceeded();
}
private void prepareHostsFile( final String fileName, final String containerId,
Set<io.subutai.hub.share.dto.ansible.Group> groups )
{
String groupName;
String inventoryLine;
final String inventoryFile = fileName + ".hosts";
try
{
for ( Group group : groups )
{
groupName = String.format( "[%s]", group.getName() );
runCmd( containerId,
String.format( "grep -q -F '%s' /etc/ansible/%s || echo '%s' >> /etc/ansible/%s", groupName,
inventoryFile, groupName, inventoryFile ) );
for ( io.subutai.hub.share.dto.ansible.Host host : group.getHosts() )
{
inventoryLine = format( host ).trim();
runCmd( containerId,
String.format( "grep -q -F '%s' /etc/ansible/%s || echo '%s' >> /etc/ansible/%s",
inventoryLine, inventoryFile, inventoryLine, inventoryFile ) );
}
}
}
catch ( Exception e )
{
log.error( "Error configuring environment", e );
}
}
private void runCmd( String containerId, String cmd ) throws HostNotFoundException, CommandException
{
Host host = ctx.localPeer.getContainerHostById( containerId );
RequestBuilder rb =
new RequestBuilder( cmd ).withTimeout( ( int ) TimeUnit.MINUTES.toSeconds( commandTimeout ) );
CommandResult result = host.execute( rb );
if ( !result.hasSucceeded() )
{
log.error( "Error configuring environment: {}", result );
}
}
private static String format( io.subutai.hub.share.dto.ansible.Host host )
{
String inventoryLineFormat = "%s ansible_user=%s template=%s ansible_ssh_host=%s";
//if template has python3, default is python2
if ( host.getPythonPath() != null )
{
inventoryLineFormat += " ansible_python_interpreter=" + host.getPythonPath();
}
return String.format( inventoryLineFormat, host.getHostname(), host.getAnsibleUser(), host.getTemplateName(),
host.getIp() );
}
private void runCmdAsync( String containerId, String cmd, String envSubutaiId )
throws HostNotFoundException, CommandException
{
Host host = ctx.localPeer.getContainerHostById( containerId );
RequestBuilder rb =
new RequestBuilder( cmd ).withTimeout( ( int ) TimeUnit.MINUTES.toSeconds( commandTimeout ) );
AnsibleCallback ansibleCallback = new AnsibleCallback( envSubutaiId );
host.execute( rb, ansibleCallback );
}
private class AnsibleCallback implements CommandCallback
{
final String envSubutaiId;
private List<Integer> cache = new ArrayList<>();
AnsibleCallback( String envSubutaiId )
{
this.envSubutaiId = envSubutaiId;
}
@Override
public void onResponse( final Response response, final CommandResult commandResult )
{
if ( cache.contains( response.getResponseNumber() ) )
{
return;
}
else
{
cache.add( response.getResponseNumber() );
}
AnsibleDto ansibleDto = new AnsibleDto();
ansibleDto.setState( AnsibleDto.State.IN_PROGRESS );
if ( commandResult.hasCompleted() )
{
if ( !commandResult.hasSucceeded() )
{
ansibleDto.setState( AnsibleDto.State.FAILED );
ansibleDto.setLogs( commandResult.getStdErr() + commandResult.getStdOut() );
}
else
{
ansibleDto.setState( AnsibleDto.State.SUCCESS );
ansibleDto.setLogs( commandResult.getStdOut() );
}
}
else
{
ansibleDto.setLogs( commandResult.getStdOut() );
}
String path = String.format( ENV_APPS_URL, this.envSubutaiId );
restClient.post( path, ansibleDto );
}
}
} |
package monitoring.impl;
import java.util.IdentityHashMap;
import java.util.Map;
import structure.impl.SimplestQEA;
import structure.impl.Verdict;
/**
* A small-step monitor for the Simplest QEA
*
* @author Giles Reger
* @author Helena Cuenca
*/
public class SimplestSmallStepQEAMonitor extends SmallStepMonitor<SimplestQEA> {
private IdentityHashMap<Object, Integer> bindings;
private int bindingsInNonFinalStateCount;
private int bindingsInFinalStateCount;
/**
* Creates a SimplestSmallStepQEAMonitor for the specified QEA
*
* @param qea
* QEA
*/
SimplestSmallStepQEAMonitor(SimplestQEA qea) {
super(qea);
bindings = new IdentityHashMap<>();
bindingsInNonFinalStateCount = 0;
bindingsInFinalStateCount = 0;
}
@Override
public Verdict step(int eventName, Object[] args) {
// TODO Auto-generated method stub
return null;
}
@Override
public Verdict step(int eventName, Object param1) {
boolean existingBinding = false;
int startState;
// Determine if the value received corresponds to an existing binding
if (bindings.containsKey(param1)) { // Existing binding
// Get current state for the binding
startState = bindings.get(param1);
// Assign flag for counters update
existingBinding = true;
} else { // New binding
startState = 1;
}
// Compute next state
int endState = qea.getNextState(startState, eventName);
// Update/add state for the binding
bindings.put(param1, endState);
// If applicable, update counters
if (existingBinding) {
if (qea.isStateFinal(startState) && !qea.isStateFinal(endState)) {
bindingsInNonFinalStateCount++;
bindingsInFinalStateCount
} else if (!qea.isStateFinal(startState)
&& qea.isStateFinal(endState)) {
bindingsInNonFinalStateCount
bindingsInFinalStateCount++;
}
} else {
if (qea.isStateFinal(endState)) {
bindingsInFinalStateCount++;
} else {
bindingsInNonFinalStateCount++;
}
}
// According to the quantification of the variable, return verdict
if (qea.isQuantificationUniversal() && allBindingsInFinalState()
|| !qea.isQuantificationUniversal()
&& existsOneBindingInFinalState()) {
return Verdict.WEAK_SUCCESS;
}
return Verdict.WEAK_FAILURE;
}
@Override
public Verdict step(int eventName) {
Verdict finalVerdict = null;
for (Map.Entry<Object, Integer> entry : bindings.entrySet()) {
finalVerdict = step(eventName, entry.getKey());
}
return finalVerdict;
}
@Override
public Verdict end() {
// According to the quantification of the variable, return verdict
if (qea.isQuantificationUniversal() && allBindingsInFinalState()
|| !qea.isQuantificationUniversal()
&& existsOneBindingInFinalState()) {
return Verdict.SUCCESS;
}
return Verdict.FAILURE;
}
/**
* Determines if all bindings for the current monitor are in a final state
*
* @return <code>true</code> if all bindings for the current monitor are in
* a final state; <code>false</code> otherwise
*/
private boolean allBindingsInFinalState() {
if (bindingsInNonFinalStateCount == 0) {
return true;
}
return false;
}
/**
* Determines if there is at least one binding in a final state for the
* current monitor
*
* @return <code>true</code> if at least one binding is in final state;
* <code>false</code> otherwise
*/
private boolean existsOneBindingInFinalState() {
if (bindingsInFinalStateCount > 0) {
return true;
}
return false;
}
} |
package com.couchbase.lite;
import com.couchbase.lite.internal.RevisionInternal;
import com.couchbase.lite.util.Log;
import junit.framework.Assert;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.map.ObjectMapper;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class DocumentTest extends LiteTestCase {
public void testNewDocumentHasCurrentRevision() throws CouchbaseLiteException {
Document document = database.createDocument();
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("foo", "foo");
properties.put("bar", Boolean.FALSE);
document.putProperties(properties);
Assert.assertNotNull(document.getCurrentRevisionId());
Assert.assertNotNull(document.getCurrentRevision());
}
public void testPutDeletedDocument() throws CouchbaseLiteException {
Document document = database.createDocument();
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("foo", "foo");
properties.put("bar", Boolean.FALSE);
document.putProperties(properties);
Assert.assertNotNull(document.getCurrentRevision());
String docId = document.getId();
properties.put("_rev",document.getCurrentRevisionId());
properties.put("_deleted", true);
properties.put("mykey", "myval");
SavedRevision newRev = document.putProperties(properties);
newRev.loadProperties();
assertTrue( newRev.getProperties().containsKey("mykey") );
Assert.assertTrue(document.isDeleted());
Document fetchedDoc = database.getExistingDocument(docId);
Assert.assertNull(fetchedDoc);
// query all docs and make sure we don't see that document
database.getAllDocs(new QueryOptions());
Query queryAllDocs = database.createAllDocumentsQuery();
QueryEnumerator queryEnumerator = queryAllDocs.run();
for (Iterator<QueryRow> it = queryEnumerator; it.hasNext();) {
QueryRow row = it.next();
Assert.assertFalse(row.getDocument().getId().equals(docId));
}
}
public void testDeleteDocument() throws CouchbaseLiteException {
Document document = database.createDocument();
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("foo", "foo");
properties.put("bar", Boolean.FALSE);
document.putProperties(properties);
Assert.assertNotNull(document.getCurrentRevision());
String docId = document.getId();
document.delete();
Assert.assertTrue(document.isDeleted());
Document fetchedDoc = database.getExistingDocument(docId);
Assert.assertNull(fetchedDoc);
// query all docs and make sure we don't see that document
database.getAllDocs(new QueryOptions());
Query queryAllDocs = database.createAllDocumentsQuery();
QueryEnumerator queryEnumerator = queryAllDocs.run();
for (Iterator<QueryRow> it = queryEnumerator; it.hasNext();) {
QueryRow row = it.next();
Assert.assertFalse(row.getDocument().getId().equals(docId));
}
}
public void testGetNonExistentDocument() throws CouchbaseLiteException {
assertNull(database.getExistingDocument("missing"));
Document doc = database.getDocument("missing");
assertNotNull(doc);
assertNull(database.getExistingDocument("missing"));
}
// Reproduces issue #167
public void testLoadRevisionBody() throws CouchbaseLiteException {
Document document = database.createDocument();
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("foo", "foo");
properties.put("bar", Boolean.FALSE);
document.putProperties(properties);
Assert.assertNotNull(document.getCurrentRevision());
boolean deleted = false;
RevisionInternal revisionInternal = new RevisionInternal(
document.getId(),
document.getCurrentRevisionId(),
deleted,
database
);
EnumSet<Database.TDContentOptions> contentOptions = EnumSet.of(
Database.TDContentOptions.TDIncludeAttachments,
Database.TDContentOptions.TDBigAttachmentsFollow
);
database.loadRevisionBody(revisionInternal, contentOptions);
// now lets purge the document, and then try to load the revision body again
document.purge();
boolean gotExpectedException = false;
try {
database.loadRevisionBody(revisionInternal, contentOptions);
} catch (CouchbaseLiteException e) {
if (e.getCBLStatus().getCode() == Status.NOT_FOUND) {
gotExpectedException = true;
}
}
assertTrue(gotExpectedException);
}
public void testDocumentWithRemovedProperty() {
Map<String, Object> props = new HashMap<String, Object>();
props.put("_id", "fakeid");
props.put("_removed", true);
props.put("foo", "bar");
Document doc = createDocumentWithProperties(database, props);
assertNotNull(doc);
Document docFetched = database.getDocument(doc.getId());
Map<String, Object> fetchedProps = docFetched.getCurrentRevision().getProperties();
assertNotNull(fetchedProps.get("_removed"));
assertTrue(docFetched.getCurrentRevision().isGone());
}
public void failingTestGetDocumentWithLargeJSON() {
Map<String, Object> props = new HashMap<String, Object>();
props.put("_id", "laaargeJSON");
char[] chars = new char[2500000];//~5MB
Arrays.fill(chars, 'a');
props.put("foo", new String(chars));
Document doc = createDocumentWithProperties(database, props);
assertNotNull(doc);
Document docFetched = database.getDocument(doc.getId());
Map<String, Object> fetchedProps = docFetched.getCurrentRevision().getProperties();
assertEquals(fetchedProps.get("foo"), new String(chars));
}
public void failingTestDocumentPropertiesAreImmutable() throws Exception {
String jsonString = "{\n" +
" \"name\":\"praying mantis\",\n" +
" \"wikipedia\":{\n" +
" \"behavior\":{\n" +
" \"style\":\"predatory\",\n" +
" \"attack\":\"ambush\"\n" +
" },\n" +
" \"evolution\":{\n" +
" \"ancestor\":\"proto-roaches\",\n" +
" \"cousin\":\"termite\"\n" +
" } \n" +
" } \n" +
"\n" +
"}";
Map map = (Map) Manager.getObjectMapper().readValue(jsonString, Object.class);
Document doc = createDocumentWithProperties(database, map);
boolean firstLevelImmutable = false;
Map<String, Object> props = doc.getProperties();
try {
props.put("name", "bug");
} catch (UnsupportedOperationException e) {
firstLevelImmutable = true;
}
assertTrue(firstLevelImmutable);
boolean secondLevelImmutable = false;
Map wikiProps = (Map) props.get("wikipedia");
try {
wikiProps.put("behavior", "unknown");
} catch (UnsupportedOperationException e) {
secondLevelImmutable = true;
}
assertTrue(secondLevelImmutable);
boolean thirdLevelImmutable = false;
Map evolutionProps = (Map) wikiProps.get("behavior");
try {
evolutionProps.put("movement", "flight");
} catch (UnsupportedOperationException e) {
thirdLevelImmutable = true;
}
assertTrue(thirdLevelImmutable);
}
public void failingTestProvidedMapChangesAreSafe() throws Exception {
Map<String, Object> originalProps = new HashMap<String, Object>();
Document doc = createDocumentWithProperties(database, originalProps);
Map<String, Object> nestedProps = new HashMap<String, Object>();
nestedProps.put("version", "original");
UnsavedRevision rev = doc.createRevision();
rev.getProperties().put("nested", nestedProps);
rev.save();
nestedProps.put("version", "changed");
assertEquals("original", ((Map) doc.getProperty("nested")).get("version"));
}
@JsonIgnoreProperties(ignoreUnknown = true)
static public class Foo {
private String bar;
public Foo() {
}
public String getBar() {
return bar;
}
public void setBar(String bar) {
this.bar = bar;
}
}
/**
* Assert that if you add a
* @throws Exception
*/
public void testNonPrimitiveTypesInDocument() throws Exception {
Object fooProperty;
Map<String, Object> props = new HashMap<String, Object>();
Foo foo = new Foo();
foo.setBar("basic");
props.put("foo", foo);
Document doc = createDocumentWithProperties(database, props);
fooProperty = doc.getProperties().get("foo");
assertTrue(fooProperty instanceof Map);
assertFalse(fooProperty instanceof Foo);
Document fetched = database.getDocument(doc.getId());
fooProperty = fetched.getProperties().get("foo");
assertTrue(fooProperty instanceof Map);
assertFalse(fooProperty instanceof Foo);
ObjectMapper mapper = new ObjectMapper();
Foo fooResult = mapper.convertValue(fooProperty, Foo.class);
assertEquals(foo.bar, fooResult.bar);
}
public void testDocCustomID() throws Exception {
Document document = database.getDocument("my_custom_id");
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("foo", "bar");
document.putProperties(properties);
Document documentFetched = database.getDocument("my_custom_id");
assertEquals("my_custom_id", documentFetched.getId());
assertEquals("bar", documentFetched.getProperties().get("foo"));
}
} |
package com.sapienter.jbilling.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
* This is a Singleton call that provides the system properties from
* the jbilling.properties file
*/
public class SystemProperties {
private static final Logger LOG = Logger.getLogger(SystemProperties.class);
private static final String JBILLING_HOME = "JBILLING_HOME";
private static final String PROPERTIES_FILE = "jbilling.properties";
private static SystemProperties INSTANCE;
private Properties prop = null;
/*
private singleton constructor
*/
private SystemProperties() throws IOException {
File properties = getPropertiesFile();
FileInputStream stream = new FileInputStream(properties);
prop = new Properties();
prop.load(stream);
stream.close();
LOG.debug("System properties loaded from: " + properties.getPath());
System.out.println("System properties loaded from: " + properties.getPath());
}
/**
* Returns a singleton instance of SystemProperties
*
* @return instance
* @throws IOException if properties could not be loaded
*/
public static SystemProperties getSystemProperties() throws IOException{
if (INSTANCE == null)
INSTANCE = new SystemProperties();
return INSTANCE;
}
/**
* Returns the jBilling home path where resources and configuration files
* can be found.
*
* The environment variable JBILLING_HOME and system property JBILLING_HOME are examined
* for this value, with precedence given to system properties set via command line arguments.
*
* If no jBilling home path is set, properties will be loaded from the classpath.
*
* @return jbilling home path
*/
public static String getJBillingHome() {
String jbillingHome = System.getProperty(JBILLING_HOME);
if (jbillingHome == null) {
jbillingHome = System.getenv(JBILLING_HOME);
}
return jbillingHome;
}
/**
* Returns the path to the jbilling.properties file.
*
* @return properties file
*/
public static File getPropertiesFile() {
String jbillingHome = getJBillingHome();
if (jbillingHome != null) {
// properties file from filesystem
return new File(jbillingHome + File.separator + PROPERTIES_FILE);
} else {
// properties file from classpath
URL url = SystemProperties.class.getResource("/" + PROPERTIES_FILE);
return new File(url.getFile());
}
}
public String get(String key) throws Exception {
String value = prop.getProperty(key);
if (value == null)
throw new Exception("Missing system property: " + key);
return value;
}
public String get(String key, String defaultValue) {
return prop.getProperty(key, defaultValue);
}
} |
package founderio.chaoscrystal;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Random;
import net.minecraft.client.Minecraft;
import net.minecraft.client.multiplayer.PlayerControllerMP;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.INetworkManager;
import net.minecraft.network.packet.Packet250CustomPayload;
import net.minecraft.util.MathHelper;
import net.minecraft.world.World;
import net.minecraftforge.common.DimensionManager;
import cpw.mods.fml.common.network.IPacketHandler;
import cpw.mods.fml.common.network.PacketDispatcher;
import cpw.mods.fml.common.network.Player;
import founderio.chaoscrystal.degradation.Aspects;
import founderio.chaoscrystal.entities.DegradationParticles;
import founderio.chaoscrystal.entities.EntityFocusFilter;
public class ChaosCrystalNetworkHandler implements IPacketHandler {
private Random rnd = new Random();
public static void spawnParticleEffect(int dimension, int effect,
int sourceX, int sourceY, int sourceZ,
int offX, int offY, int offZ) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream(Integer.SIZE * 7);
DataOutputStream dos = new DataOutputStream(bos);
dos.writeInt(effect);
dos.writeInt(dimension);
dos.writeInt(sourceX);
dos.writeInt(sourceY);
dos.writeInt(sourceZ);
dos.writeInt(offX);
dos.writeInt(offY);
dos.writeInt(offZ);
Packet250CustomPayload degradationPacket = new Packet250CustomPayload();
degradationPacket.channel = Constants.CHANNEL_NAME_PARTICLES;
degradationPacket.data = bos.toByteArray();
degradationPacket.length = bos.size();
dos.close();
PacketDispatcher.sendPacketToAllAround(sourceX, sourceY, sourceZ, 128, dimension, degradationPacket);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void spawnParticleEffects(Entity from, Entity to, int effect) {
spawnParticleEffect(from.worldObj.provider.dimensionId, effect,
(int)from.posX, (int)from.posY, (int)from.posZ,
(int)(to.posX - from.posX), (int)(to.posY - from.posY), (int)(to.posZ - from.posZ));
}
@Override
public void onPacketData(INetworkManager manager,
Packet250CustomPayload packet, Player player) {
if(packet.channel.equals(Constants.CHANNEL_NAME_PARTICLES)) {
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(packet.data));
try {
int type = dis.readInt();
int dimension = dis.readInt();
int posX = dis.readInt();
int posY = dis.readInt();
int posZ = dis.readInt();
int offX = dis.readInt();
int offY = dis.readInt();
int offZ = dis.readInt();
World w = DimensionManager.getWorld(dimension);
if(w != null) {
for(int i = 0; i < 5 + rnd.nextInt(5); i++) {
Minecraft.getMinecraft().effectRenderer.addEffect(
new DegradationParticles(
w,
posX + rnd.nextDouble(),
posY + rnd.nextDouble(),
posZ + rnd.nextDouble(),
offX + rnd.nextDouble(),
offY + rnd.nextDouble(),
offZ + rnd.nextDouble(),
type));
}
}
} catch (IOException e) {
e.printStackTrace();
}
} else if(packet.channel.equals(Constants.CHANNEL_NAME_OTHER_VISUAL)) {
DataInputStream dis = new DataInputStream(new ByteArrayInputStream(packet.data));
try {
int type = dis.readInt();
if(type==1) {
//Unused
} else if(type==2) {
// Update player's selected stack
int dimension = dis.readInt();
String playerName = dis.readUTF();
String aspect = dis.readUTF();
World w = DimensionManager.getWorld(dimension);
if(w != null) {
EntityPlayer e = w.getPlayerEntityByName(playerName);
if(e != null) {
ItemStack currentItem = e.inventory.getCurrentItem();
if(currentItem == null || currentItem.itemID != ChaosCrystalMain.itemFocus.itemID) {
return;
}
if(currentItem.getItemDamage() != 2) {
return;
}
NBTTagCompound tags = currentItem.getTagCompound();
if(tags == null) {
tags = new NBTTagCompound();
}
tags.setString("aspect", aspect);
currentItem.setTagCompound(tags);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} |
package org.apache.velocity.test.provider;
import java.util.*;
/**
* This class is used by the testbed. Instances of the class
* are fed into the context that is set before the AST
* is traversed and dynamic content generated.
*
* @author <a href="mailto:jvanzyl@periapt.com">Jason van Zyl</a>
* @version $Id: TestProvider.java,v 1.17 2001/06/29 23:39:03 geirm Exp $
*/
public class TestProvider
{
String title = "lunatic";
boolean state;
Object ob = null;
public static String PUB_STAT_STRING = "Public Static String";
int stateint = 0;
public String getName()
{
return "jason";
}
public Stack getStack()
{
Stack stack = new Stack();
stack.push("stack element 1");
stack.push("stack element 2");
stack.push("stack element 3");
return stack;
}
public List getEmptyList()
{
List list = new ArrayList();
return list;
}
public List getList()
{
List list = new ArrayList();
list.add("list element 1");
list.add("list element 2");
list.add("list element 3");
return list;
}
public Hashtable getSearch()
{
Hashtable h = new Hashtable();
h.put("Text", "this is some text");
h.put("EscText", "this is escaped text");
h.put("Title", "this is the title");
h.put("Index", "this is the index");
h.put("URL", "http://periapt.com");
ArrayList al = new ArrayList();
al.add(h);
h.put("RelatedLinks", al);
return h;
}
public Hashtable getHashtable()
{
Hashtable h = new Hashtable();
h.put("key0", "value0");
h.put("key1", "value1");
h.put("key2", "value2");
return h;
}
public ArrayList getRelSearches()
{
ArrayList al = new ArrayList();
al.add(getSearch());
return al;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public Object[] getMenu()
{
//ArrayList al = new ArrayList();
Object[] menu = new Object[3];
for (int i = 0; i < 3; i++)
{
Hashtable item = new Hashtable();
item.put("id", "item" + Integer.toString(i+1));
item.put("name", "name" + Integer.toString(i+1));
item.put("label", "label" + Integer.toString(i+1));
//al.add(item);
menu[i] = item;
}
//return al;
return menu;
}
public ArrayList getCustomers()
{
ArrayList list = new ArrayList();
list.add("ArrayList element 1");
list.add("ArrayList element 2");
list.add("ArrayList element 3");
list.add("ArrayList element 4");
return list;
}
public ArrayList getCustomers2()
{
ArrayList list = new ArrayList();
list.add(new TestProvider());
list.add(new TestProvider());
list.add(new TestProvider());
list.add(new TestProvider());
return list;
}
public Object me()
{
return this;
}
public String toString()
{
return ("test provider");
}
public Vector getVector()
{
Vector list = new Vector();
list.addElement("vector element 1");
list.addElement("vector element 2");
return list;
}
public String[] getArray()
{
String[] strings = new String[2];
strings[0] = "first element";
strings[1] = "second element";
return strings;
}
public boolean theAPLRules()
{
return true;
}
public boolean getStateTrue()
{
return true;
}
public boolean getStateFalse()
{
return false;
}
public String objectArrayMethod(Object[] o)
{
return "result of objectArrayMethod";
}
public String concat(Object[] o)
{
String result = "";
for (int i = 0; i < o.length; i++)
result += (String) o[i] + " ";
return result;
}
public String concat( List o)
{
String result = "";
for (int i = 0; i < o.size(); i++)
result += (String) o.get(i) + " ";
return result;
}
public String objConcat( List list)
{
String result = "";
Object o;
for (int i = 0; i < list.size(); i++)
{
o = list.get(i);
result += o.toString() + " ";
}
return result;
}
public String parse(String a, Object o, String c, String d)
{
return a + o.toString() + c + d;
}
public String concat(String a, String b)
{
return a + b;
}
// These two are for testing subclasses.
public Person getPerson()
{
return new Person();
}
public Child getChild()
{
return new Child();
}
public String showPerson(Person person)
{
return person.getName();
}
/**
* Chop i characters off the end of a string.
*
* @param string String to chop.
* @param i Number of characters to chop.
* @return String with processed answer.
*/
public String chop(String string, int i)
{
return(string.substring(0, string.length() - i));
}
public boolean allEmpty(Object[] list)
{
int size = list.length;
for (int i = 0; i < size; i++)
if (list[i].toString().length() > 0)
return false;
return true;
}
/*
* This can't have the signature
public void setState(boolean state)
or dynamically invoking the method
doesn't work ... you would have to
put a wrapper around a method for a
real boolean property that takes a
Boolean object if you wanted this to
work. Not really sure how useful it
is anyway. Who cares about boolean
values you can just set a variable.
*/
public void setState(Boolean state)
{
}
public void setBangStart( Integer i )
{
System.out.println("SetBangStart() : called with val = " + i );
stateint = i.intValue();
}
public Integer bang()
{
System.out.println("Bang! : " + stateint );
Integer ret = new Integer( stateint );
stateint++;
return ret;
}
/**
* Test the ability of vel to use a get(key)
* method for any object type, not just one
* that implements the Map interface.
*/
public String get(String key)
{
return key;
}
/**
* Test the ability of vel to use a put(key)
* method for any object type, not just one
* that implements the Map interface.
*/
public String put(String key, Object o)
{
ob = o;
return key;
}
public String getFoo()
throws Exception
{
throw new Exception("From getFoo()");
}
public String getThrow()
throws Exception
{
throw new Exception("From getThrow()");
}
} |
package test.org.relique.jdbc.csv;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* This class is used to test the CsvJdbc driver.
*
* @author Mario Frasca
*/
public class TestPrepareStatement
{
private static String filePath;
@BeforeClass
public static void setUp()
{
filePath = ".." + File.separator + "src" + File.separator + "testdata";
if (!new File(filePath).isDirectory())
filePath = "src" + File.separator + "testdata";
assertTrue("Sample files directory not found: " + filePath, new File(filePath).isDirectory());
// load CSV driver
try
{
Class.forName("org.relique.jdbc.csv.CsvDriver");
}
catch (ClassNotFoundException e)
{
fail("Driver is not in the CLASSPATH -> " + e);
}
}
@Test
public void testCanPrepareStatement() throws SQLException
{
Properties props = new Properties();
props.put("extension", ".csv");
Connection conn = DriverManager.getConnection("jdbc:relique:csv:"
+ filePath, props);
String queryString = "SELECT * FROM sample5 WHERE id BETWEEN ? AND ?";
try
{
conn.prepareStatement(queryString);
conn.prepareStatement(queryString, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
conn.prepareStatement(queryString, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY,
ResultSet.HOLD_CURSORS_OVER_COMMIT);
}
catch (UnsupportedOperationException e)
{
fail("cannot prepareStatement!");
}
}
@Test
public void testCanUsePreparedStatement() throws SQLException
{
Properties props = new Properties();
props.put("extension", ".csv");
props.put("columnTypes", "Int,String,String,Timestamp,String");
Connection conn = DriverManager.getConnection("jdbc:relique:csv:"
+ filePath, props);
String queryString = "SELECT * FROM sample5 WHERE id BETWEEN ? AND ?";
PreparedStatement prepstmt = conn.prepareStatement(queryString);
prepstmt.setInt(1, 1);
prepstmt.setInt(2, 3);
ResultSet results = prepstmt.executeQuery();
assertTrue(results.next());
assertEquals("Integer column ID is wrong", new Integer(1), results
.getObject("id"));
assertTrue(results.next());
assertEquals("Integer column ID is wrong", new Integer(2), results
.getObject("id"));
assertTrue(results.next());
assertEquals("Integer column ID is wrong", new Integer(3), results
.getObject("id"));
assertFalse(results.next());
}
@Test
public void testPreparedStatementIsClosed() throws SQLException
{
Connection conn = DriverManager.getConnection("jdbc:relique:csv:" + filePath);
String queryString = "SELECT * FROM sample WHERE id = ?";
PreparedStatement prepstmt = conn.prepareStatement(queryString);
prepstmt.setString(1, "A123");
ResultSet results = prepstmt.executeQuery();
assertTrue(results.next());
assertEquals("Column EXTRA_FIELD is wrong", "A", results.getString("EXTRA_FIELD"));
conn.close();
assertTrue(prepstmt.isClosed());
}
@Test
public void testShortParameter() throws SQLException
{
Properties props = new Properties();
props.put("extension", ".csv");
props.put("columnTypes", "Short,String,String");
Connection conn = DriverManager.getConnection("jdbc:relique:csv:"
+ filePath, props);
String queryString = "SELECT * FROM sample4 WHERE id = ?";
PreparedStatement prepstmt = conn.prepareStatement(queryString);
prepstmt.setShort(1, (short)3);
ResultSet results = prepstmt.executeQuery();
assertTrue(results.next());
assertEquals("Column Job is wrong", "Finance Manager", results.getString("Job"));
assertFalse(results.next());
}
@Test
public void testLongParameter() throws SQLException
{
Properties props = new Properties();
props.put("headerline", "BLZ,BANK_NAME");
props.put("suppressHeaders", "true");
props.put("fileExtension", ".txt");
props.put("commentChar", "
props.put("columnTypes", "Long,String");
Connection conn = DriverManager.getConnection("jdbc:relique:csv:"
+ filePath, props);
String queryString = "SELECT * FROM banks WHERE BLZ = ?";
PreparedStatement prepstmt = conn.prepareStatement(queryString);
long blz = 10020200;
prepstmt.setLong(1, blz);
ResultSet results = prepstmt.executeQuery();
assertTrue(results.next());
assertEquals("Column BANK_NAME is wrong", "BHF-BANK (Berlin)", results.getString("BANK_NAME"));
assertFalse(results.next());
}
@Test
public void testFloatParameter() throws SQLException
{
Properties props = new Properties();
props.put("columnTypes", "Byte,Short,Integer,Long,Float,Double,BigDecimal");
Connection conn = DriverManager.getConnection("jdbc:relique:csv:"
+ filePath, props);
String queryString = "SELECT * FROM numeric WHERE C5 < ?";
PreparedStatement prepstmt = conn.prepareStatement(queryString);
prepstmt.setFloat(1, (float)3);
ResultSet results = prepstmt.executeQuery();
assertTrue(results.next());
assertEquals("Column C5 is wrong", "0.0", results.getString("C5"));
assertFalse(results.next());
}
@Test
public void testDoubleParameter() throws SQLException
{
Properties props = new Properties();
props.put("columnTypes", "Byte,Short,Integer,Long,Float,Double,BigDecimal");
Connection conn = DriverManager.getConnection("jdbc:relique:csv:"
+ filePath, props);
String queryString = "SELECT * FROM numeric WHERE C6 < ?";
PreparedStatement prepstmt = conn.prepareStatement(queryString);
prepstmt.setDouble(1, 1000.0);
ResultSet results = prepstmt.executeQuery();
assertTrue(results.next());
assertEquals("Column C6 is wrong", "-0.0", results.getString("C6"));
assertFalse(results.next());
}
@Test
public void testLike() throws SQLException
{
Properties props = new Properties();
props.put("columnTypes", "Int,String,String,Timestamp,String");
Connection conn = DriverManager.getConnection("jdbc:relique:csv:"
+ filePath, props);
String queryString = "SELECT * FROM sample5 WHERE Name LIKE ?";
PreparedStatement prepstmt = conn.prepareStatement(queryString);
prepstmt.setString(1, "%Lucero%");
ResultSet results = prepstmt.executeQuery();
assertTrue(results.next());
assertEquals("Column ID is wrong", 3, results.getInt("ID"));
assertFalse(results.next());
}
@Test
public void testCanReuseAPreparedStatement() throws SQLException
{
Properties props = new Properties();
props.put("extension", ".csv");
props.put("columnTypes", "Int,String,String,Timestamp,String");
Connection conn = DriverManager.getConnection("jdbc:relique:csv:"
+ filePath, props);
String queryString = "SELECT * FROM sample5 WHERE id BETWEEN ? AND ?";
PreparedStatement prepstmt = conn.prepareStatement(queryString);
prepstmt.setInt(1, 1);
prepstmt.setInt(2, 3);
ResultSet results1 = prepstmt.executeQuery();
assertTrue(results1.next());
assertTrue(results1.next());
assertTrue(results1.next());
assertFalse(results1.next());
prepstmt.setInt(1, 30);
prepstmt.setInt(2, 50);
ResultSet results2 = prepstmt.executeQuery();
assertTrue(results1.isClosed());
assertTrue(results2.next());
assertEquals("Integer column ID is wrong", new Integer(41), results2
.getObject("id"));
assertFalse(results2.next());
}
@Test
public void testCanUsePreparedStatementOnStrings() throws SQLException
{
Properties props = new Properties();
props.put("extension", ".csv");
props.put("columnTypes", "Int,String,String,Timestamp,String");
Connection conn = DriverManager.getConnection("jdbc:relique:csv:"
+ filePath, props);
String queryString = "SELECT * FROM sample5 WHERE job = ?";
PreparedStatement prepstmt = conn.prepareStatement(queryString);
prepstmt.setString(1, "Project Manager");
ResultSet results = prepstmt.executeQuery();
assertTrue(results.next());
assertEquals("Integer column ID is wrong", new Integer(1), results
.getObject("id"));
assertTrue(results.next());
assertEquals("Integer column ID is wrong", new Integer(3), results
.getObject("id"));
assertTrue(results.next());
assertEquals("Integer column ID is wrong", new Integer(4), results
.getObject("id"));
assertFalse(results.next());
prepstmt.setString(1, "Office Employee");
results = prepstmt.executeQuery();
assertTrue(results.next());
assertEquals("Integer column ID is wrong", new Integer(6), results
.getObject("id"));
assertTrue(results.next());
assertEquals("Integer column ID is wrong", new Integer(7), results
.getObject("id"));
assertTrue(results.next());
assertEquals("Integer column ID is wrong", new Integer(8), results
.getObject("id"));
assertTrue(results.next());
assertEquals("Integer column ID is wrong", new Integer(9), results
.getObject("id"));
assertFalse(results.next());
}
@Test
public void testNoWhereClause() throws SQLException
{
Properties props = new Properties();
props.put("extension", ".csv");
Connection conn = DriverManager.getConnection("jdbc:relique:csv:"
+ filePath, props);
String queryString = "SELECT * FROM sample5";
try
{
conn.prepareStatement(queryString);
}
catch (UnsupportedOperationException e)
{
fail("can't prepareStatement!");
}
}
@Test
public void testTableReader() throws SQLException
{
Connection conn = DriverManager.getConnection("jdbc:relique:csv:class:" +
TableReaderTester.class.getName());
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM airport where code=?");
stmt.setString(1, "CDG");
ResultSet results = stmt.executeQuery();
assertTrue(results.next());
assertEquals("NAME wrong", "Paris Charles De Gaulle", results.getString("NAME"));
assertFalse(results.next());
}
@Test
public void testPreparedStatementWithOrderBy() throws SQLException
{
Properties props = new Properties();
props.put("extension", ".csv");
props.put("columnTypes", "Int,String,String,Timestamp,String");
Connection conn = DriverManager.getConnection("jdbc:relique:csv:"
+ filePath, props);
String queryString = "SELECT * FROM sample5 where id > ? order by id";
PreparedStatement prepstmt = conn.prepareStatement(queryString);
prepstmt.setInt(1, 7);
ResultSet results = prepstmt.executeQuery();
assertTrue(results.next());
assertEquals("column ID is wrong", 8, results.getInt("ID"));
assertTrue(results.next());
assertEquals("column ID is wrong", 9, results.getInt("ID"));
assertTrue(results.next());
assertEquals("column ID is wrong", 41, results.getInt("ID"));
assertFalse(results.next());
results.close();
}
} |
package br.com.blackhubos.eventozero.handlers;
import br.com.blackhubos.eventozero.EventoZero;
import br.com.blackhubos.eventozero.ability.Ability;
import br.com.blackhubos.eventozero.factory.ItemFactory;
import java.util.Vector;
import org.bukkit.plugin.Plugin;
import com.google.common.base.Optional;
import br.com.blackhubos.eventozero.kit.Kit;
import br.com.blackhubos.eventozero.util.Framework;
import java.io.File;
public final class KitHandler {
private final Vector<Kit> kits;
public KitHandler() {
this.kits = new Vector<>();
}
public Optional<Kit> getKitByName(final String name) {
for (final Kit kit : this.getKits()) {
if (kit.getName().equals(name)) {
return Optional.of(kit);
}
}
return Optional.absent();
}
public Vector<Kit> getKits() {
return this.kits;
}
public void loadKits(final Plugin plugin) {
final File file = new File(plugin.getDataFolder() + File.separator + "kit" + File.separator + "kits.yml");
final Framework.Configuration configuration = new Framework.Configuration(file);
for (String key : configuration.getConfigurationSection("kits").getKeys(false)) {
Kit kit = new Kit(key, new ItemFactory(configuration.getString("kits." + key + ".icon"), null).getPreparedItem());
Optional<Ability> ability = AbilityHandler.getAbilityByName(configuration.getString("kits." + key + ".ability"));
if (ability.isPresent()) {
kit.updateAbility(ability.get()).
setArmorContents(3, new ItemFactory(configuration.getString("kits." + key + ".inventory.armor_contents.helmet"), null).getPreparedItem()).
setArmorContents(2, new ItemFactory(configuration.getString("kits." + key + ".inventory.armor_contents.armor"), null).getPreparedItem()).
setArmorContents(1, new ItemFactory(configuration.getString("kits." + key + ".inventory.armor_contents.leggings"), null).getPreparedItem()).
setArmorContents(0, new ItemFactory(configuration.getString("kits." + key + ".inventory.armor_contents.boots"), null).getPreparedItem());
}
int count = 0;
for (String otherKey : configuration.getStringList("kits." + key + ".inventory.contents")) {
kit.setContents(count, new ItemFactory(otherKey, null).getPreparedItem());
count++;
}
kits.add(kit);
}
EventoZero.consoleMessage("Formam carregado(s) " + kits.size() + " kit(s)");
}
} |
package ch.unizh.ini.jaer.projects.minliu;
import ch.unizh.ini.jaer.projects.davis.frames.ApsFrameExtractor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.util.logging.Level;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import com.jogamp.opengl.GL;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GL2ES3;
import com.jogamp.opengl.GLAutoDrawable;
import com.jogamp.opengl.util.awt.TextRenderer;
import ch.unizh.ini.jaer.projects.rbodo.opticalflow.AbstractMotionFlow;
import ch.unizh.ini.jaer.projects.rbodo.opticalflow.MotionFlowStatistics;
import ch.unizh.ini.jaer.projects.rbodo.opticalflow.MotionFlowStatistics.GlobalMotion;
import com.jogamp.opengl.GLException;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.ApsDvsEvent;
import net.sf.jaer.event.ApsDvsEventPacket;
import net.sf.jaer.event.BasicEvent;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.event.PolarityEvent;
import net.sf.jaer.eventio.AEInputStream;
import net.sf.jaer.eventprocessing.TimeLimiter;
import net.sf.jaer.graphics.AEViewer;
import net.sf.jaer.graphics.FrameAnnotater;
import net.sf.jaer.graphics.ImageDisplay;
import net.sf.jaer.graphics.ImageDisplay.Legend;
import net.sf.jaer.util.DrawGL;
import net.sf.jaer.util.EngineeringFormat;
import net.sf.jaer.util.TobiLogger;
import net.sf.jaer.util.filter.LowpassFilter;
import org.apache.commons.lang3.ArrayUtils;
/**
* Uses adaptive block matching optical flow (ABMOF) to measureTT local optical
* flow. <b>Not</b> gradient based, but rather matches local features backwards
* in time.
*
* @author Tobi and Min, Jan 2016
*/
@Description("<html>EDFLOW: Computes optical flow with vector direction using SFAST keypoint/corner detection and adaptive time slice block matching (ABMOF) as published in<br>"
+ "Liu, M., and Delbruck, T. (2018). <a href=\"http://bmvc2018.org/contents/papers/0280.pdf\">Adaptive Time-Slice Block-Matching Optical Flow Algorithm for Dynamic Vision Sensors</a>.<br> in BMVC 2018 (Nescatle upon Tyne)")
@DevelopmentStatus(DevelopmentStatus.Status.Experimental)
public class PatchMatchFlow extends AbstractMotionFlow implements FrameAnnotater {
/* LDSP is Large Diamond Search Pattern, and SDSP mens Small Diamond Search Pattern.
LDSP has 9 points and SDSP consists of 5 points.
*/
private static final int LDSP[][] = {{0, -2}, {-1, -1}, {1, -1}, {-2, 0}, {0, 0},
{2, 0}, {-1, 1}, {1, 1}, {0, 2}};
private static final int SDSP[][] = {{0, -1}, {-1, 0}, {0, 0}, {1, 0}, {0, 1}};
// private int[][][] histograms = null;
private int numSlices = 3; //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d
volatile private int numScales = getInt("numScales", 3); //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d
private String scalesToCompute = getString("scalesToCompute", ""); //getInt("numSlices", 3); // fix to 4 slices to compute error sign from min SAD result from t-2d to t-3d
private Integer[] scalesToComputeArray = null; // holds array of scales to actually compute, for debugging
private int[] scaleResultCounts = new int[numScales]; // holds counts at each scale for min SAD results
/**
* The computed average possible match distance from 0 motion
*/
protected float avgPossibleMatchDistance;
private static final int MIN_SLICE_EVENT_COUNT_FULL_FRAME = 1000;
private static final int MAX_SLICE_EVENT_COUNT_FULL_FRAME = 1000000;
// private int sx, sy;
private int currentSliceIdx = 0; // the slice we are currently filling with events
/**
* time slice 2d histograms of (maybe signed) event counts slices = new
* byte[numSlices][numScales][subSizeX][subSizeY] [slice][scale][x][y]
*/
private byte[][][][] slices = null;
private float[] sliceSummedSADValues = null; // tracks the total summed SAD differences between reference and past slices, to adjust the slice duration
private int[] sliceSummedSADCounts = null; // tracks the total summed SAD differences between reference and past slices, to adjust the slice duration
private int[] sliceStartTimeUs; // holds the time interval between reference slice and this slice
private int[] sliceEndTimeUs; // holds the time interval between reference slice and this slice
private byte[][][] currentSlice;
private SADResult lastGoodSadResult = new SADResult(0, 0, 0, 0); // used for consistency check
private int blockDimension = getInt("blockDimension", 7); // This is the block dimension of the coarse scale.
// private float cost = getFloat("cost", 0.001f);
private float maxAllowedSadDistance = getFloat("maxAllowedSadDistance", .5f);
private float validPixOccupancy = getFloat("validPixOccupancy", 0.01f); // threshold for valid pixel percent for one block
private float weightDistance = getFloat("weightDistance", 0.95f); // confidence value consists of the distance and the dispersion, this value set the distance value
private static final int MAX_SKIP_COUNT = 1000;
private int skipProcessingEventsCount = getInt("skipProcessingEventsCount", 0); // skip this many events for processing (but not for accumulating to bitmaps)
private int skipCounter = 0;
private boolean adaptiveEventSkipping = getBoolean("adaptiveEventSkipping", true);
private float skipChangeFactor = (float) Math.sqrt(2); // by what factor to change the skip count if too slow or too fast
private boolean outputSearchErrorInfo = false; // make user choose this slow down every time
private boolean adaptiveSliceDuration = getBoolean("adaptiveSliceDuration", true);
private boolean adaptiveSliceDurationLogging = false; // for debugging and analyzing control of slice event number/duration
private TobiLogger adaptiveSliceDurationLogger = null;
private int adaptiveSliceDurationPacketCount = 0;
private boolean useSubsampling = getBoolean("useSubsampling", false);
private int adaptiveSliceDurationMinVectorsToControl = getInt("adaptiveSliceDurationMinVectorsToControl", 10);
private boolean showBlockMatches = getBoolean("showBlockMatches", false); // Display the bitmaps
private boolean showSlices = false; // Display the bitmaps
private int showSlicesScale = 0; // Display the bitmaps
private float adapativeSliceDurationProportionalErrorGain = getFloat("adapativeSliceDurationProportionalErrorGain", 0.05f); // factor by which an error signal on match distance changes slice duration
private boolean adapativeSliceDurationUseProportionalControl = getBoolean("adapativeSliceDurationUseProportionalControl", false);
private int processingTimeLimitMs = getInt("processingTimeLimitMs", 100); // time limit for processing packet in ms to process OF events (events still accumulate). Overrides the system EventPacket timelimiter, which cannot be used here because we still need to accumulate and render the events.
private int sliceMaxValue = getInt("sliceMaxValue", 7);
private boolean rectifyPolarties = getBoolean("rectifyPolarties", false);
private int sliceDurationMinLimitUS = getInt("sliceDurationMinLimitUS", 100);
private int sliceDurationMaxLimitUS = getInt("sliceDurationMaxLimitUS", 300000);
private boolean outlierRejectionEnabled = getBoolean("outlierRejectionEnabled", false);
private float outlierRejectionThresholdSigma = getFloat("outlierRejectionThresholdSigma", 2f);
protected int outlierRejectionWindowSize=getInt("outlierRejectionWindowSize",300);
private MotionFlowStatistics outlierRejectionMotionFlowStatistics;
private TimeLimiter timeLimiter = new TimeLimiter(); // private instance used to accumulate events to slices even if packet has timed out
// results histogram for each packet
// private int ANGLE_HISTOGRAM_COUNT = 16;
// private int[] resultAngleHistogram = new int[ANGLE_HISTOGRAM_COUNT + 1];
private int[][] resultHistogram = null;
// private int resultAngleHistogramCount = 0, resultAngleHistogramMax = 0;
private int resultHistogramCount;
private volatile float avgMatchDistance = 0; // stores average match distance for rendering it
private float histStdDev = 0, lastHistStdDev = 0;
private float FSCnt = 0, DSCorrectCnt = 0;
float DSAverageNum = 0, DSAveError[] = {0, 0}; // Evaluate DS cost average number and the error.
// private float lastErrSign = Math.signum(1);
// private final String outputFilename;
private int sliceDeltaT; // The time difference between two slices used for velocity caluction. For constantDuration, this one is equal to the duration. For constantEventNumber, this value will change.
private boolean enableImuTimesliceLogging = false;
private TobiLogger imuTimesliceLogger = null;
private volatile boolean resetOFHistogramFlag; // signals to reset the OF histogram after it is rendered
private float cornerThr = getFloat("cornerThr", 0.2f);
private boolean saveSliceGrayImage = false;
private PrintWriter dvsWriter = null;
// These variables are only used by HW_ABMOF.
// HW_ABMOF send slice rotation flag so we need to indicate the real rotation timestamp
// HW_ABMOF is only supported for davis346Zynq
private int curretnRotatTs_HW = 0, tMinus1RotateTs_HW = 0, tMinus2RotateTs_HW = 0;
private float deltaTsMs_HW = 0;
private boolean HWABMOFEnabled = false;
public enum CornerCircleSelection {
InnerCircle, OuterCircle, OR, AND
}
private CornerCircleSelection cornerCircleSelection = CornerCircleSelection.valueOf(getString("cornerCircleSelection", CornerCircleSelection.OuterCircle.name())); // Tobi change to Outer which is the condition used for experimental results in paper
protected static String DEFAULT_FILENAME = "jAER.txt";
protected String lastFileName = getString("lastFileName", DEFAULT_FILENAME);
public enum PatchCompareMethod {
/*JaccardDistance,*/ /*HammingDistance*/
SAD/*, EventSqeDistance*/
};
private PatchCompareMethod patchCompareMethod = null;
public enum SearchMethod {
FullSearch, DiamondSearch, CrossDiamondSearch
};
private SearchMethod searchMethod = SearchMethod.valueOf(getString("searchMethod", SearchMethod.DiamondSearch.toString()));
private int sliceDurationUs = getInt("sliceDurationUs", 20000);
private int sliceEventCount = getInt("sliceEventCount", 1000);
private boolean rewindFlg = false; // The flag to indicate the rewind event.
private boolean displayResultHistogram = getBoolean("displayResultHistogram", true);
public enum SliceMethod {
ConstantDuration, ConstantEventNumber, AreaEventNumber, ConstantIntegratedFlow
};
private SliceMethod sliceMethod = SliceMethod.valueOf(getString("sliceMethod", SliceMethod.AreaEventNumber.toString()));
// counting events into subsampled areas, when count exceeds the threshold in any area, the slices are rotated
private int areaEventNumberSubsampling = getInt("areaEventNumberSubsampling", 5);
private int[][] areaCounts = null;
private int numAreas = 1;
private boolean areaCountExceeded = false;
// nongreedy flow evaluation
// the entire scene is subdivided into regions, and a bitmap of these regions distributed flow computation more fairly
// by only servicing a region when sufficient fraction of other regions have been serviced first
private boolean nonGreedyFlowComputingEnabled = getBoolean("nonGreedyFlowComputingEnabled", false);
private boolean[][] nonGreedyRegions = null;
private int nonGreedyRegionsNumberOfRegions, nonGreedyRegionsCount;
/**
* This fraction of the regions must be serviced for computing flow before
* we reset the nonGreedyRegions map
*/
private float nonGreedyFractionToBeServiced = getFloat("nonGreedyFractionToBeServiced", .5f);
// Print scale count's statics
private boolean printScaleCntStatEnabled = getBoolean("printScaleCntStatEnabled", false);
// timers and flags for showing filter properties temporarily
private final int SHOW_STUFF_DURATION_MS = 4000;
private volatile TimerTask stopShowingStuffTask = null;
private boolean showBlockSizeAndSearchAreaTemporarily = false;
private volatile boolean showAreaCountAreasTemporarily = false;
private int eventCounter = 0;
private int sliceLastTs = Integer.MAX_VALUE;
private JFrame blockMatchingFrame[] = new JFrame[numScales];
private JFrame blockMatchingFrameTarget[] = new JFrame[numScales];
private ImageDisplay blockMatchingImageDisplay[] = new ImageDisplay[numScales];
private ImageDisplay blockMatchingImageDisplayTarget[] = new ImageDisplay[numScales]; // makde a new ImageDisplay GLCanvas with default OpenGL capabilities
private Legend blockMatchingDisplayLegend[] = new Legend[numScales];
private Legend blockMatchingDisplayLegendTarget[] = new Legend[numScales];
private static final String LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH = "G: search area\nR: ref block area\nB: best match";
private JFrame sliceBitMapFrame = null;
private ImageDisplay sliceBitmapImageDisplay; // makde a new ImageDisplay GLCanvas with default OpenGL capabilities
private Legend sliceBitmapImageDisplayLegend;
private static final String LEGEND_SLICES = "R: Slice t-d\nG: Slice t-2d";
private JFrame timeStampBlockFrame = null;
private ImageDisplay timeStampBlockImageDisplay; // makde a new ImageDisplay GLCanvas with default OpenGL capabilities
private Legend timeStampBlockImageDisplayLegend;
private static final String TIME_STAMP_BLOCK_LEGEND_SLICES = "R: Inner Circle\nB: Outer Circle\nG: Current event";
private static final int circle1[][] = {{0, 1}, {1, 1}, {1, 0}, {1, -1},
{0, -1}, {-1, -1}, {-1, 0}, {-1, 1}};
private static final int circle2[][] = {{0, 2}, {1, 2}, {2, 1}, {2, 0},
{2, -1}, {1, -2}, {0, -2}, {-1, -2},
{-2, -1}, {-2, 0}, {-2, 1}, {-1, 2}};
private static final int circle3[][] = {{0, 3}, {1, 3}, {2, 2}, {3, 1},
{3, 0}, {3, -1}, {2, -2}, {1, -3},
{0, -3}, {-1, -3}, {-2, -2}, {-3, -1},
{-3, 0}, {-3, 1}, {-2, 2}, {-1, 3}};
private static final int circle4[][] = {{0, 4}, {1, 4}, {2, 3}, {3, 2},
{4, 1}, {4, 0}, {4, -1}, {3, -2},
{2, -3}, {1, -4}, {0, -4}, {-1, -4},
{-2, -3}, {-3, -2}, {-4, -1}, {-4, 0},
{-4, 1}, {-3, 2}, {-2, 3}, {-1, 4}};
int innerCircle[][] = circle1;
int innerCircleSize = innerCircle.length;
int xInnerOffset[] = new int[innerCircleSize];
int yInnerOffset[] = new int[innerCircleSize];
int innerTsValue[] = new int[innerCircleSize];
int outerCircle[][] = circle2;
int outerCircleSize = outerCircle.length;
int yOuterOffset[] = new int[outerCircleSize];
int xOuterOffset[] = new int[outerCircleSize];
int outerTsValue[] = new int[outerCircleSize];
private HWCornerPointRenderer keypointFilter = null;
/**
* A PropertyChangeEvent with this value is fired when the slices has been
* rotated. The oldValue is t-2d slice. The newValue is the t-d slice.
*/
public static final String EVENT_NEW_SLICES = "eventNewSlices";
TobiLogger sadValueLogger = new TobiLogger("sadvalues", "sadvalue,scale"); // TODO debug
private boolean calcOFonCornersEnabled = getBoolean("calcOFonCornersEnabled", true);
protected boolean useEFASTnotSFAST = getBoolean("useEFASTnotSFAST", false);
private final ApsFrameExtractor apsFrameExtractor;
// Corner events array; only used for rendering.
private boolean showCorners = getBoolean("showCorners", false);
private ArrayList<BasicEvent> cornerEvents = new ArrayList(1000);
public PatchMatchFlow(AEChip chip) {
super(chip);
getEnclosedFilterChain().clear();
// getEnclosedFilterChain().add(new SpatioTemporalCorrelationFilter(chip));
keypointFilter = new HWCornerPointRenderer(chip);
apsFrameExtractor = new ApsFrameExtractor(chip);
apsFrameExtractor.setShowAPSFrameDisplay(false);
getEnclosedFilterChain().add(apsFrameExtractor);
// getEnclosedFilterChain().add(keypointFilter); // use for EFAST
setSliceDurationUs(getSliceDurationUs()); // 40ms is good for the start of the slice duration adatative since 4ms is too fast and 500ms is too slow.
setDefaultScalesToCompute();
// // Save the result to the file
// Format formatter = new SimpleDateFormat("YYYY-MM-dd_hh-mm-ss");
// // Instantiate a Date object
// Date date = new Date();
// Log file for the OF distribution's statistics
// outputFilename = "PMF_HistStdDev" + formatter.format(date) + ".txt";
// String eventSqeMatching = "Event squence matching";
// String preProcess = "Denoise";
try {
patchCompareMethod = PatchCompareMethod.valueOf(getString("patchCompareMethod", PatchCompareMethod.SAD.toString()));
} catch (IllegalArgumentException e) {
patchCompareMethod = PatchCompareMethod.SAD;
}
String hwTip = "0b: Hardware EDFLOW";
setPropertyTooltip(hwTip, "HWABMOFEnabled", "Select to show output of hardware EDFLOW camera");
String cornerTip = "0c: Corners/Keypoints";
setPropertyTooltip(cornerTip, "showCorners", "Select to show corners (as red overlay)");
setPropertyTooltip(cornerTip, "cornerThr", "Threshold difference for SFAST detection as fraction of maximum event count value; increase for fewer corners");
setPropertyTooltip(cornerTip, "calcOFonCornersEnabled", "Calculate OF based on corners or not");
setPropertyTooltip(cornerTip, "cornerCircleSelection", "Determines SFAST circles used for detecting the corner/keypoint");
setPropertyTooltip(cornerTip, "useEFASTnotSFAST", "Use EFAST corner detector, not SFAST which is default");
String patchTT = "0a: Block matching";
setPropertyTooltip(patchTT, "blockDimension", "linear dimenion of patches to match on coarse scale, in pixels");
setPropertyTooltip(patchTT, "searchDistance", "search distance for matching patches, in pixels");
setPropertyTooltip(patchTT, "patchCompareMethod", "method to compare two patches; SAD=sum of absolute differences, HammingDistance is same as SAD for binary bitmaps");
setPropertyTooltip(patchTT, "searchMethod", "method to search patches");
setPropertyTooltip(patchTT, "sliceDurationUs", "duration of bitmaps in us, also called sample interval, when ConstantDuration method is used");
setPropertyTooltip(patchTT, "sliceEventCount", "number of events collected to fill a slice, when ConstantEventNumber method is used");
setPropertyTooltip(patchTT, "sliceMethod", "<html>Method for determining time slice duration for block matching<ul>"
+ "<li>ConstantDuration: slices are fixed time duration"
+ "<li>ConstantEventNumber: slices are fixed event number"
+ "<li>AreaEventNumber: slices are fixed event number in any subsampled area defined by areaEventNumberSubsampling"
+ "<li>ConstantIntegratedFlow: slices are rotated when average speeds times delta time exceeds half the search distance");
setPropertyTooltip(patchTT, "areaEventNumberSubsampling", "<html>how to subsample total area to count events per unit subsampling blocks for AreaEventNumber method. <p>For example, if areaEventNumberSubsampling=5, <br> then events falling into 32x32 blocks of pixels are counted <br>to determine when they exceed sliceEventCount to make new slice");
setPropertyTooltip(patchTT, "adapativeSliceDurationProportionalErrorGain", "gain for proporportional change of duration or slice event number. typically 0.05f for bang-bang, and 0.5f for proportional control");
setPropertyTooltip(patchTT, "adapativeSliceDurationUseProportionalControl", "If true, then use proportional error control. If false, use bang-bang control with sign of match distance error");
setPropertyTooltip(patchTT, "skipProcessingEventsCount", "skip this many events for processing (but not for accumulating to bitmaps)");
setPropertyTooltip(patchTT, "adaptiveEventSkipping", "enables adaptive event skipping depending on free time left in AEViewer animation loop");
setPropertyTooltip(patchTT, "adaptiveSliceDuration", "<html>Enables adaptive slice duration using feedback control, <br> based on average match search distance compared with total search distance. <p>If the match distance is too small, increaes duration or event count, and if too far, decreases duration or event count.<p>If using <i>AreaEventNumber</i> slice rotation method, don't increase count if actual duration is already longer than <i>sliceDurationUs</i>");
setPropertyTooltip(patchTT, "nonGreedyFlowComputingEnabled", "<html>Enables fairer distribution of computing flow by areas; an area is only serviced after " + nonGreedyFractionToBeServiced + " fraction of areas have been serviced. <p> Areas are defined by the the area subsubsampling bit shift.<p>Enabling this option ignores event skipping, so use <i>processingTimeLimitMs</i> to ensure minimum frame rate");
setPropertyTooltip(patchTT, "nonGreedyFractionToBeServiced", "An area is only serviced after " + nonGreedyFractionToBeServiced + " fraction of areas have been serviced. <p> Areas are defined by the the area subsubsampling bit shift.<p>Enabling this option ignores event skipping, so use the timeLimiter to ensure minimum frame rate");
setPropertyTooltip(patchTT, "useSubsampling", "<html>Enables using both full and subsampled block matching; <p>when using adaptiveSliceDuration, enables adaptive slice duration using feedback controlusing difference between full and subsampled resolution slice matching");
setPropertyTooltip(patchTT, "adaptiveSliceDurationMinVectorsToControl", "<html>Min flow vectors computed in packet to control slice duration, increase to reject control during idle periods");
setPropertyTooltip(patchTT, "processingTimeLimitMs", "<html>time limit for processing packet in ms to process OF events (events still accumulate). <br> Set to 0 to disable. <p>Alternative to the system EventPacket timelimiter, which cannot be used here because we still need to accumulate and render the events");
setPropertyTooltip(patchTT, "outputSearchErrorInfo", "enables displaying the search method error information");
setPropertyTooltip(patchTT, "outlierMotionFilteringEnabled", "(Currently has no effect) discards first optical flow event that points in opposite direction as previous one (dot product is negative)");
setPropertyTooltip(patchTT, "numSlices", "<html>Number of bitmaps to use. <p>At least 3: 1 to collect on, and two more to match on. <br>If >3, then best match is found between last slice reference block and all previous slices.");
setPropertyTooltip(patchTT, "numScales", "<html>Number of scales to search over for minimum SAD value; 1 for single full resolution scale, 2 for full + 2x2 subsampling, etc.");
setPropertyTooltip(patchTT, "sliceMaxValue", "<html> the maximum value used to represent each pixel in the time slice:<br>1 for binary or signed binary slice, (in conjunction with rectifyEventPolarities==true), etc, <br>up to 127 by these byte values");
setPropertyTooltip(patchTT, "rectifyPolarties", "<html> whether to rectify ON and OFF polarities to unsigned counts; true ignores polarity for block matching, false uses polarity with sliceNumBits>1");
setPropertyTooltip(patchTT, "scalesToCompute", "Scales to compute, e.g. 1,2; blank for all scales. 0 is full resolution, 1 is subsampled 2x2, etc");
setPropertyTooltip(patchTT, "defaults", "Sets reasonable defaults");
setPropertyTooltip(patchTT, "enableImuTimesliceLogging", "Logs IMU and rate gyro");
setPropertyTooltip(patchTT, "startRecordingForEDFLOW", "Start to record events and its OF result to a file which can be converted to a .bin file for EDFLOW.");
setPropertyTooltip(patchTT, "stopRecordingForEDFLOW", "Stop to record events and its OF result to a file which can be converted to a .bin file for EDFLOW.");
setPropertyTooltip(patchTT, "sliceDurationMinLimitUS", "The minimum value (us) of slice duration.");
setPropertyTooltip(patchTT, "sliceDurationMaxLimitUS", "The maximum value (us) of slice duration.");
setPropertyTooltip(patchTT, "outlierRejectionEnabled", "Enable outlier flow vector rejection");
setPropertyTooltip(patchTT, "outlierRejectionThresholdSigma", "Flow vectors that are larger than this many sigma from global flow variation are discarded");
setPropertyTooltip(patchTT, "outlierRejectionWindowSize", "Window in events for measurement of average flow for outlier rejection");
String metricConfid = "0ab: Density checks";
setPropertyTooltip(metricConfid, "maxAllowedSadDistance", "<html>SAD distance threshold for rejecting unresonable block matching result; <br> events with SAD distance larger than this value are rejected. <p>Lower value means it is harder to accept the event.");
setPropertyTooltip(metricConfid, "validPixOccupancy", "<html>Threshold for valid pixel percent for each block; Range from 0 to 1. <p>If either matching block is less occupied than this fraction, no motion vector will be calculated.");
setPropertyTooltip(metricConfid, "weightDistance", "<html>The confidence value consists of the distance and the dispersion; <br>weightDistance sets the weighting of the distance value compared with the dispersion value; Range from 0 to 1. <p>To count only e.g. hamming distance, set weighting to 1. <p> To count only dispersion, set to 0.");
String patchDispTT = "0b: Block matching display";
setPropertyTooltip(patchDispTT, "showSlices", "enables displaying the entire bitmaps slices (the current slices)");
setPropertyTooltip(patchDispTT, "showSlicesScale", "sets which scale of the slices to display");
setPropertyTooltip(patchDispTT, "showBlockMatches", "enables displaying the individual block matches");
setPropertyTooltip(patchDispTT, "ppsScale", "scale of pixels per second to draw local motion vectors; global vectors are scaled up by an additional factor of " + GLOBAL_MOTION_DRAWING_SCALE);
setPropertyTooltip(patchDispTT, "displayOutputVectors", "display the output motion vectors or not");
setPropertyTooltip(patchDispTT, "displayResultHistogram", "display the output motion vectors histogram to show disribution of results for each packet. Only implemented for HammingDistance");
setPropertyTooltip(patchDispTT, "printScaleCntStatEnabled", "enables printing the statics of scale counts");
getSupport().addPropertyChangeListener(AEViewer.EVENT_TIMESTAMPS_RESET, this);
getSupport().addPropertyChangeListener(AEViewer.EVENT_FILEOPEN, this);
getSupport().addPropertyChangeListener(AEInputStream.EVENT_REWOUND, this);
getSupport().addPropertyChangeListener(AEInputStream.EVENT_NON_MONOTONIC_TIMESTAMP, this);
computeAveragePossibleMatchDistance();
numInputTypes = 2; // allocate timestamp map
}
// TODO debug
public void doStartLogSadValues() {
sadValueLogger.setEnabled(true);
}
// TODO debug
public void doStopLogSadValues() {
sadValueLogger.setEnabled(false);
}
@Override
synchronized public EventPacket filterPacket(EventPacket in) {
setupFilter(in);
checkArrays();
if (processingTimeLimitMs > 0) {
timeLimiter.setTimeLimitMs(processingTimeLimitMs);
timeLimiter.restart();
} else {
timeLimiter.setEnabled(false);
}
int minDistScale = 0;
// following awkward block needed to deal with DVS/DAVIS and IMU/APS events
// block STARTS
Iterator i = null;
if (in instanceof ApsDvsEventPacket) {
i = ((ApsDvsEventPacket) in).fullIterator();
} else {
i = ((EventPacket) in).inputIterator();
}
cornerEvents.clear();
nSkipped = 0;
nProcessed = 0;
while (i.hasNext()) {
Object o = i.next();
if (o == null) {
log.warning("null event passed in, returning input packet");
return in;
}
if ((o instanceof ApsDvsEvent) && ((ApsDvsEvent) o).isApsData()) {
continue;
}
PolarityEvent ein = (PolarityEvent) o;
if (!extractEventInfo(o)) {
continue;
}
if (measureAccuracy || discardOutliersForStatisticalMeasurementEnabled) {
if (imuFlowEstimator.calculateImuFlow(o)) {
continue;
}
}
// block ENDS
if (xyFilter()) {
continue;
}
if (isInvalidTimestamp()) {
continue;
}
countIn++;
// compute flow
SADResult result = null;
if (HWABMOFEnabled) // Only use it when there is hardware supported. Hardware is davis346Zynq
{
SADResult sliceResult = new SADResult();
int data = ein.address & 0x7ff;
// The OF result from the hardware has following procotol:
// If the data is 0x7ff, it indicates that this result is an invalid result
// if the data is 0x7fe, then it means slice rotated on this event,
// in this case, only rotation information is included.
// Other cases are valid OF data.
// The valid OF data is represented in a compressed data format.
// It is calculated by OF_x * (2 * maxSearchDistanceRadius + 1) + OF_y.
// Therefore, simple decompress is required.
if ((data & 0x7ff) == 0x7ff) {
continue;
} else if ((data & 0x7ff) == 0x7fe) {
tMinus2RotateTs_HW = tMinus1RotateTs_HW;
tMinus1RotateTs_HW = curretnRotatTs_HW;
curretnRotatTs_HW = ts;
deltaTsMs_HW = (float) (tMinus1RotateTs_HW - tMinus2RotateTs_HW) / (float) 1000.0;
continue;
} else {
final int searchDistanceHW = 3; // hardcoded on hardware.
final int maxSearchDistanceRadius = (4 + 2 + 1) * searchDistanceHW;
int OF_x = (data / (2 * maxSearchDistanceRadius + 1)) - maxSearchDistanceRadius;
int OF_y = (data % (2 * maxSearchDistanceRadius + 1)) - maxSearchDistanceRadius;
sliceResult.dx = -OF_x;
sliceResult.dy = OF_y;
sliceResult.vx = (float) (1e3 * sliceResult.dx / deltaTsMs_HW);
sliceResult.vy = (float) (1e3 * sliceResult.dy / deltaTsMs_HW);
result = sliceResult;
vx = result.vx;
vy = result.vy;
v = (float) Math.sqrt((vx * vx) + (vy * vy));
cornerEvents.add(e);
}
} else {
float[] sadVals = new float[numScales]; // TODO debug
int[] dxInitVals = new int[numScales];
int[] dyInitVals = new int[numScales];
int rotateFlg = 0;
switch (patchCompareMethod) {
case SAD:
boolean rotated = maybeRotateSlices();
if (rotated) {
rotateFlg = 1;
adaptSliceDuration();
setResetOFHistogramFlag();
resetOFHistogram();
nCountPerSlicePacket = 0; // Reset counter for next slice packet.
}
nCountPerSlicePacket++;
// if (ein.x >= subSizeX || ein.y > subSizeY) {
// log.warning("event out of range");
// continue;
if (!accumulateEvent(ein)) { // maybe skip events here
if (dvsWriter != null) {
dvsWriter.println(String.format("%d %d %d %d %d %d %d %d %d", ein.timestamp, ein.x, ein.y, ein.polarity == PolarityEvent.Polarity.Off ? 0 : 1, 0x7, 0x7, 0, rotateFlg, 0));
}
break;
}
SADResult sliceResult = new SADResult();
minDistScale = 0;
boolean OFRetValidFlag = true;
// Sorts scalesToComputeArray[] in descending order
Arrays.sort(scalesToComputeArray, Collections.reverseOrder());
for (int scale : scalesToComputeArray) {
if (scale >= numScales) {
// log.warning("scale " + scale + " is out of range of " + numScales + "; fix scalesToCompute for example by clearing it");
// break;
}
int dx_init = ((result != null) && !isNotSufficientlyAccurate(sliceResult)) ? (sliceResult.dx >> scale) : 0;
int dy_init = ((result != null) && !isNotSufficientlyAccurate(sliceResult)) ? (sliceResult.dy >> scale) : 0;
// dx_init = 0;
// dy_init = 0;
// The reason why we inverse dx_init, dy_init i is the offset is pointing from previous slice to current slice.
// The dx_init, dy_init are from the corse scale's result, and it is used as the finer scale's initial guess.
sliceResult = minSADDistance(ein.x, ein.y, -dx_init, -dy_init, slices[sliceIndex(1)], slices[sliceIndex(2)], scale); // from ref slice to past slice k+1, using scale 0,1,....
// sliceSummedSADValues[sliceIndex(scale + 2)] += sliceResult.sadValue; // accumulate SAD for this past slice
// sliceSummedSADCounts[sliceIndex(scale + 2)]++; // accumulate SAD count for this past slice
// sliceSummedSADValues should end up filling 2 values for 4 slices
sadVals[scale] = sliceResult.sadValue; // TODO debug
dxInitVals[scale] = dx_init;
dyInitVals[scale] = dy_init;
if (sliceResult.sadValue >= this.maxAllowedSadDistance) {
OFRetValidFlag = false;
break;
} else {
if ((result == null) || (sliceResult.sadValue < result.sadValue)) {
result = sliceResult; // result holds the overall min sad result
minDistScale = scale;
}
}
// result=sliceResult; // TODO tobi: override the absolute minimum to always use the finest scale result, which has been guided by coarser scales
}
result = sliceResult;
minDistScale = 0;
float dt = (sliceDeltaTimeUs(2) * 1e-6f);
if (result != null) {
result.vx = result.dx / dt; // hack, convert to pix/second
result.vy = result.dy / dt; // TODO clean up, make time for each slice, since could be different when const num events
}
if (dvsWriter != null) {
dvsWriter.println(String.format("%d %d %d %d %d %d %d %d %d", ein.timestamp, ein.x, ein.y, ein.polarity == PolarityEvent.Polarity.Off ? 0 : 1, result.dx, result.dy, OFRetValidFlag ? 1 : 0, rotateFlg, 1));
}
break;
// case JaccardDistance:
// maybeRotateSlices();
// if (!accumulateEvent(in)) {
// break;
// result = minJaccardDistance(x, y, bitmaps[sliceIndex(2)], bitmaps[sliceIndex(1)]);
// float dtj=(sliceDeltaTimeUs(2) * 1e-6f);
// result.dx = result.dx / dtj;
// result.dy = result.dy / dtj;
// break;
}
if (result == null || result.sadValue == Float.MAX_VALUE) {
continue; // maybe some property change caused this
}
// reject values that are unreasonable
if (isNotSufficientlyAccurate(result)) {
continue;
}
scaleResultCounts[minDistScale]++;
vx = result.vx;
vy = result.vy;
v = (float) Math.sqrt((vx * vx) + (vy * vy));
// TODO debug
StringBuilder sadValsString = new StringBuilder();
for (int k = 0; k < sadVals.length - 1; k++) {
sadValsString.append(String.format("%f,", sadVals[k]));
}
sadValsString.append(String.format("%f", sadVals[sadVals.length - 1])); // very awkward to prevent trailing ,
if (sadValueLogger.isEnabled()) { // TODO debug
sadValueLogger.log(sadValsString.toString());
}
if (showBlockMatches) {
// TODO danger, drawing outside AWT thread
final SADResult thisResult = result;
final PolarityEvent thisEvent = ein;
final byte[][][][] thisSlices = slices;
// SwingUtilities.invokeLater(new Runnable() {
// @Override
// public void run() {
drawMatching(thisResult, thisEvent, thisSlices, sadVals, dxInitVals, dyInitVals); // ein.x >> result.scale, ein.y >> result.scale, (int) result.dx >> result.scale, (int) result.dy >> result.scale, slices[sliceIndex(1)][result.scale], slices[sliceIndex(2)][result.scale], result.scale);
drawTimeStampBlock(thisEvent);
}
}
if (isOutlierFlowVector(result)) {
countOutliers++;
continue;
}
// if (result.dx != 0 || result.dy != 0) {
// final int bin = (int) Math.round(ANGLE_HISTOGRAM_COUNT * (Math.atan2(result.dy, result.dx) + Math.PI) / (2 * Math.PI));
// int v = ++resultAngleHistogram[bin];
// resultAngleHistogramCount++;
// if (v > resultAngleHistogramMax) {
// resultAngleHistogramMax = v;
processGoodEvent();
if (resultHistogram != null) {
resultHistogram[result.dx + computeMaxSearchDistance()][result.dy + computeMaxSearchDistance()]++;
resultHistogramCount++;
}
lastGoodSadResult.set(result);
}
motionFlowStatistics.updatePacket(countIn, countOut, ts);
outlierRejectionMotionFlowStatistics.updatePacket(countIn, countOut, ts);
// float fracOutliers = (float) countOutliers / countIn;
// System.out.println(String.format("Fraction of outliers: %.1f%%", 100 * fracOutliers));
adaptEventSkipping();
if (rewindFlg) {
rewindFlg = false;
for (byte[][][] b : slices) {
clearSlice(b);
}
currentSliceIdx = 0; // start by filling slice 0
currentSlice = slices[currentSliceIdx];
sliceLastTs = Integer.MAX_VALUE;
}
return isDisplayRawInput() ? in : dirPacket;
}
public void doDefaults() {
setSearchMethod(SearchMethod.DiamondSearch);
setBlockDimension(21);
setNumScales(3);
setSearchDistance(3);
setAdaptiveEventSkipping(true);
setAdaptiveSliceDuration(true);
setMaxAllowedSadDistance(.5f);
setDisplayVectorsEnabled(true);
setPpsScaleDisplayRelativeOFLength(false);
setDisplayGlobalMotion(true);
setPpsScale(.1f);
setSliceMaxValue(15);
setRectifyPolarties(true); // rectify to better handle cases of steadicam where pan/tilt flips event polarities
setValidPixOccupancy(.01f); // at least this fraction of pixels from each block must both have nonzero values
setSliceMethod(SliceMethod.AreaEventNumber);
setSliceDurationMinLimitUS(1000);
setSliceDurationMaxLimitUS(300000);
setCalcOFonCornersEnabled(true); // Enable corner detector
// compute nearest power of two over block dimension
int ss = (int) (Math.log(blockDimension - 1) / Math.log(2));
setAreaEventNumberSubsampling(ss);
// set event count so that count=block area * sliceMaxValue/4;
// i.e. set count to roll over when slice pixels from most subsampled scale are half full if they are half stimulated
final int eventCount = (((blockDimension * blockDimension) * sliceMaxValue) / 2) >> (numScales - 1);
setSliceEventCount(eventCount);
setSliceDurationUs(50000); // set a bit smaller max duration in us to avoid instability where count gets too high with sparse input
}
private void adaptSliceDuration() {
// measure last hist to get control signal on slice duration
// measures avg match distance. weights the average so that long distances with more pixels in hist are not overcounted, simply
// by having more pixels.
if (rewindFlg) {
return; // don't adapt during rewind or delay before playing again
}
float radiusSum = 0;
int countSum = 0;
// int maxRadius = (int) Math.ceil(Math.sqrt(2 * searchDistance * searchDistance));
// int countSum = 0;
final int totSD = computeMaxSearchDistance();
for (int xx = -totSD; xx <= totSD; xx++) {
for (int yy = -totSD; yy <= totSD; yy++) {
int count = resultHistogram[xx + totSD][yy + totSD];
if (count > 0) {
final float radius = (float) Math.sqrt((xx * xx) + (yy * yy));
countSum += count;
radiusSum += radius * count;
}
}
}
if (countSum > 0) {
avgMatchDistance = radiusSum / (countSum); // compute average match distance from reference block
}
if (adaptiveSliceDuration && (countSum > adaptiveSliceDurationMinVectorsToControl)) {
// if (resultHistogramCount > 0) {
// following stats not currently used
// double[] rstHist1D = new double[resultHistogram.length * resultHistogram.length];
// int index = 0;
//// int rstHistMax = 0;
// for (int[] resultHistogram1 : resultHistogram) {
// for (int element : resultHistogram1) {
// rstHist1D[index++] = element;
// Statistics histStats = new Statistics(rstHist1D);
// // double histMax = Collections.max(Arrays.asList(ArrayUtils.toObject(rstHist1D)));
// double histMax = histStats.getMax();
// for (int m = 0; m < rstHist1D.length; m++) {
// rstHist1D[m] = rstHist1D[m] / histMax;
// lastHistStdDev = histStdDev;
// histStdDev = (float) histStats.getStdDev();
// try (FileWriter outFile = new FileWriter(outputFilename,true)) {
// outFile.write(String.format(in.getFirstEvent().getTimestamp() + " " + histStdDev + "\r\n"));
// outFile.close();
// } catch (IOException ex) {
// Logger.getLogger(PatchMatchFlow.class.getName()).log(Level.SEVERE, null, ex);
// } catch (Exception e) {
// log.warning("Caught " + e + ". See following stack trace.");
// e.printStackTrace();
// float histMean = (float) histStats.getMean();
// compute error signal.
// If err<0 it means the average match distance is larger than target avg match distance, so we need to reduce slice duration
// If err>0, it means the avg match distance is too short, so increse time slice
final float err = avgMatchDistance / (avgPossibleMatchDistance); // use target that is smaller than average possible to bound excursions to large slices better
// final float err = avgPossibleMatchDistance / 2 - avgMatchDistance; // use target that is smaller than average possible to bound excursions to large slices better
// final float err = ((searchDistance << (numScales - 1)) / 2) - avgMatchDistance;
// final float lastErr = searchDistance / 2 - lastHistStdDev;
// final double err = histMean - 1/ (rstHist1D.length * rstHist1D.length);
float errSign = Math.signum(err - 1);
// float avgSad2 = sliceSummedSADValues[sliceIndex(4)] / sliceSummedSADCounts[sliceIndex(4)];
// float avgSad3 = sliceSummedSADValues[sliceIndex(3)] / sliceSummedSADCounts[sliceIndex(3)];
// float errSign = avgSad2 <= avgSad3 ? 1 : -1;
// if(Math.abs(err) > Math.abs(lastErr)) {
// errSign = -errSign;
// if(histStdDev >= 0.14) {
// if(lastHistStdDev > histStdDev) {
// errSign = -lastErrSign;
// } else {
// errSign = lastErrSign;
// errSign = 1;
// } else {
// errSign = (float) Math.signum(err);
// lastErrSign = errSign;
// problem with following is that if sliceDurationUs gets really big, then of course the avgMatchDistance becomes small because
// of the biased-towards-zero search policy that selects the closest match
switch (sliceMethod) {
case ConstantDuration:
if (adapativeSliceDurationUseProportionalControl) { // proportional
setSliceDurationUs(Math.round((1 / (1 + (err - 1) * adapativeSliceDurationProportionalErrorGain)) * sliceDurationUs));
} else { // bang bang
int durChange = (int) (-errSign * adapativeSliceDurationProportionalErrorGain * sliceDurationUs);
setSliceDurationUs(sliceDurationUs + durChange);
}
break;
case ConstantEventNumber:
case AreaEventNumber:
if (adapativeSliceDurationUseProportionalControl) { // proportional
setSliceEventCount(Math.round((1 / (1 + (err - 1) * adapativeSliceDurationProportionalErrorGain)) * sliceEventCount));
} else {
if (errSign < 0) { // match distance too short, increase duration
// match too short, increase count
setSliceEventCount(Math.round(sliceEventCount * (1 + adapativeSliceDurationProportionalErrorGain)));
} else if (errSign > 0) { // match too long, decrease duration
setSliceEventCount(Math.round(sliceEventCount * (1 - adapativeSliceDurationProportionalErrorGain)));
}
}
break;
case ConstantIntegratedFlow:
setSliceEventCount(eventCounter);
}
if (adaptiveSliceDurationLogger != null && adaptiveSliceDurationLogger.isEnabled()) {
if (!isDisplayGlobalMotion()) {
setDisplayGlobalMotion(true);
}
adaptiveSliceDurationLogger.log(String.format("%f\t%d\t%d\t%f\t%f\t%f\t%d\t%d", e.timestamp * 1e-6f,
adaptiveSliceDurationPacketCount++, nCountPerSlicePacket, avgMatchDistance, err,
motionFlowStatistics.getGlobalMotion().getGlobalSpeed().getMean(), sliceDeltaT, sliceEventCount));
}
}
}
private void setResetOFHistogramFlag() {
resetOFHistogramFlag = true;
}
private void clearResetOFHistogramFlag() {
resetOFHistogramFlag = false;
}
private void resetOFHistogram() {
if (!resetOFHistogramFlag || resultHistogram == null) {
return;
}
for (int[] h : resultHistogram) {
Arrays.fill(h, 0);
}
resultHistogramCount = 0;
// Arrays.fill(resultAngleHistogram, 0);
// resultAngleHistogramCount = 0;
// resultAngleHistogramMax = Integer.MIN_VALUE;
// Print statics of scale count, only for debuuging.
if (printScaleCntStatEnabled) {
float sumScaleCounts = 0;
for (int scale : scalesToComputeArray) {
sumScaleCounts += scaleResultCounts[scale];
}
for (int scale : scalesToComputeArray) {
System.out.println("Scale " + scale + " count percentage is: " + scaleResultCounts[scale] / sumScaleCounts);
}
}
Arrays.fill(scaleResultCounts, 0);
clearResetOFHistogramFlag();
}
private EngineeringFormat engFmt = new EngineeringFormat();
private TextRenderer textRenderer = null;
@Override
synchronized public void annotate(GLAutoDrawable drawable) {
super.annotate(drawable);
GL2 gl = drawable.getGL().getGL2();
try {
gl.glEnable(GL.GL_BLEND);
gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
gl.glBlendEquation(GL.GL_FUNC_ADD);
} catch (GLException e) {
e.printStackTrace();
}
if (displayResultHistogram && (resultHistogram != null)) {
// draw histogram as shaded in 2d hist above color wheel
// normalize hist
int rhDim = resultHistogram.length; // this.computeMaxSearchDistance();
gl.glPushMatrix();
final float scale = 30f / rhDim; // size same as the color wheel
gl.glTranslatef(-35, .65f * chip.getSizeY(), 0); // center above color wheel
gl.glScalef(scale, scale, 1);
gl.glColor3f(0, 0, 1);
gl.glLineWidth(2f);
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex2f(0, 0);
gl.glVertex2f(rhDim, 0);
gl.glVertex2f(rhDim, rhDim);
gl.glVertex2f(0, rhDim);
gl.glEnd();
if (textRenderer == null) {
textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 64));
}
int max = 0;
for (int[] h : resultHistogram) {
for (int vv : h) {
if (vv > max) {
max = vv;
}
}
}
if (max == 0) {
gl.glTranslatef(0, rhDim / 2, 0); // translate to UL corner of histogram
textRenderer.begin3DRendering();
textRenderer.draw3D("No data", 0, 0, 0, .07f);
textRenderer.end3DRendering();
gl.glPopMatrix();
} else {
final float maxRecip = 2f / max;
gl.glPushMatrix();
// draw hist values
for (int xx = 0; xx < rhDim; xx++) {
for (int yy = 0; yy < rhDim; yy++) {
float g = maxRecip * resultHistogram[xx][yy];
gl.glColor3f(g, g, g);
gl.glBegin(GL2ES3.GL_QUADS);
gl.glVertex2f(xx, yy);
gl.glVertex2f(xx + 1, yy);
gl.glVertex2f(xx + 1, yy + 1);
gl.glVertex2f(xx, yy + 1);
gl.glEnd();
}
}
final int tsd = computeMaxSearchDistance();
if (avgMatchDistance > 0) {
gl.glPushMatrix();
gl.glColor4f(1f, 0, 0, .5f);
gl.glLineWidth(5f);
DrawGL.drawCircle(gl, tsd + .5f, tsd + .5f, avgMatchDistance, 16);
gl.glPopMatrix();
}
if (avgPossibleMatchDistance > 0) {
gl.glPushMatrix();
gl.glColor4f(0, 1f, 0, .5f);
gl.glLineWidth(5f);
DrawGL.drawCircle(gl, tsd + .5f, tsd + .5f, avgPossibleMatchDistance, 16); // draw circle at target match distance
gl.glPopMatrix();
}
// a bunch of cryptic crap to draw a string the same width as the histogram...
gl.glPopMatrix();
gl.glPopMatrix(); // back to original chip coordinates
gl.glPushMatrix();
textRenderer.begin3DRendering();
String s = String.format("dt=%.1f ms", 1e-3f * sliceDeltaT);
// final float sc = TextRendererScale.draw3dScale(textRenderer, s, chip.getCanvas().getScale(), chip.getWidth(), .1f);
// determine width of string in pixels and scale accordingly
FontRenderContext frc = textRenderer.getFontRenderContext();
Rectangle2D r = textRenderer.getBounds(s); // bounds in java2d coordinates, downwards more positive
Rectangle2D rt = frc.getTransform().createTransformedShape(r).getBounds2D(); // get bounds in textrenderer coordinates
// float ps = chip.getCanvas().getScale();
float w = (float) rt.getWidth(); // width of text in textrenderer, i.e. histogram cell coordinates (1 unit = 1 histogram cell)
float sc = subSizeX / w / 6; // scale to histogram width
gl.glTranslatef(0, .65f * subSizeY, 0); // translate to UL corner of histogram
textRenderer.draw3D(s, 0, 0, 0, sc);
String s2 = String.format("Skip: %d", skipProcessingEventsCount);
textRenderer.draw3D(s2, 0, (float) (rt.getHeight()) * sc, 0, sc);
String s3 = String.format("Slice events: %d", sliceEventCount);
textRenderer.draw3D(s3, 0, 2 * (float) (rt.getHeight()) * sc, 0, sc);
StringBuilder sb = new StringBuilder("Scale counts: ");
for (int c : scaleResultCounts) {
sb.append(String.format("%d ", c));
}
textRenderer.draw3D(sb.toString(), 0, (float) (3 * rt.getHeight()) * sc, 0, sc);
if (timeLimiter.isTimedOut()) {
String s4 = String.format("Timed out: skipped %d events", nSkipped);
textRenderer.draw3D(s4, 0, 4 * (float) (rt.getHeight()) * sc, 0, sc);
}
if (outlierRejectionEnabled) {
String s5 = String.format("Outliers: %%%.0f", 100 * (float) countOutliers / countIn);
textRenderer.draw3D(s5, 0, 5 * (float) (rt.getHeight()) * sc, 0, sc);
}
textRenderer.end3DRendering();
gl.glPopMatrix(); // back to original chip coordinates
// log.info(String.format("processed %.1f%% (%d/%d)", 100 * (float) nProcessed / (nSkipped + nProcessed), nProcessed, (nProcessed + nSkipped)));
// // draw histogram of angles around center of image
// if (resultAngleHistogramCount > 0) {
// gl.glPushMatrix();
// gl.glTranslatef(subSizeX / 2, subSizeY / 2, 0);
// gl.glLineWidth(getMotionVectorLineWidthPixels());
// gl.glColor3f(1, 1, 1);
// gl.glBegin(GL.GL_LINES);
// for (int i = 0; i < ANGLE_HISTOGRAM_COUNT; i++) {
// float l = ((float) resultAngleHistogram[i] / resultAngleHistogramMax) * chip.getMinSize() / 2; // bin 0 is angle -PI
// double angle = ((2 * Math.PI * i) / ANGLE_HISTOGRAM_COUNT) - Math.PI;
// float dx = (float) Math.cos(angle) * l, dy = (float) Math.sin(angle) * l;
// gl.glVertex2f(0, 0);
// gl.glVertex2f(dx, dy);
// gl.glEnd();
// gl.glPopMatrix();
}
}
if (sliceMethod == SliceMethod.AreaEventNumber && showAreaCountAreasTemporarily) {
int d = 1 << areaEventNumberSubsampling;
gl.glLineWidth(2f);
gl.glColor3f(1, 1, 1);
gl.glBegin(GL.GL_LINES);
for (int x = 0; x <= subSizeX; x += d) {
gl.glVertex2f(x, 0);
gl.glVertex2f(x, subSizeY);
}
for (int y = 0; y <= subSizeY; y += d) {
gl.glVertex2f(0, y);
gl.glVertex2f(subSizeX, y);
}
gl.glEnd();
}
if (sliceMethod == SliceMethod.ConstantIntegratedFlow && showAreaCountAreasTemporarily) {
// TODO fill in what to draw
}
if (showBlockSizeAndSearchAreaTemporarily) {
gl.glLineWidth(2f);
gl.glColor3f(1, 0, 0);
// show block size
final int xx = subSizeX / 2, yy = subSizeY / 2, d = blockDimension / 2;
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex2f(xx - d, yy - d);
gl.glVertex2f(xx + d, yy - d);
gl.glVertex2f(xx + d, yy + d);
gl.glVertex2f(xx - d, yy + d);
gl.glEnd();
// show search area
gl.glColor3f(0, 1, 0);
final int sd = d + (searchDistance << (numScales - 1));
gl.glBegin(GL.GL_LINE_LOOP);
gl.glVertex2f(xx - sd, yy - sd);
gl.glVertex2f(xx + sd, yy - sd);
gl.glVertex2f(xx + sd, yy + sd);
gl.glVertex2f(xx - sd, yy + sd);
gl.glEnd();
}
if (showCorners) {
gl.glColor4f(1f, 0, 0, 0.1f);
for (BasicEvent e : cornerEvents) {
gl.glPushMatrix();
DrawGL.drawBox(gl, e.x, e.y, 4, 4, 0);
gl.glPopMatrix();
}
}
}
@Override
public void initFilter() {
super.initFilter();
checkForEASTCornerDetectorEnclosedFilter();
outlierRejectionMotionFlowStatistics = new MotionFlowStatistics(this.getClass().getSimpleName(), subSizeX, subSizeY, outlierRejectionWindowSize);
outlierRejectionMotionFlowStatistics.setMeasureGlobalMotion(true);
}
@Override
public synchronized void resetFilter() {
setSubSampleShift(0); // filter breaks with super's bit shift subsampling
super.resetFilter();
eventCounter = 0;
// lastTs = Integer.MIN_VALUE;
checkArrays();
if (slices == null) {
return; // on reset maybe chip is not set yet
}
for (byte[][][] b : slices) {
clearSlice(b);
}
// currentSliceIdx = 0; // start by filling slice 0
// currentSlice = slices[currentSliceIdx];
// sliceLastTs = Integer.MAX_VALUE;
rewindFlg = true;
if (adaptiveEventSkippingUpdateCounterLPFilter != null) {
adaptiveEventSkippingUpdateCounterLPFilter.reset();
}
clearAreaCounts();
clearNonGreedyRegions();
}
private LowpassFilter speedFilter = new LowpassFilter();
/**
* uses the current event to maybe rotate the slices
*
* @return true if slices were rotated
*/
private boolean maybeRotateSlices() {
int dt = ts - sliceLastTs;
if (dt < 0) { // handle timestamp wrapping
// System.out.println("rotated slices at ");
// System.out.println("rotated slices with dt= "+dt);
rotateSlices();
eventCounter = 0;
sliceDeltaT = dt;
sliceLastTs = ts;
return true;
}
switch (sliceMethod) {
case ConstantDuration:
if ((dt < sliceDurationUs)) {
return false;
}
break;
case ConstantEventNumber:
if (eventCounter < sliceEventCount) {
return false;
}
break;
case AreaEventNumber:
// If dt is too small, we should rotate it later until it has enough accumulation time.
if (!areaCountExceeded && dt < getSliceDurationMaxLimitUS() || (dt < getSliceDurationMinLimitUS())) {
return false;
}
break;
case ConstantIntegratedFlow:
speedFilter.setTauMs(sliceDeltaTimeUs(2) >> 10);
final float meanGlobalSpeed = motionFlowStatistics.getGlobalMotion().meanGlobalSpeed;
if (!Float.isNaN(meanGlobalSpeed)) {
speedFilter.filter(meanGlobalSpeed, ts);
}
final float filteredMeanGlobalSpeed = speedFilter.getValue();
final float totalMovement = filteredMeanGlobalSpeed * dt * 1e-6f;
if (Float.isNaN(meanGlobalSpeed)) { // we need to rotate slices somwhow even if there is no motion computed yet
if (eventCounter < sliceEventCount) {
return false;
}
if ((dt < sliceDurationUs)) {
return false;
}
break;
}
if (totalMovement < searchDistance / 2 && dt < sliceDurationUs) {
return false;
}
break;
}
rotateSlices();
/* Slices have been rotated */
getSupport().firePropertyChange(PatchMatchFlow.EVENT_NEW_SLICES, slices[sliceIndex(1)], slices[sliceIndex(2)]);
return true;
}
void saveAPSImage() {
byte[] grayImageBuffer = new byte[sizex * sizey];
for (int y = 0; y < sizey; y++) {
for (int x = 0; x < sizex; x++) {
final int idx = x + (sizey - y - 1) * chip.getSizeX();
float bufferValue = apsFrameExtractor.getRawFrame()[idx];
grayImageBuffer[x + y * chip.getSizeX()] = (byte) (int) (bufferValue * 0.5f);
}
}
final BufferedImage theImage = new BufferedImage(chip.getSizeX(), chip.getSizeY(), BufferedImage.TYPE_BYTE_GRAY);
theImage.getRaster().setDataElements(0, 0, sizex, sizey, grayImageBuffer);
final Date d = new Date();
final String PNG = "png";
final String fn = "ApsFrame-" + sliceEndTimeUs[sliceIndex(1)] + "." + PNG;
// if user is playing a file, use folder that file lives in
String userDir = Paths.get(".").toAbsolutePath().normalize().toString();
File APSFrmaeDir = new File(userDir + File.separator + "APSFrames" + File.separator + getChip().getAeInputStream().getFile().getName());
if (!APSFrmaeDir.exists()) {
APSFrmaeDir.mkdirs();
}
File outputfile = new File(APSFrmaeDir + File.separator + fn);
try {
ImageIO.write(theImage, "png", outputfile);
} catch (IOException ex) {
Logger.getLogger(PatchMatchFlow.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Rotates slices by incrementing the slice pointer with rollover back to
* zero, and sets currentSliceIdx and currentBitmap. Clears the new
* currentBitmap. Thus the slice pointer increments. 0,1,2,0,1,2
*
*/
private void rotateSlices() {
if (e != null) {
sliceEndTimeUs[currentSliceIdx] = e.timestamp;
}
/*Thus if 0 is current index for current filling slice, then sliceIndex returns 1,2 for pointer =1,2.
* Then if NUM_SLICES=3, after rotateSlices(),
currentSliceIdx=NUM_SLICES-1=2, and sliceIndex(0)=2, sliceIndex(1)=0, sliceIndex(2)=1.
*/
sliceSummedSADValues[currentSliceIdx] = 0; // clear out current collecting slice which becomes the oldest slice after rotation
sliceSummedSADCounts[currentSliceIdx] = 0; // clear out current collecting slice which becomes the oldest slice after rotation
currentSliceIdx
if (currentSliceIdx < 0) {
currentSliceIdx = numSlices - 1;
}
currentSlice = slices[currentSliceIdx];
//sliceStartTimeUs[currentSliceIdx] = ts; // current event timestamp; set on first event to slice
clearSlice(currentSlice);
clearAreaCounts();
eventCounter = 0;
sliceDeltaT = ts - sliceLastTs;
sliceLastTs = ts;
if (imuTimesliceLogger != null && imuTimesliceLogger.isEnabled()) {
imuTimesliceLogger.log(String.format("%d %d %.3f", ts, sliceDeltaT, imuFlowEstimator.getPanRateDps()));
}
saveSliceGrayImage = true;
// if(e.timestamp == 213686212)
// saveAPSImage();
// saveSliceGrayImage = true;
if (isShowSlices() && !rewindFlg) {
// TODO danger, drawing outside AWT thread
final byte[][][][] thisSlices = slices;
// log.info("making runnable to draw slices in EDT");
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// will grab this instance. if called from AWT via e.g. slider, then can deadlock if we also invokeAndWait to draw something in ViewLoop
drawSlices(thisSlices);
}
});
}
}
/**
* Returns index to slice given pointer, with zero as current filling slice
* pointer.
*
*
* @param pointer how many slices in the past to index for. I.e.. 0 for
* current slice (one being currently filled), 1 for next oldest, 2 for
* oldest (when using NUM_SLICES=3).
* @return index into bitmaps[]
*/
private int sliceIndex(int pointer) {
return (currentSliceIdx + pointer) % numSlices;
}
/**
* returns slice delta time in us from reference slice
*
* @param pointer how many slices in the past to index for. I.e.. 0 for
* current slice (one being currently filled), 1 for next oldest, 2 for
* oldest (when using NUM_SLICES=3). Only meaningful for pointer>=2,
* currently exactly only pointer==2 since we are using only 3 slices.
*
* Modified to compute the delta time using the average of start and end
* timestamps of each slices, i.e. the slice time "midpoint" where midpoint
* is defined by average of first and last timestamp.
*
*/
protected int sliceDeltaTimeUs(int pointer) {
// System.out.println("dt(" + pointer + ")=" + (sliceStartTimeUs[sliceIndex(1)] - sliceStartTimeUs[sliceIndex(pointer)]));
int idxOlder = sliceIndex(pointer), idxYounger = sliceIndex(1);
int tOlder = (sliceStartTimeUs[idxOlder] + sliceEndTimeUs[idxOlder]) / 2;
int tYounger = (sliceStartTimeUs[idxYounger] + sliceEndTimeUs[idxYounger]) / 2;
int dt = tYounger - tOlder;
return dt;
}
private int nSkipped = 0, nProcessed = 0, nCountPerSlicePacket = 0;
/**
* Accumulates the current event to the current slice
*
* @return true if subsequent processing should done, false if it should be
* skipped for efficiency
*/
synchronized private boolean accumulateEvent(PolarityEvent e) {
if (eventCounter++ == 0) {
sliceStartTimeUs[currentSliceIdx] = e.timestamp; // current event timestamp
}
for (int s = 0; s < numScales; s++) {
final int xx = e.x >> s;
final int yy = e.y >> s;
// if (xx >= currentSlice[legendString].length || yy > currentSlice[legendString][xx].length) {
// log.warning("event out of range");
// return false;
int cv = currentSlice[s][xx][yy];
cv += rectifyPolarties ? 1 : (e.polarity == PolarityEvent.Polarity.On ? 1 : -1);
// cv = cv << (numScales - 1 - legendString);
if (cv > sliceMaxValue) {
cv = sliceMaxValue;
} else if (cv < -sliceMaxValue) {
cv = -sliceMaxValue;
}
currentSlice[s][xx][yy] = (byte) cv;
}
if (sliceMethod == SliceMethod.AreaEventNumber) {
if (areaCounts == null) {
clearAreaCounts();
}
int c = ++areaCounts[e.x >> areaEventNumberSubsampling][e.y >> areaEventNumberSubsampling];
if (c >= sliceEventCount) {
areaCountExceeded = true;
// int count=0, sum=0, sum2=0;
// StringBuilder sb=new StringBuilder("Area counts:\n");
// for(int[] i:areaCounts){
// for(int j:i){
// count++;
// sum+=j;
// sum2+=j*j;
// sb.append(String.format("%6d ",j));
// sb.append("\n");
// float m=(float)sum/count;
// float legendString=(float)Math.sqrt((float)sum2/count-m*m);
// sb.append(String.format("mean=%.1f, std=%.1f",m,legendString));
// log.info("area count stats "+sb.toString());
}
}
// detect if keypoint here
boolean isEASTCorner = (useEFASTnotSFAST && ((e.getAddress() & 1) == 1)); // supported only HWCornerPointRender or HW EFAST is used
boolean isBFASTCorner = PatchFastDetectorisFeature(e);
boolean isCorner = (useEFASTnotSFAST && isEASTCorner) || (!useEFASTnotSFAST && isBFASTCorner);
if (calcOFonCornersEnabled && !isCorner) {
return false;
}
cornerEvents.add(e);
if (timeLimiter.isTimedOut()) {
nSkipped++;
return false;
}
if (nonGreedyFlowComputingEnabled) {
// only process the event for flow if most of the other regions have already been processed
int xx = e.x >> areaEventNumberSubsampling, yy = e.y >> areaEventNumberSubsampling;
boolean didArea = nonGreedyRegions[xx][yy];
if (!didArea) {
nonGreedyRegions[xx][yy] = true;
nonGreedyRegionsCount++;
if (nonGreedyRegionsCount >= (int) (nonGreedyFractionToBeServiced * nonGreedyRegionsNumberOfRegions)) {
clearNonGreedyRegions();
}
nProcessed++;
return true; // skip counter is ignored
} else {
nSkipped++;
return false;
}
}
if (skipProcessingEventsCount == 0) {
nProcessed++;
return true;
}
if (skipCounter++ < skipProcessingEventsCount) {
nSkipped++;
return false;
}
nProcessed++;
skipCounter = 0;
return true;
}
// private void clearSlice(int idx) {
// for (int[] a : histograms[idx]) {
// Arrays.fill(a, 0);
private float sumArray[][] = null;
/**
* Computes block matching image difference best match around point x,y
* using blockDimension and searchDistance and scale
*
* @param x coordinate in subsampled space
* @param y
* @param dx_init initial offset
* @param dy_init
* @param prevSlice the slice over which we search for best match
* @param curSlice the slice from which we get the reference block
* @param subSampleBy the scale to compute this SAD on, 0 for full
* resolution, 1 for 2x2 subsampled block bitmap, etc
* @return SADResult that provides the shift and SAD value
*/
// private SADResult minHammingDistance(int x, int y, BitSet prevSlice, BitSet curSlice) {
private SADResult minSADDistance(int x, int y, int dx_init, int dy_init, byte[][][] curSlice, byte[][][] prevSlice, int subSampleBy) {
SADResult result = new SADResult();
float minSum = Float.MAX_VALUE, sum;
float FSDx = 0, FSDy = 0, DSDx = 0, DSDy = 0; // This is for testing the DS search accuracy.
final int searchRange = (2 * searchDistance) + 1; // The maximum search distance in this subSampleBy slice
if ((sumArray == null) || (sumArray.length != searchRange)) {
sumArray = new float[searchRange][searchRange];
} else {
for (float[] row : sumArray) {
Arrays.fill(row, Float.MAX_VALUE);
}
}
if (outputSearchErrorInfo) {
searchMethod = SearchMethod.FullSearch;
} else {
searchMethod = getSearchMethod();
}
final int xsub = (x >> subSampleBy) + dx_init;
final int ysub = (y >> subSampleBy) + dy_init;
final int r = ((blockDimension) / 2) << (numScales - 1 - subSampleBy);
int w = subSizeX >> subSampleBy, h = subSizeY >> subSampleBy;
// Make sure both ref block and past slice block are in bounds on all sides or there'll be arrayIndexOutOfBoundary exception.
// Also we don't want to match ref block only on inner sides or there will be a bias towards motion towards middle
if (xsub - r - searchDistance < 0 || xsub + r + searchDistance >= 1 * w
|| ysub - r - searchDistance < 0 || ysub + r + searchDistance >= 1 * h) {
result.sadValue = Float.MAX_VALUE; // return very large distance for this match so it is not selected
result.scale = subSampleBy;
return result;
}
switch (searchMethod) {
case DiamondSearch:
// SD = small diamond, LD=large diamond SP=search process
/* The center of the LDSP or SDSP could change in the iteration process,
so we need to use a variable to represent it.
In the first interation, it's the Zero Motion Potion (ZMP).
*/
int xCenter = x,
yCenter = y;
/* x offset of center point relative to ZMP, y offset of center point to ZMP.
x offset of center pointin positive number to ZMP, y offset of center point in positive number to ZMP.
*/
int dx,
dy,
xidx,
yidx; // x and y best match offsets in pixels, indices of these in 2d hist
int minPointIdx = 0; // Store the minimum point index.
boolean SDSPFlg = false; // If this flag is set true, then it means LDSP search is finished and SDSP search could start.
/* If one block has been already calculated, the computedFlg will be set so we don't to do
the calculation again.
*/
boolean computedFlg[][] = new boolean[searchRange][searchRange];
for (boolean[] row : computedFlg) {
Arrays.fill(row, false);
}
if (searchDistance == 1) { // LDSP search can only be applied for search distance >= 2.
SDSPFlg = true;
}
int iterationsLeft = searchRange * searchRange;
while (!SDSPFlg) {
/* 1. LDSP search */
for (int pointIdx = 0; pointIdx < LDSP.length; pointIdx++) {
dx = (LDSP[pointIdx][0] + xCenter) - x;
dy = (LDSP[pointIdx][1] + yCenter) - y;
xidx = dx + searchDistance;
yidx = dy + searchDistance;
// Point to be searched is out of search area, skip it.
if ((xidx >= searchRange) || (yidx >= searchRange) || (xidx < 0) || (yidx < 0)) {
continue;
}
/* We just calculate the blocks that haven't been calculated before */
if (computedFlg[xidx][yidx] == false) {
sumArray[xidx][yidx] = sadDistance(x, y, dx_init + dx, dy_init + dy, curSlice, prevSlice, subSampleBy);
computedFlg[xidx][yidx] = true;
if (outputSearchErrorInfo) {
DSAverageNum++;
}
if (outputSearchErrorInfo) {
if (sumArray[xidx][yidx] != sumArray[xidx][yidx]) { // TODO huh? this is never true, compares to itself
log.warning("It seems that there're some bugs in the DS algorithm.");
}
}
}
if (sumArray[xidx][yidx] <= minSum) {
minSum = sumArray[xidx][yidx];
minPointIdx = pointIdx;
}
}
/* 2. Check the minimum value position is in the center or not. */
xCenter = xCenter + LDSP[minPointIdx][0];
yCenter = yCenter + LDSP[minPointIdx][1];
if (minPointIdx == 4) { // It means it's in the center, so we should break the loop and go to SDSP search.
SDSPFlg = true;
}
if (--iterationsLeft < 0) {
log.warning("something is wrong with diamond search; did not find min in SDSP search");
SDSPFlg = true;
}
}
/* 3. SDSP Search */
for (int[] element : SDSP) {
dx = (element[0] + xCenter) - x;
dy = (element[1] + yCenter) - y;
xidx = dx + searchDistance;
yidx = dy + searchDistance;
// Point to be searched is out of search area, skip it.
if ((xidx >= searchRange) || (yidx >= searchRange) || (xidx < 0) || (yidx < 0)) {
continue;
}
/* We just calculate the blocks that haven't been calculated before */
if (computedFlg[xidx][yidx] == false) {
sumArray[xidx][yidx] = sadDistance(x, y, dx_init + dx, dy_init + dy, curSlice, prevSlice, subSampleBy);
computedFlg[xidx][yidx] = true;
if (outputSearchErrorInfo) {
DSAverageNum++;
}
if (outputSearchErrorInfo) {
if (sumArray[xidx][yidx] != sumArray[xidx][yidx]) {
log.warning("It seems that there're some bugs in the DS algorithm.");
}
}
}
if (sumArray[xidx][yidx] <= minSum) {
minSum = sumArray[xidx][yidx];
result.dx = -dx - dx_init; // minus is because result points to the past slice and motion is in the other direction
result.dy = -dy - dy_init;
result.sadValue = minSum;
}
// // debug
// if(result.dx==-searchDistance && result.dy==-searchDistance){
// System.out.println(result);
}
if (outputSearchErrorInfo) {
DSDx = result.dx;
DSDy = result.dy;
}
break;
case FullSearch:
if ((e.timestamp) == 81160149) {
System.out.printf("Scale %d with Refblock is: \n", subSampleBy);
int xscale = (x >> subSampleBy);
int yscale = (y >> subSampleBy);
for (int xx = xscale - r; xx <= (xscale + r); xx++) {
for (int yy = yscale - r; yy <= (yscale + r); yy++) {
System.out.printf("%d\t", curSlice[subSampleBy][xx][yy]);
}
System.out.printf("\n");
}
System.out.printf("\n");
System.out.printf("Tagblock is: \n");
for (int xx = xscale + dx_init - r - searchDistance; xx <= (xscale + dx_init + r + searchDistance); xx++) {
for (int yy = yscale + dy_init - r - searchDistance; yy <= (yscale + dy_init + r + searchDistance); yy++) {
System.out.printf("%d\t", prevSlice[subSampleBy][xx][yy]);
}
System.out.printf("\n");
}
}
for (dx = -searchDistance; dx <= searchDistance; dx++) {
for (dy = -searchDistance; dy <= searchDistance; dy++) {
sum = sadDistance(x, y, dx_init + dx, dy_init + dy, curSlice, prevSlice, subSampleBy);
sumArray[dx + searchDistance][dy + searchDistance] = sum;
if (sum < minSum) {
minSum = sum;
result.dx = -dx - dx_init; // minus is because result points to the past slice and motion is in the other direction
result.dy = -dy - dy_init;
result.sadValue = minSum;
}
}
}
// System.out.printf("result is %s: \n", result.toString());
if (outputSearchErrorInfo) {
FSCnt += 1;
FSDx = result.dx;
FSDy = result.dy;
} else {
break;
}
case CrossDiamondSearch:
break;
}
// compute the indices into 2d histogram of all motion vector results.
// It's a bit complicated because of multiple scales.
// Also, we want the indexes to be centered in the histogram array so that searches at full scale appear at the middle
// of the array and not at 0,0 corner.
// Suppose searchDistance=1 and numScales=2. Then the histogram has size 2*2+1=5.
// Therefore the scale 0 results need to have offset added to them to center results in histogram that
// shows results over all scales.
result.scale = subSampleBy;
// convert dx in search steps to dx in pixels including subsampling
// compute index assuming no subsampling or centering
result.xidx = (result.dx + dx_init) + searchDistance;
result.yidx = (result.dy + dy_init) + searchDistance;
// compute final dx and dy including subsampling
result.dx = (result.dx) << subSampleBy;
result.dy = (result.dy) << subSampleBy;
// compute final index including subsampling and centering
// idxCentering is shift needed to be applyed to store this result finally into the hist,
final int idxCentering = (searchDistance << (numScales - 1)) - ((searchDistance) << subSampleBy); // i.e. for subSampleBy=0 and numScales=2, shift=1 so that full scale search is centered in 5x5 hist
result.xidx = (result.xidx << subSampleBy) + idxCentering;
result.yidx = (result.yidx << subSampleBy) + idxCentering;
// if (result.xidx < 0 || result.yidx < 0 || result.xidx > maxIdx || result.yidx > maxIdx) {
// log.warning("something wrong with result=" + result);
// return null;
if (outputSearchErrorInfo) {
if ((DSDx == FSDx) && (DSDy == FSDy)) {
DSCorrectCnt += 1;
} else {
DSAveError[0] += Math.abs(DSDx - FSDx);
DSAveError[1] += Math.abs(DSDy - FSDy);
}
if (0 == (FSCnt % 10000)) {
log.log(Level.INFO, "Correct Diamond Search times are {0}, Full Search times are {1}, accuracy is {2}, averageNumberPercent is {3}, averageError is ({4}, {5})",
new Object[]{DSCorrectCnt, FSCnt, DSCorrectCnt / FSCnt, DSAverageNum / (searchRange * searchRange * FSCnt), DSAveError[0] / FSCnt, DSAveError[1] / (FSCnt - DSCorrectCnt)});
}
}
// if (tmpSadResult.xidx == searchRange-1 && tmpSadResult.yidx == searchRange-1) {
// tmpSadResult.sadValue = 1; // reject results to top right that are likely result of ambiguous search
return result;
}
/**
* computes Hamming distance centered on x,y with patch of patchSize for
* prevSliceIdx relative to curSliceIdx patch.
*
* @param xfull coordinate x in full resolution
* @param yfull coordinate y in full resolution
* @param dx the offset in pixels in the subsampled space of the past slice.
* The motion vector is then *from* this position *to* the current slice.
* @param dy
* @param prevSlice
* @param curSlice
* @param subsampleBy the scale to search over
* @return Distance value, max 1 when all pixels differ, min 0 when all the
* same
*/
private float sadDistance(final int xfull, final int yfull,
final int dx, final int dy,
final byte[][][] curSlice,
final byte[][][] prevSlice,
final int subsampleBy) {
final int x = xfull >> subsampleBy;
final int y = yfull >> subsampleBy;
final int r = ((blockDimension) / 2) << (numScales - 1 - subsampleBy);
// int w = subSizeX >> subsampleBy, h = subSizeY >> subsampleBy;
// int adx = dx > 0 ? dx : -dx; // abs val of dx and dy, to compute limits
// int ady = dy > 0 ? dy : -dy;
// // Make sure both ref block and past slice block are in bounds on all sides or there'll be arrayIndexOutOfBoundary exception.
// // Also we don't want to match ref block only on inner sides or there will be a bias towards motion towards middle
// if (x - r - adx < 0 || x + r + adx >= w
// || y - r - ady < 0 || y + r + ady >= h) {
// return 1; // tobi changed to 1 again // Float.MAX_VALUE; // return very large distance for this match so it is not selected
int validPixNumCurSlice = 0, validPixNumPrevSlice = 0; // The valid pixel number in the current block
int nonZeroMatchCount = 0;
// int saturatedPixNumCurSlice = 0, saturatedPixNumPrevSlice = 0; // The valid pixel number in the current block
int sumDist = 0;
// try {
for (int xx = x - r; xx <= (x + r); xx++) {
for (int yy = y - r; yy <= (y + r); yy++) {
// if (xx < 0 || yy < 0 || xx >= w || yy >= h
// || xx + dx < 0 || yy + dy < 0 || xx + dx >= w || yy + dy >= h) {
//// log.warning("out of bounds slice access; something wrong"); // TODO fix this check above
// continue;
int currSliceVal = curSlice[subsampleBy][xx][yy]; // binary value on (xx, yy) for current slice
int prevSliceVal = prevSlice[subsampleBy][xx + dx][yy + dy]; // binary value on (xx, yy) for previous slice at offset dx,dy in (possibly subsampled) slice
int dist = (currSliceVal - prevSliceVal);
if (dist < 0) {
dist = (-dist);
}
sumDist += dist;
// if (currSlicePol != prevSlicePol) {
// hd += 1;
// if (currSliceVal == sliceMaxValue || currSliceVal == -sliceMaxValue) {
// saturatedPixNumCurSlice++; // pixels that are not saturated
// if (prevSliceVal == sliceMaxValue || prevSliceVal == -sliceMaxValue) {
// saturatedPixNumPrevSlice++;
if (currSliceVal != 0) {
validPixNumCurSlice++; // pixels that are not saturated
}
if (prevSliceVal != 0) {
validPixNumPrevSlice++;
}
if (currSliceVal != 0 && prevSliceVal != 0) {
nonZeroMatchCount++; // pixels that both have events in them
}
}
}
// } catch (ArrayIndexOutOfBoundsException ex) {
// log.warning(ex.toString());
// debug
// if(dx==-1 && dy==-1) return 0; else return Float.MAX_VALUE;
sumDist = sumDist;
final int blockDim = (2 * r) + 1;
final int blockArea = (blockDim) * (blockDim); // TODO check math here for fraction correct with subsampling
// TODD: NEXT WORK IS TO DO THE RESEARCH ON WEIGHTED HAMMING DISTANCE
// Calculate the metric confidence value
final int minValidPixNum = (int) (this.validPixOccupancy * blockArea);
// final int maxSaturatedPixNum = (int) ((1 - this.validPixOccupancy) * blockArea);
final float sadNormalizer = 1f / (blockArea * (rectifyPolarties ? 2 : 1) * sliceMaxValue);
// if current or previous block has insufficient pixels with values or if all the pixels are filled up, then reject match
if ((validPixNumCurSlice < minValidPixNum)
|| (validPixNumPrevSlice < minValidPixNum)
|| (nonZeroMatchCount < minValidPixNum) // || (saturatedPixNumCurSlice >= maxSaturatedPixNum) || (saturatedPixNumPrevSlice >= maxSaturatedPixNum)
) { // If valid pixel number of any slice is 0, then we set the distance to very big value so we can exclude it.
return 1; // tobi changed to 1 to represent max distance // Float.MAX_VALUE;
} else {
/*
retVal consists of the distance and the dispersion. dispersion is used to describe the spatial relationship within one block.
Here we use the difference between validPixNumCurrSli and validPixNumPrevSli to calculate the dispersion.
Inspired by paper "Measuring the spatial dispersion of evolutionist search process: application to Walksat" by Alain Sidaner.
*/
final float finalDistance = sadNormalizer * ((sumDist * weightDistance) + (Math.abs(validPixNumCurSlice - validPixNumPrevSlice) * (1 - weightDistance)));
return finalDistance;
}
}
/**
* Computes hamming weight around point x,y using blockDimension and
* searchDistance
*
* @param x coordinate in subsampled space
* @param y
* @param prevSlice
* @param curSlice
* @return SADResult that provides the shift and SAD value
*/
// private SADResult minJaccardDistance(int x, int y, BitSet prevSlice, BitSet curSlice) {
// private SADResult minJaccardDistance(int x, int y, byte[][] prevSlice, byte[][] curSlice) {
// float minSum = Integer.MAX_VALUE, sum = 0;
// SADResult sadResult = new SADResult(0, 0, 0);
// for (int dx = -searchDistance; dx <= searchDistance; dx++) {
// for (int dy = -searchDistance; dy <= searchDistance; dy++) {
// sum = jaccardDistance(x, y, dx, dy, prevSlice, curSlice);
// if (sum <= minSum) {
// minSum = sum;
// sadResult.dx = dx;
// sadResult.dy = dy;
// sadResult.sadValue = minSum;
// return sadResult;
/**
* computes Hamming distance centered on x,y with patch of patchSize for
* prevSliceIdx relative to curSliceIdx patch.
*
* @param x coordinate in subSampled space
* @param y
* @param patchSize
* @param prevSlice
* @param curSlice
* @return SAD value
*/
// private float jaccardDistance(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) {
private float jaccardDistance(int x, int y, int dx, int dy, boolean[][] prevSlice, boolean[][] curSlice) {
float M01 = 0, M10 = 0, M11 = 0;
int blockRadius = blockDimension / 2;
// Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception.
if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius))
|| (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) {
return 1; // changed back to 1 // Float.MAX_VALUE;
}
for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) {
for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) {
final boolean c = curSlice[xx][yy], p = prevSlice[xx - dx][yy - dy];
if ((c == true) && (p == true)) {
M11 += 1;
}
if ((c == true) && (p == false)) {
M01 += 1;
}
if ((c == false) && (p == true)) {
M10 += 1;
}
// if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == true) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == true)) {
// M11 += 1;
// if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == true) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == false)) {
// M01 += 1;
// if ((curSlice.get((xx + 1) + ((yy) * subSizeX)) == false) && (prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)) == true)) {
// M10 += 1;
}
}
float retVal;
if (0 == (M01 + M10 + M11)) {
retVal = 0;
} else {
retVal = M11 / (M01 + M10 + M11);
}
retVal = 1 - retVal;
return retVal;
}
// private SADResult minVicPurDistance(int blockX, int blockY) {
// ArrayList<Integer[]> seq1 = new ArrayList(1);
// SADResult sadResult = new SADResult(0, 0, 0);
// int size = spikeTrains[blockX][blockY].size();
// int lastTs = spikeTrains[blockX][blockY].get(size - forwardEventNum)[0];
// for (int i = size - forwardEventNum; i < size; i++) {
// seq1.appendCopy(spikeTrains[blockX][blockY].get(i));
//// if(seq1.get(2)[0] - seq1.get(0)[0] > thresholdTime) {
//// return sadResult;
// double minium = Integer.MAX_VALUE;
// for (int i = -1; i < 2; i++) {
// for (int j = -1; j < 2; j++) {
// // Remove the seq1 itself
// if ((0 == i) && (0 == j)) {
// continue;
// ArrayList<Integer[]> seq2 = new ArrayList(1);
// if ((blockX >= 2) && (blockY >= 2)) {
// ArrayList<Integer[]> tmpSpikes = spikeTrains[blockX + i][blockY + j];
// if (tmpSpikes != null) {
// for (int index = 0; index < tmpSpikes.size(); index++) {
// if (tmpSpikes.get(index)[0] >= lastTs) {
// seq2.appendCopy(tmpSpikes.get(index));
// double dis = vicPurDistance(seq1, seq2);
// if (dis < minium) {
// minium = dis;
// sadResult.dx = -i;
// sadResult.dy = -j;
// lastFireIndex[blockX][blockY] = spikeTrains[blockX][blockY].size() - 1;
// if ((sadResult.dx != 1) || (sadResult.dy != 0)) {
// // sadResult = new SADResult(0, 0, 0);
// return sadResult;
// private double vicPurDistance(ArrayList<Integer[]> seq1, ArrayList<Integer[]> seq2) {
// int sum1Plus = 0, sum1Minus = 0, sum2Plus = 0, sum2Minus = 0;
// Iterator itr1 = seq1.iterator();
// Iterator itr2 = seq2.iterator();
// int length1 = seq1.size();
// int length2 = seq2.size();
// double[][] distanceMatrix = new double[length1 + 1][length2 + 1];
// for (int h = 0; h <= length1; h++) {
// for (int k = 0; k <= length2; k++) {
// if (h == 0) {
// distanceMatrix[h][k] = k;
// continue;
// if (k == 0) {
// distanceMatrix[h][k] = h;
// continue;
// double tmpMin = Math.min(distanceMatrix[h][k - 1] + 1, distanceMatrix[h - 1][k] + 1);
// double event1 = seq1.get(h - 1)[0] - seq1.get(0)[0];
// double event2 = seq2.get(k - 1)[0] - seq2.get(0)[0];
// distanceMatrix[h][k] = Math.min(tmpMin, distanceMatrix[h - 1][k - 1] + (cost * Math.abs(event1 - event2)));
// while (itr1.hasNext()) {
// Integer[] ii = (Integer[]) itr1.next();
// if (ii[1] == 1) {
// sum1Plus += 1;
// } else {
// sum1Minus += 1;
// while (itr2.hasNext()) {
// Integer[] ii = (Integer[]) itr2.next();
// if (ii[1] == 1) {
// sum2Plus += 1;
// } else {
// sum2Minus += 1;
// // return Math.abs(sum1Plus - sum2Plus) + Math.abs(sum1Minus - sum2Minus);
// return distanceMatrix[length1][length2];
// /**
// * Computes min SAD shift around point x,y using blockDimension and
// * searchDistance
// *
// * @param x coordinate in subsampled space
// * @param y
// * @param prevSlice
// * @param curSlice
// * @return SADResult that provides the shift and SAD value
// */
// private SADResult minSad(int x, int y, BitSet prevSlice, BitSet curSlice) {
// // for now just do exhaustive search over all shifts up to +/-searchDistance
// SADResult sadResult = new SADResult(0, 0, 0);
// float minSad = 1;
// for (int dx = -searchDistance; dx <= searchDistance; dx++) {
// for (int dy = -searchDistance; dy <= searchDistance; dy++) {
// float sad = sad(x, y, dx, dy, prevSlice, curSlice);
// if (sad <= minSad) {
// minSad = sad;
// sadResult.dx = dx;
// sadResult.dy = dy;
// sadResult.sadValue = minSad;
// return sadResult;
// /**
// * computes SAD centered on x,y with shift of dx,dy for prevSliceIdx
// * relative to curSliceIdx patch.
// *
// * @param x coordinate x in subSampled space
// * @param y coordinate y in subSampled space
// * @param dx block shift of x
// * @param dy block shift of y
// * @param prevSliceIdx
// * @param curSliceIdx
// * @return SAD value
// */
// private float sad(int x, int y, int dx, int dy, BitSet prevSlice, BitSet curSlice) {
// int blockRadius = blockDimension / 2;
// // Make sure 0<=xx+dx<subSizeX, 0<=xx<subSizeX and 0<=yy+dy<subSizeY, 0<=yy<subSizeY, or there'll be arrayIndexOutOfBoundary exception.
// if ((x < (blockRadius + dx)) || (x >= ((subSizeX - blockRadius) + dx)) || (x < blockRadius) || (x >= (subSizeX - blockRadius))
// || (y < (blockRadius + dy)) || (y >= ((subSizeY - blockRadius) + dy)) || (y < blockRadius) || (y >= (subSizeY - blockRadius))) {
// return Float.MAX_VALUE;
// float sad = 0, retVal = 0;
// float validPixNumCurrSli = 0, validPixNumPrevSli = 0; // The valid pixel number in the current block
// for (int xx = x - blockRadius; xx <= (x + blockRadius); xx++) {
// for (int yy = y - blockRadius; yy <= (y + blockRadius); yy++) {
// boolean currSlicePol = curSlice.get((xx + 1) + ((yy) * subSizeX)); // binary value on (xx, yy) for current slice
// boolean prevSlicePol = prevSlice.get(((xx + 1) - dx) + ((yy - dy) * subSizeX)); // binary value on (xx, yy) for previous slice
// int imuWarningDialog = (currSlicePol ? 1 : 0) - (prevSlicePol ? 1 : 0);
// if (currSlicePol == true) {
// validPixNumCurrSli += 1;
// if (prevSlicePol == true) {
// validPixNumPrevSli += 1;
// if (imuWarningDialog <= 0) {
// imuWarningDialog = -imuWarningDialog;
// sad += imuWarningDialog;
// // Calculate the metric confidence value
// float validPixNum = this.validPixOccupancy * (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1));
// if ((validPixNumCurrSli <= validPixNum) || (validPixNumPrevSli <= validPixNum)) { // If valid pixel number of any slice is 0, then we set the distance to very big value so we can exclude it.
// retVal = 1;
// } else {
// /*
// retVal is consisted of the distance and the dispersion, dispersion is used to describe the spatial relationship within one block.
// Here we use the difference between validPixNumCurrSli and validPixNumPrevSli to calculate the dispersion.
// Inspired by paper "Measuring the spatial dispersion of evolutionist search process: application to Walksat" by Alain Sidaner.
// */
// retVal = ((sad * weightDistance) + (Math.abs(validPixNumCurrSli - validPixNumPrevSli) * (1 - weightDistance))) / (((2 * blockRadius) + 1) * ((2 * blockRadius) + 1));
// return retVal;
private class SADResult {
int dx, dy; // best match offset in pixels to reference block from past slice block, i.e. motion vector points in this direction
float vx, vy; // optical flow in pixels/second corresponding to this match
float sadValue; // sum of absolute differences for this best match normalized by number of pixels in reference area
int xidx, yidx; // x and y indices into 2d matrix of result. 0,0 corresponds to motion SW. dx, dy may be negative, like (-1, -1) represents SW.
// However, for histgram index, it's not possible to use negative number. That's the reason for intrducing xidx and yidx.
// boolean minSearchedFlg = false; // The flag indicates that this minimum have been already searched before.
int scale;
/**
* Allocates new results initialized to zero
*/
public SADResult() {
this(0, 0, 0, 0);
}
public SADResult(int dx, int dy, float sadValue, int scale) {
this.dx = dx;
this.dy = dy;
this.sadValue = sadValue;
}
public void set(SADResult s) {
this.dx = s.dx;
this.dy = s.dy;
this.sadValue = s.sadValue;
this.xidx = s.xidx;
this.yidx = s.yidx;
this.scale = s.scale;
}
@Override
public String toString() {
return String.format("(dx,dy=%5d,%5d), (vx,vy=%.1f,%.1f px/s), SAD=%f, scale=%d", dx, dy, vx, vy, sadValue, scale);
}
}
private class Statistics {
double[] data;
int size;
public Statistics(double[] data) {
this.data = data;
size = data.length;
}
double getMean() {
double sum = 0.0;
for (double a : data) {
sum += a;
}
return sum / size;
}
double getVariance() {
double mean = getMean();
double temp = 0;
for (double a : data) {
temp += (a - mean) * (a - mean);
}
return temp / size;
}
double getStdDev() {
return Math.sqrt(getVariance());
}
public double median() {
Arrays.sort(data);
if ((data.length % 2) == 0) {
return (data[(data.length / 2) - 1] + data[data.length / 2]) / 2.0;
}
return data[data.length / 2];
}
public double getMin() {
Arrays.sort(data);
return data[0];
}
public double getMax() {
Arrays.sort(data);
return data[data.length - 1];
}
}
/**
* @return the blockDimension
*/
public int getBlockDimension() {
return blockDimension;
}
/**
* @param blockDimension the blockDimension to set
*/
synchronized public void setBlockDimension(int blockDimension) {
int old = this.blockDimension;
// enforce odd value
if ((blockDimension & 1) == 0) { // even
if (blockDimension > old) {
blockDimension++;
} else {
blockDimension
}
}
// clip final value
if (blockDimension < 1) {
blockDimension = 1;
} else if (blockDimension > 63) {
blockDimension = 63;
}
this.blockDimension = blockDimension;
getSupport().firePropertyChange("blockDimension", old, blockDimension);
putInt("blockDimension", blockDimension);
showBlockSizeAndSearchAreaTemporarily();
}
/**
* @return the sliceMethod
*/
public SliceMethod getSliceMethod() {
return sliceMethod;
}
/**
* @param sliceMethod the sliceMethod to set
*/
synchronized public void setSliceMethod(SliceMethod sliceMethod) {
SliceMethod old = this.sliceMethod;
this.sliceMethod = sliceMethod;
putString("sliceMethod", sliceMethod.toString());
if (sliceMethod == SliceMethod.AreaEventNumber || sliceMethod == SliceMethod.ConstantIntegratedFlow) {
showAreasForAreaCountsTemporarily();
}
// if(sliceMethod==SliceMethod.ConstantIntegratedFlow){
// setDisplayGlobalMotion(true);
getSupport().firePropertyChange("sliceMethod", old, this.sliceMethod);
}
public PatchCompareMethod getPatchCompareMethod() {
return patchCompareMethod;
}
synchronized public void setPatchCompareMethod(PatchCompareMethod patchCompareMethod) {
this.patchCompareMethod = patchCompareMethod;
putString("patchCompareMethod", patchCompareMethod.toString());
}
/**
*
* @return the search method
*/
public SearchMethod getSearchMethod() {
return searchMethod;
}
/**
*
* @param searchMethod the method to be used for searching
*/
synchronized public void setSearchMethod(SearchMethod searchMethod) {
SearchMethod old = this.searchMethod;
this.searchMethod = searchMethod;
putString("searchMethod", searchMethod.toString());
getSupport().firePropertyChange("searchMethod", old, this.searchMethod);
}
private int computeMaxSearchDistance() {
int sumScales = 0;
for (int i = 0; i < numScales; i++) {
sumScales += (1 << i);
}
return searchDistance * sumScales;
}
private void computeAveragePossibleMatchDistance() {
int n = 0;
double s = 0;
for (int xx = -searchDistance; xx <= searchDistance; xx++) {
for (int yy = -searchDistance; yy <= searchDistance; yy++) {
n++;
s += Math.sqrt((xx * xx) + (yy * yy));
}
}
double d = s / n; // avg for one scale
double s2 = 0;
for (int i = 0; i < numScales; i++) {
s2 += d * (1 << i);
}
double d2 = s2 / numScales;
avgPossibleMatchDistance = (float) d2;
log.info(String.format("searchDistance=%d numScales=%d: avgPossibleMatchDistance=%.1f", searchDistance, numScales, avgPossibleMatchDistance));
}
@Override
synchronized public void setSearchDistance(int searchDistance) {
int old = this.searchDistance;
if (searchDistance > 12) {
searchDistance = 12;
} else if (searchDistance < 1) {
searchDistance = 1; // limit size
}
this.searchDistance = searchDistance;
putInt("searchDistance", searchDistance);
getSupport().firePropertyChange("searchDistance", old, searchDistance);
resetFilter();
showBlockSizeAndSearchAreaTemporarily();
computeAveragePossibleMatchDistance();
}
/**
* @return the sliceDurationUs
*/
public int getSliceDurationUs() {
return sliceDurationUs;
}
/**
* @param sliceDurationUs the sliceDurationUs to set
*/
public void setSliceDurationUs(int sliceDurationUs) {
int old = this.sliceDurationUs;
if (sliceDurationUs < getSliceDurationMinLimitUS()) {
sliceDurationUs = getSliceDurationMinLimitUS();
} else if (sliceDurationUs > getSliceDurationMaxLimitUS()) {
sliceDurationUs = getSliceDurationMaxLimitUS(); // limit it to one second
}
this.sliceDurationUs = sliceDurationUs;
/* If the slice duration is changed, reset FSCnt and DScorrect so we can get more accurate evaluation result */
FSCnt = 0;
DSCorrectCnt = 0;
putInt("sliceDurationUs", sliceDurationUs);
getSupport().firePropertyChange("sliceDurationUs", old, this.sliceDurationUs);
}
/**
* @return the sliceEventCount
*/
public int getSliceEventCount() {
return sliceEventCount;
}
/**
* @param sliceEventCount the sliceEventCount to set
*/
public void setSliceEventCount(int sliceEventCount) {
final int div = sliceMethod == SliceMethod.AreaEventNumber ? numAreas : 1;
final int old = this.sliceEventCount;
if (sliceEventCount < MIN_SLICE_EVENT_COUNT_FULL_FRAME / div) {
sliceEventCount = MIN_SLICE_EVENT_COUNT_FULL_FRAME / div;
} else if (sliceEventCount > MAX_SLICE_EVENT_COUNT_FULL_FRAME / div) {
sliceEventCount = MAX_SLICE_EVENT_COUNT_FULL_FRAME / div;
}
this.sliceEventCount = sliceEventCount;
putInt("sliceEventCount", sliceEventCount);
getSupport().firePropertyChange("sliceEventCount", old, this.sliceEventCount);
}
public float getMaxAllowedSadDistance() {
return maxAllowedSadDistance;
}
public void setMaxAllowedSadDistance(float maxAllowedSadDistance) {
float old = this.maxAllowedSadDistance;
if (maxAllowedSadDistance < 0) {
maxAllowedSadDistance = 0;
} else if (maxAllowedSadDistance > 1) {
maxAllowedSadDistance = 1;
}
this.maxAllowedSadDistance = maxAllowedSadDistance;
putFloat("maxAllowedSadDistance", maxAllowedSadDistance);
getSupport().firePropertyChange("maxAllowedSadDistance", old, this.maxAllowedSadDistance);
}
public float getValidPixOccupancy() {
return validPixOccupancy;
}
public void setValidPixOccupancy(float validPixOccupancy) {
float old = this.validPixOccupancy;
if (validPixOccupancy < 0) {
validPixOccupancy = 0;
} else if (validPixOccupancy > 1) {
validPixOccupancy = 1;
}
this.validPixOccupancy = validPixOccupancy;
putFloat("validPixOccupancy", validPixOccupancy);
getSupport().firePropertyChange("validPixOccupancy", old, this.validPixOccupancy);
}
public float getWeightDistance() {
return weightDistance;
}
public void setWeightDistance(float weightDistance) {
if (weightDistance < 0) {
weightDistance = 0;
} else if (weightDistance > 1) {
weightDistance = 1;
}
this.weightDistance = weightDistance;
putFloat("weightDistance", weightDistance);
}
// private int totalFlowEvents=0, filteredOutFlowEvents=0;
// private boolean filterOutInconsistentEvent(SADResult result) {
// if (!isOutlierMotionFilteringEnabled()) {
// return false;
// totalFlowEvents++;
// if (lastGoodSadResult == null) {
// return false;
// if (result.dx * lastGoodSadResult.dx + result.dy * lastGoodSadResult.dy >= 0) {
// return false;
// filteredOutFlowEvents++;
// return true;
synchronized private void checkArrays() {
if (subSizeX == 0 || subSizeY == 0) {
return; // don't do on init when chip is not known yet
}
// numSlices = getInt("numSlices", 3); // since resetFilter is called in super before numSlices is even initialized
if (slices == null || slices.length != numSlices
|| slices[0] == null || slices[0].length != numScales) {
if (numScales > 0 && numSlices > 0) { // deal with filter reconstruction where these fields are not set
slices = new byte[numSlices][numScales][][];
for (int n = 0; n < numSlices; n++) {
for (int s = 0; s < numScales; s++) {
int nx = (subSizeX >> s) + 1 + blockDimension, ny = (subSizeY >> s) + 1 + blockDimension;
if (slices[n][s] == null || slices[n][s].length != nx
|| slices[n][s][0] == null || slices[n][s][0].length != ny) {
slices[n][s] = new byte[nx][ny];
}
}
}
currentSliceIdx = 0; // start by filling slice 0
currentSlice = slices[currentSliceIdx];
sliceLastTs = Integer.MAX_VALUE;
sliceStartTimeUs = new int[numSlices];
sliceEndTimeUs = new int[numSlices];
sliceSummedSADValues = new float[numSlices];
sliceSummedSADCounts = new int[numSlices];
}
// log.info("allocated slice memory");
}
// if (lastTimesMap != null) {
// lastTimesMap = null; // save memory
int rhDim = 2 * computeMaxSearchDistance() + 1; // e.g. coarse to fine search strategy
if ((resultHistogram == null) || (resultHistogram.length != rhDim)) {
resultHistogram = new int[rhDim][rhDim];
resultHistogramCount = 0;
}
checkNonGreedyRegionsAllocated();
}
/**
*
* @param distResult
* @return the confidence of the result. True means it's not good and should
* be rejected, false means we should accept it.
*/
private synchronized boolean isNotSufficientlyAccurate(SADResult distResult) {
boolean retVal = super.accuracyTests(); // check accuracy in super, if reject returns true
// additional test, normalized blaock distance must be small enough
// distance has max value 1
if (distResult.sadValue >= maxAllowedSadDistance) {
retVal = true;
}
return retVal;
}
/**
* @return the skipProcessingEventsCount
*/
public int getSkipProcessingEventsCount() {
return skipProcessingEventsCount;
}
/**
* @param skipProcessingEventsCount the skipProcessingEventsCount to set
*/
public void setSkipProcessingEventsCount(int skipProcessingEventsCount) {
int old = this.skipProcessingEventsCount;
if (skipProcessingEventsCount < 0) {
skipProcessingEventsCount = 0;
}
if (skipProcessingEventsCount > MAX_SKIP_COUNT) {
skipProcessingEventsCount = MAX_SKIP_COUNT;
}
this.skipProcessingEventsCount = skipProcessingEventsCount;
getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount);
putInt("skipProcessingEventsCount", skipProcessingEventsCount);
}
/**
* @return the displayResultHistogram
*/
public boolean isDisplayResultHistogram() {
return displayResultHistogram;
}
/**
* @param displayResultHistogram the displayResultHistogram to set
*/
public void setDisplayResultHistogram(boolean displayResultHistogram) {
this.displayResultHistogram = displayResultHistogram;
putBoolean("displayResultHistogram", displayResultHistogram);
}
/**
* @return the adaptiveEventSkipping
*/
public boolean isAdaptiveEventSkipping() {
return adaptiveEventSkipping;
}
/**
* @param adaptiveEventSkipping the adaptiveEventSkipping to set
*/
synchronized public void setAdaptiveEventSkipping(boolean adaptiveEventSkipping) {
boolean old = this.adaptiveEventSkipping;
this.adaptiveEventSkipping = adaptiveEventSkipping;
putBoolean("adaptiveEventSkipping", adaptiveEventSkipping);
if (adaptiveEventSkipping && adaptiveEventSkippingUpdateCounterLPFilter != null) {
adaptiveEventSkippingUpdateCounterLPFilter.reset();
}
getSupport().firePropertyChange("adaptiveEventSkipping", old, this.adaptiveEventSkipping);
}
public boolean isOutputSearchErrorInfo() {
return outputSearchErrorInfo;
}
public boolean isShowBlockMatches() {
return showBlockMatches;
}
/**
* @param showBlockMatches
* @param showBlockMatches the option of displaying bitmap
*/
synchronized public void setShowBlockMatches(boolean showBlockMatches) {
boolean old = this.showBlockMatches;
this.showBlockMatches = showBlockMatches;
putBoolean("showBlockMatches", showBlockMatches);
getSupport().firePropertyChange("showBlockMatches", old, this.showBlockMatches);
}
public boolean isShowSlices() {
return showSlices;
}
/**
* @param showSlices
* @param showSlices the option of displaying bitmap
*/
synchronized public void setShowSlices(boolean showSlices) {
boolean old = this.showSlices;
this.showSlices = showSlices;
getSupport().firePropertyChange("showSlices", old, this.showSlices);
putBoolean("showSlices", showSlices);
}
synchronized public void setOutputSearchErrorInfo(boolean outputSearchErrorInfo) {
this.outputSearchErrorInfo = outputSearchErrorInfo;
if (!outputSearchErrorInfo) {
searchMethod = SearchMethod.valueOf(getString("searchMethod", SearchMethod.FullSearch.toString())); // make sure method is reset
}
}
private LowpassFilter adaptiveEventSkippingUpdateCounterLPFilter = null;
private int adaptiveEventSkippingUpdateCounter = 0;
private void adaptEventSkipping() {
if (!adaptiveEventSkipping) {
return;
}
if (chip.getAeViewer() == null) {
return;
}
int old = skipProcessingEventsCount;
if (chip.getAeViewer().isPaused() || chip.getAeViewer().isSingleStep()) {
skipProcessingEventsCount = 0;
getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount);
}
if (adaptiveEventSkippingUpdateCounterLPFilter == null) {
adaptiveEventSkippingUpdateCounterLPFilter = new LowpassFilter(chip.getAeViewer().getFrameRater().FPS_LOWPASS_FILTER_TIMECONSTANT_MS);
}
final float averageFPS = chip.getAeViewer().getFrameRater().getAverageFPS();
final int frameRate = chip.getAeViewer().getDesiredFrameRate();
boolean skipMore = averageFPS < (int) (0.75f * frameRate);
boolean skipLess = averageFPS > (int) (0.25f * frameRate);
float newSkipCount = skipProcessingEventsCount;
if (skipMore) {
newSkipCount = adaptiveEventSkippingUpdateCounterLPFilter.filter(1 + (skipChangeFactor * skipProcessingEventsCount), 1000 * (int) System.currentTimeMillis());
} else if (skipLess) {
newSkipCount = adaptiveEventSkippingUpdateCounterLPFilter.filter((skipProcessingEventsCount / skipChangeFactor) - 1, 1000 * (int) System.currentTimeMillis());
}
skipProcessingEventsCount = Math.round(newSkipCount);
if (skipProcessingEventsCount > MAX_SKIP_COUNT) {
skipProcessingEventsCount = MAX_SKIP_COUNT;
} else if (skipProcessingEventsCount < 0) {
skipProcessingEventsCount = 0;
}
getSupport().firePropertyChange("skipProcessingEventsCount", old, this.skipProcessingEventsCount);
}
/**
* @return the adaptiveSliceDuration
*/
public boolean isAdaptiveSliceDuration() {
return adaptiveSliceDuration;
}
/**
* @param adaptiveSliceDuration the adaptiveSliceDuration to set
*/
synchronized public void setAdaptiveSliceDuration(boolean adaptiveSliceDuration) {
boolean old = this.adaptiveSliceDuration;
this.adaptiveSliceDuration = adaptiveSliceDuration;
putBoolean("adaptiveSliceDuration", adaptiveSliceDuration);
if (adaptiveSliceDurationLogging) {
if (adaptiveSliceDurationLogger == null) {
adaptiveSliceDurationLogger = new TobiLogger("PatchMatchFlow-SliceDurationControl", "slice duration or event count control logging");
adaptiveSliceDurationLogger.setColumnHeaderLine("eventTsSec\tpacketNumber\tpacketEvenNumber\tavgMatchDistance\tmatchRadiusError\tglobalTranslationSpeedPPS\tsliceDurationUs\tsliceEventCount");
adaptiveSliceDurationLogger.setSeparator("\t");
}
adaptiveSliceDurationLogger.setEnabled(adaptiveSliceDuration);
}
getSupport().firePropertyChange("adaptiveSliceDuration", old, this.adaptiveSliceDuration);
}
/**
* @return the processingTimeLimitMs
*/
public int getProcessingTimeLimitMs() {
return processingTimeLimitMs;
}
/**
* @param processingTimeLimitMs the processingTimeLimitMs to set
*/
public void setProcessingTimeLimitMs(int processingTimeLimitMs) {
this.processingTimeLimitMs = processingTimeLimitMs;
putInt("processingTimeLimitMs", processingTimeLimitMs);
}
/**
* clears all scales for a particular time slice
*
* @param slice [scale][x][y]
*/
private void clearSlice(byte[][][] slice) {
for (byte[][] scale : slice) { // for each scale
for (byte[] row : scale) { // for each col
Arrays.fill(row, (byte) 0); // fill col
}
}
}
private int dim = blockDimension + (2 * searchDistance);
/**
* Draws the block matching bitmap
*
* @param x
* @param y
* @param dx
* @param dy
* @param refBlock
* @param searchBlock
* @param subSampleBy
*/
synchronized private void drawMatching(SADResult result, PolarityEvent ein, byte[][][][] slices, float[] sadVals, int[] dxInitVals, int[] dyInitVals) {
// synchronized private void drawMatching(int x, int y, int dx, int dy, byte[][] refBlock, byte[][] searchBlock, int subSampleBy) {
for (int dispIdx = 0; dispIdx < numScales; dispIdx++) {
int x = ein.x >> dispIdx, y = ein.y >> dispIdx;
int dx = (int) result.dx >> dispIdx, dy = (int) result.dy >> dispIdx;
byte[][] refBlock = slices[sliceIndex(1)][dispIdx], searchBlock = slices[sliceIndex(2)][dispIdx];
int subSampleBy = dispIdx;
Legend sadLegend = null;
final int refRadius = (blockDimension / 2) << (numScales - 1 - dispIdx);
int dimNew = refRadius * 2 + 1 + (2 * (searchDistance));
if (blockMatchingFrame[dispIdx] == null) {
String windowName = "Ref Block " + dispIdx;
blockMatchingFrame[dispIdx] = new JFrame(windowName);
blockMatchingFrame[dispIdx].setLayout(new BoxLayout(blockMatchingFrame[dispIdx].getContentPane(), BoxLayout.Y_AXIS));
blockMatchingFrame[dispIdx].setPreferredSize(new Dimension(600, 600));
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
blockMatchingImageDisplay[dispIdx] = ImageDisplay.createOpenGLCanvas();
blockMatchingImageDisplay[dispIdx].setBorderSpacePixels(10);
blockMatchingImageDisplay[dispIdx].setImageSize(dimNew, dimNew);
blockMatchingImageDisplay[dispIdx].setSize(200, 200);
blockMatchingImageDisplay[dispIdx].setGrayValue(0);
blockMatchingDisplayLegend[dispIdx] = blockMatchingImageDisplay[dispIdx].addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim);
panel.add(blockMatchingImageDisplay[dispIdx]);
blockMatchingFrame[dispIdx].getContentPane().add(panel);
blockMatchingFrame[dispIdx].pack();
blockMatchingFrame[dispIdx].addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setShowBlockMatches(false);
}
});
}
if (!blockMatchingFrame[dispIdx].isVisible()) {
blockMatchingFrame[dispIdx].setVisible(true);
}
if (blockMatchingFrameTarget[dispIdx] == null) {
String windowName = "Target Block " + dispIdx;
blockMatchingFrameTarget[dispIdx] = new JFrame(windowName);
blockMatchingFrameTarget[dispIdx].setLayout(new BoxLayout(blockMatchingFrameTarget[dispIdx].getContentPane(), BoxLayout.Y_AXIS));
blockMatchingFrameTarget[dispIdx].setPreferredSize(new Dimension(600, 600));
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
blockMatchingImageDisplayTarget[dispIdx] = ImageDisplay.createOpenGLCanvas();
blockMatchingImageDisplayTarget[dispIdx].setBorderSpacePixels(10);
blockMatchingImageDisplayTarget[dispIdx].setImageSize(dimNew, dimNew);
blockMatchingImageDisplayTarget[dispIdx].setSize(200, 200);
blockMatchingImageDisplayTarget[dispIdx].setGrayValue(0);
blockMatchingDisplayLegendTarget[dispIdx] = blockMatchingImageDisplayTarget[dispIdx].addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim);
panel.add(blockMatchingImageDisplayTarget[dispIdx]);
blockMatchingFrameTarget[dispIdx].getContentPane().add(panel);
blockMatchingFrameTarget[dispIdx].pack();
blockMatchingFrameTarget[dispIdx].addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setShowBlockMatches(false);
}
});
}
if (!blockMatchingFrameTarget[dispIdx].isVisible()) {
blockMatchingFrameTarget[dispIdx].setVisible(true);
}
final int radius = (refRadius) + searchDistance;
float scale = 1f / getSliceMaxValue();
try {
// if ((x >= radius) && ((x + radius) < subSizeX)
// && (y >= radius) && ((y + radius) < subSizeY))
{
if (dimNew != blockMatchingImageDisplay[dispIdx].getWidth()) {
dim = dimNew;
blockMatchingImageDisplay[dispIdx].setImageSize(dimNew, dimNew);
blockMatchingImageDisplay[dispIdx].clearLegends();
blockMatchingDisplayLegend[dispIdx] = blockMatchingImageDisplay[dispIdx].addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim);
}
if (dimNew != blockMatchingImageDisplayTarget[dispIdx].getWidth()) {
dim = dimNew;
blockMatchingImageDisplayTarget[dispIdx].setImageSize(dimNew, dimNew);
blockMatchingImageDisplayTarget[dispIdx].clearLegends();
blockMatchingDisplayLegendTarget[dispIdx] = blockMatchingImageDisplayTarget[dispIdx].addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim);
}
// TextRenderer textRenderer = new TextRenderer(new Font("SansSerif", Font.PLAIN, 12));
if (blockMatchingDisplayLegend[dispIdx] != null) {
blockMatchingDisplayLegend[dispIdx].setLegendString("R: ref block area"
+ "\nScale: "
+ subSampleBy
+ "\nSAD: "
+ engFmt.format(sadVals[dispIdx])
+ "\nTimestamp: " + ein.timestamp);
}
if (blockMatchingDisplayLegendTarget[dispIdx] != null) {
blockMatchingDisplayLegendTarget[dispIdx].setLegendString("G: search area"
+ "\nx: " + ein.x
+ "\ny: " + ein.y
+ "\ndx_init: " + dxInitVals[dispIdx]
+ "\ndy_init: " + dyInitVals[dispIdx]);
}
/* Reset the image first */
blockMatchingImageDisplay[dispIdx].clearImage();
blockMatchingImageDisplayTarget[dispIdx].clearImage();
/* Rendering the reference patch in t-imuWarningDialog slice, it's on the center with color red */
for (int i = searchDistance; i < (refRadius * 2 + 1 + searchDistance); i++) {
for (int j = searchDistance; j < (refRadius * 2 + 1 + searchDistance); j++) {
float[] f = blockMatchingImageDisplay[dispIdx].getPixmapRGB(i, j);
// Scale the pixel value to make it brighter for finer scale slice.
f[0] = (1 << (numScales - 1 - dispIdx)) * scale * Math.abs(refBlock[((x - (refRadius)) + i) - searchDistance][((y - (refRadius)) + j) - searchDistance]);
blockMatchingImageDisplay[dispIdx].setPixmapRGB(i, j, f);
}
}
/* Rendering the area within search distance in t-2d slice, it's full of the whole search area with color green */
for (int i = 0; i < ((2 * radius) + 1); i++) {
for (int j = 0; j < ((2 * radius) + 1); j++) {
float[] f = blockMatchingImageDisplayTarget[dispIdx].getPixmapRGB(i, j);
f[1] = scale * Math.abs(searchBlock[(x - dxInitVals[dispIdx] - radius) + i][(y - dyInitVals[dispIdx] - radius) + j]);
blockMatchingImageDisplayTarget[dispIdx].setPixmapRGB(i, j, f);
}
}
/* Rendering the best matching patch in t-2d slice, it's on the shifted position related to the center location with color blue */
// for (int i = searchDistance + dx; i < (blockDimension + searchDistance + dx); i++) {
// for (int j = searchDistance + dy; j < (blockDimension + searchDistance + dy); j++) {
// float[] f = blockMatchingImageDisplayTarget[dispIdx].getPixmapRGB(i, j);
// f[2] = scale * Math.abs(searchBlock[((x - (blockDimension / 2)) + i) - searchDistance][((y - (blockDimension / 2)) + j) - searchDistance]);
// blockMatchingImageDisplayTarget[dispIdx].setPixmapRGB(i, j, f);
}
} catch (ArrayIndexOutOfBoundsException e) {
}
blockMatchingImageDisplay[dispIdx].repaint();
blockMatchingImageDisplayTarget[dispIdx].repaint();
}
}
synchronized private void drawTimeStampBlock(PolarityEvent ein) {
int dim = 11;
int sliceScale = 2;
int eX = ein.x >> sliceScale, eY = ein.y >> sliceScale, eType = ein.type;
if (timeStampBlockFrame == null) {
String windowName = "FASTCornerBlock";
timeStampBlockFrame = new JFrame(windowName);
timeStampBlockFrame.setLayout(new BoxLayout(timeStampBlockFrame.getContentPane(), BoxLayout.Y_AXIS));
timeStampBlockFrame.setPreferredSize(new Dimension(600, 600));
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
timeStampBlockImageDisplay = ImageDisplay.createOpenGLCanvas();
timeStampBlockImageDisplay.setBorderSpacePixels(10);
timeStampBlockImageDisplay.setImageSize(dim, dim);
timeStampBlockImageDisplay.setSize(200, 200);
timeStampBlockImageDisplay.setGrayValue(0);
timeStampBlockImageDisplayLegend = timeStampBlockImageDisplay.addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim);
panel.add(timeStampBlockImageDisplay);
timeStampBlockFrame.getContentPane().add(panel);
timeStampBlockFrame.pack();
timeStampBlockFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setShowSlices(false);
}
});
}
if (!timeStampBlockFrame.isVisible()) {
timeStampBlockFrame.setVisible(true);
}
timeStampBlockImageDisplay.clearImage();
for (int i = 0; i < innerCircleSize; i++) {
xInnerOffset[i] = innerCircle[i][0];
yInnerOffset[i] = innerCircle[i][1];
innerTsValue[i] = lastTimesMap[eX + xInnerOffset[i]][eY + yInnerOffset[i]][type];
innerTsValue[i] = slices[sliceIndex(1)][sliceScale][eX + xInnerOffset[i]][eY + yInnerOffset[i]];
if (innerTsValue[i] == 0x80000000) {
innerTsValue[i] = 0;
}
}
for (int i = 0; i < outerCircleSize; i++) {
xOuterOffset[i] = outerCircle[i][0];
yOuterOffset[i] = outerCircle[i][1];
outerTsValue[i] = lastTimesMap[eX + xOuterOffset[i]][eY + yOuterOffset[i]][type];
outerTsValue[i] = slices[sliceIndex(1)][sliceScale][eX + xOuterOffset[i]][eY + yOuterOffset[i]];
if (outerTsValue[i] == 0x80000000) {
outerTsValue[i] = 0;
}
}
List innerList = Arrays.asList(ArrayUtils.toObject(innerTsValue));
int innerMax = (int) Collections.max(innerList);
int innerMin = (int) Collections.min(innerList);
float innerScale = 1f / (innerMax - innerMin);
List outerList = Arrays.asList(ArrayUtils.toObject(outerTsValue));
int outerMax = (int) Collections.max(outerList);
int outerMin = (int) Collections.min(outerList);
float outerScale = 1f / (outerMax - outerMin);
float scale = 1f / getSliceMaxValue();
timeStampBlockImageDisplay.setPixmapRGB(dim / 2, dim / 2, 0, lastTimesMap[eX][eY][type] * scale, 0);
timeStampBlockImageDisplay.setPixmapRGB(dim / 2, dim / 2, 0, slices[sliceIndex(1)][sliceScale][eX][eY] * scale, 0);
for (int i = 0; i < innerCircleSize; i++) {
timeStampBlockImageDisplay.setPixmapRGB(xInnerOffset[i] + dim / 2, yInnerOffset[i] + dim / 2, innerScale * (innerTsValue[i] - innerMin), 0, 0);
timeStampBlockImageDisplay.setPixmapRGB(xInnerOffset[i] + dim / 2, yInnerOffset[i] + dim / 2, scale * (innerTsValue[i]), 0, 0);
}
for (int i = 0; i < outerCircleSize; i++) {
timeStampBlockImageDisplay.setPixmapRGB(xOuterOffset[i] + dim / 2, yOuterOffset[i] + dim / 2, 0, 0, outerScale * (outerTsValue[i] - outerMin));
timeStampBlockImageDisplay.setPixmapRGB(xOuterOffset[i] + dim / 2, yOuterOffset[i] + dim / 2, 0, 0, scale * (outerTsValue[i]));
}
if (timeStampBlockImageDisplayLegend != null) {
timeStampBlockImageDisplayLegend.setLegendString(TIME_STAMP_BLOCK_LEGEND_SLICES);
}
timeStampBlockImageDisplay.repaint();
}
private void drawSlices(byte[][][][] slices) {
// log.info("drawing slices");
if (sliceBitMapFrame == null) {
String windowName = "Slices";
sliceBitMapFrame = new JFrame(windowName);
sliceBitMapFrame.setLayout(new BoxLayout(sliceBitMapFrame.getContentPane(), BoxLayout.Y_AXIS));
sliceBitMapFrame.setPreferredSize(new Dimension(600, 600));
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
sliceBitmapImageDisplay = ImageDisplay.createOpenGLCanvas();
sliceBitmapImageDisplay.setBorderSpacePixels(10);
sliceBitmapImageDisplay.setImageSize(sizex >> showSlicesScale, sizey >> showSlicesScale);
sliceBitmapImageDisplay.setSize(200, 200);
sliceBitmapImageDisplay.setGrayValue(0);
sliceBitmapImageDisplayLegend = sliceBitmapImageDisplay.addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim);
panel.add(sliceBitmapImageDisplay);
sliceBitMapFrame.getContentPane().add(panel);
sliceBitMapFrame.pack();
sliceBitMapFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setShowSlices(false);
}
});
}
if (!sliceBitMapFrame.isVisible()) {
sliceBitMapFrame.setVisible(true);
}
int dimNewX = sizex >> showSlicesScale;
int dimNewY = sizey >> showSlicesScale;
if (dimNewX != sliceBitmapImageDisplay.getWidth() || dimNewY != sliceBitmapImageDisplay.getHeight()) {
sliceBitmapImageDisplay.setImageSize(dimNewX, dimNewY);
sliceBitmapImageDisplay.clearLegends();
sliceBitmapImageDisplayLegend = sliceBitmapImageDisplay.addLegend(LEGEND_G_SEARCH_AREA_R_REF_BLOCK_AREA_B_BEST_MATCH, 0, dim);
}
float scale = 1f / getSliceMaxValue();
sliceBitmapImageDisplay.clearImage();
int d1 = sliceIndex(1), d2 = sliceIndex(2);
if (showSlicesScale >= numScales) {
showSlicesScale = numScales - 1;
}
int imageSizeX = sizex >> showSlicesScale;
int imageSizeY = sizey >> showSlicesScale;
byte[] grayImageBuffer = new byte[imageSizeX * imageSizeY];
for (int slice = 1; slice <= 2; slice++) {
for (int x = 0; x < imageSizeX; x++) {
for (int y = 0; y < imageSizeY; y++) {
int pixelValue1 = slices[d1][showSlicesScale][x][y];
int pixelValue2 = slices[d2][showSlicesScale][x][y];
sliceBitmapImageDisplay.setPixmapRGB(x, y, scale * pixelValue1, scale * pixelValue2, 0);
// The minimum of byte is ox0(0), the maximum is 0xFF(-1);
// It is from 0 to 127 and then -128 to -1;
int imagePixelVal = (int) (pixelValue1 * 255.0f / getSliceMaxValue() + 128) + (int) (pixelValue2 * 255.0f / getSliceMaxValue());
if (imagePixelVal == 0) {
imagePixelVal = 0; // Background
}
grayImageBuffer[(imageSizeY - 1 - y) * imageSizeX + x] = (byte) imagePixelVal;
}
}
}
final BufferedImage theImage = new BufferedImage(imageSizeX, imageSizeY, BufferedImage.TYPE_BYTE_GRAY);
theImage.getRaster().setDataElements(0, 0, imageSizeX, imageSizeY, grayImageBuffer);
if (saveSliceGrayImage) {
final Date d = new Date();
final String PNG = "png";
// final String fn = "EventSlice-" + AEDataFile.DATE_FORMAT.format(d) + "." + PNG;
final String fn = "EventSlice-" + sliceEndTimeUs[d1] + "." + PNG;
// if user is playing a file, use folder that file lives in
String userDir = Paths.get(".").toAbsolutePath().normalize().toString();
File eventSliceDir = new File(userDir + File.separator + "EventSlices" + File.separator + getChip().getAeInputStream().getFile().getName());
if (!eventSliceDir.exists()) {
eventSliceDir.mkdirs();
}
File outputfile = new File(eventSliceDir + File.separator + fn);
try {
ImageIO.write(theImage, "png", outputfile);
} catch (IOException ex) {
Logger.getLogger(PatchMatchFlow.class.getName()).log(Level.SEVERE, null, ex);
}
saveSliceGrayImage = false;
}
if (sliceBitmapImageDisplayLegend != null) {
sliceBitmapImageDisplayLegend.setLegendString(LEGEND_SLICES);
}
sliceBitmapImageDisplay.repaint();
}
// /**
// * @return the numSlices
// */
// public int getNumSlices() {
// return numSlices;
// /**
// * @param numSlices the numSlices to set
// */
// synchronized public void setNumSlices(int numSlices) {
// if (numSlices < 3) {
// numSlices = 3;
// } else if (numSlices > 8) {
// numSlices = 8;
// this.numSlices = numSlices;
// putInt("numSlices", numSlices);
/**
* @return the sliceNumBits
*/
public int getSliceMaxValue() {
return sliceMaxValue;
}
/**
* @param sliceMaxValue the sliceMaxValue to set
*/
public void setSliceMaxValue(int sliceMaxValue) {
int old = this.sliceMaxValue;
if (sliceMaxValue < 1) {
sliceMaxValue = 1;
} else if (sliceMaxValue > 127) {
sliceMaxValue = 127;
}
this.sliceMaxValue = sliceMaxValue;
putInt("sliceMaxValue", sliceMaxValue);
getSupport().firePropertyChange("sliceMaxValue", old, this.sliceMaxValue);
}
/**
* @return the rectifyPolarties
*/
public boolean isRectifyPolarties() {
return rectifyPolarties;
}
/**
* @param rectifyPolarties the rectifyPolarties to set
*/
public void setRectifyPolarties(boolean rectifyPolarties) {
boolean old = this.rectifyPolarties;
this.rectifyPolarties = rectifyPolarties;
putBoolean("rectifyPolarties", rectifyPolarties);
getSupport().firePropertyChange("rectifyPolarties", old, this.rectifyPolarties);
}
/**
* @return the useSubsampling
*/
public boolean isUseSubsampling() {
return useSubsampling;
}
/**
* @param useSubsampling the useSubsampling to set
*/
public void setUseSubsampling(boolean useSubsampling) {
this.useSubsampling = useSubsampling;
}
/**
* @return the numScales
*/
public int getNumScales() {
return numScales;
}
/**
* @param numScales the numScales to set
*/
synchronized public void setNumScales(int numScales) {
int old = this.numScales;
if (numScales < 1) {
numScales = 1;
} else if (numScales > 4) {
numScales = 4;
}
this.numScales = numScales;
putInt("numScales", numScales);
setDefaultScalesToCompute();
scaleResultCounts = new int[numScales];
showBlockSizeAndSearchAreaTemporarily();
computeAveragePossibleMatchDistance();
getSupport().firePropertyChange("numScales", old, this.numScales);
}
/**
* Computes pooled (summed) value of slice at location xx, yy, in subsampled
* region around this point
*
* @param slice
* @param x
* @param y
* @param subsampleBy pool over 1<<subsampleBy by 1<<subsampleBy area to sum
* up the slice values @return
*/
private int pool(byte[][] slice, int x, int y, int subsampleBy) {
if (subsampleBy == 0) {
return slice[x][y];
} else {
int n = 1 << subsampleBy;
int sum = 0;
for (int xx = x; xx < x + n + n; xx++) {
for (int yy = y; yy < y + n + n; yy++) {
if (xx >= subSizeX || yy >= subSizeY) {
// log.warning("should not happen that xx="+xx+" or yy="+yy);
continue; // TODO remove this check when iteration avoids this sum explictly
}
sum += slice[xx][yy];
}
}
return sum;
}
}
/**
* @return the scalesToCompute
*/
public String getScalesToCompute() {
return scalesToCompute;
}
/**
* @param scalesToCompute the scalesToCompute to set
*/
synchronized public void setScalesToCompute(String scalesToCompute) {
this.scalesToCompute = scalesToCompute;
if (scalesToCompute == null || scalesToCompute.isEmpty()) {
setDefaultScalesToCompute();
} else {
StringTokenizer st = new StringTokenizer(scalesToCompute, ", ", false);
int n = st.countTokens();
if (n == 0) {
setDefaultScalesToCompute();
} else {
scalesToComputeArray = new Integer[n];
int i = 0;
while (st.hasMoreTokens()) {
try {
int scale = Integer.parseInt(st.nextToken());
scalesToComputeArray[i++] = scale;
} catch (NumberFormatException e) {
log.warning("bad string in scalesToCompute field, use blank or 0,2 for example");
setDefaultScalesToCompute();
}
}
}
}
}
private void setDefaultScalesToCompute() {
scalesToComputeArray = new Integer[numScales];
for (int i = 0; i < numScales; i++) {
scalesToComputeArray[i] = i;
}
}
/**
* @return the areaEventNumberSubsampling
*/
public int getAreaEventNumberSubsampling() {
return areaEventNumberSubsampling;
}
/**
* @param areaEventNumberSubsampling the areaEventNumberSubsampling to set
*/
synchronized public void setAreaEventNumberSubsampling(int areaEventNumberSubsampling) {
int old = this.areaEventNumberSubsampling;
if (areaEventNumberSubsampling < 3) {
areaEventNumberSubsampling = 3;
} else if (areaEventNumberSubsampling > 7) {
areaEventNumberSubsampling = 7;
}
this.areaEventNumberSubsampling = areaEventNumberSubsampling;
putInt("areaEventNumberSubsampling", areaEventNumberSubsampling);
showAreasForAreaCountsTemporarily();
clearAreaCounts();
if (sliceMethod != SliceMethod.AreaEventNumber) {
log.warning("AreaEventNumber method is not currently selected as sliceMethod");
}
getSupport().firePropertyChange("areaEventNumberSubsampling", old, this.areaEventNumberSubsampling);
}
private void showAreasForAreaCountsTemporarily() {
if (stopShowingStuffTask != null) {
stopShowingStuffTask.cancel();
}
stopShowingStuffTask = new TimerTask() {
@Override
public void run() {
showBlockSizeAndSearchAreaTemporarily = false; // in case we are canceling a task that would clear this
showAreaCountAreasTemporarily = false;
}
};
Timer showAreaCountsAreasTimer = new Timer();
showAreaCountAreasTemporarily = true;
showAreaCountsAreasTimer.schedule(stopShowingStuffTask, SHOW_STUFF_DURATION_MS);
}
private void showBlockSizeAndSearchAreaTemporarily() {
if (stopShowingStuffTask != null) {
stopShowingStuffTask.cancel();
}
stopShowingStuffTask = new TimerTask() {
@Override
public void run() {
showAreaCountAreasTemporarily = false; // in case we are canceling a task that would clear this
showBlockSizeAndSearchAreaTemporarily = false;
}
};
Timer showBlockSizeAndSearchAreaTimer = new Timer();
showBlockSizeAndSearchAreaTemporarily = true;
showBlockSizeAndSearchAreaTimer.schedule(stopShowingStuffTask, SHOW_STUFF_DURATION_MS);
}
private void clearAreaCounts() {
if (sliceMethod != SliceMethod.AreaEventNumber) {
return;
}
if (areaCounts == null || areaCounts.length != 1 + (subSizeX >> areaEventNumberSubsampling)) {
int nax = 1 + (subSizeX >> areaEventNumberSubsampling), nay = 1 + (subSizeY >> areaEventNumberSubsampling);
numAreas = nax * nay;
areaCounts = new int[nax][nay];
} else {
for (int[] i : areaCounts) {
Arrays.fill(i, 0);
}
}
areaCountExceeded = false;
}
private void clearNonGreedyRegions() {
if (!nonGreedyFlowComputingEnabled) {
return;
}
checkNonGreedyRegionsAllocated();
nonGreedyRegionsCount = 0;
for (boolean[] i : nonGreedyRegions) {
Arrays.fill(i, false);
}
}
private void checkNonGreedyRegionsAllocated() {
if (nonGreedyRegions == null || nonGreedyRegions.length != 1 + (subSizeX >> areaEventNumberSubsampling)) {
nonGreedyRegionsNumberOfRegions = (1 + (subSizeX >> areaEventNumberSubsampling)) * (1 + (subSizeY >> areaEventNumberSubsampling));
nonGreedyRegions = new boolean[1 + (subSizeX >> areaEventNumberSubsampling)][1 + (subSizeY >> areaEventNumberSubsampling)];
nonGreedyRegionsNumberOfRegions = (1 + (subSizeX >> areaEventNumberSubsampling)) * (1 + (subSizeY >> areaEventNumberSubsampling));
}
}
public int getSliceDeltaT() {
return sliceDeltaT;
}
/**
* @return the enableImuTimesliceLogging
*/
public boolean isEnableImuTimesliceLogging() {
return enableImuTimesliceLogging;
}
/**
* @param enableImuTimesliceLogging the enableImuTimesliceLogging to set
*/
public void setEnableImuTimesliceLogging(boolean enableImuTimesliceLogging) {
this.enableImuTimesliceLogging = enableImuTimesliceLogging;
if (enableImuTimesliceLogging) {
if (imuTimesliceLogger == null) {
imuTimesliceLogger = new TobiLogger("imuTimeslice.txt", "IMU rate gyro deg/s and patchmatch timeslice duration in ms");
imuTimesliceLogger.setColumnHeaderLine("systemtime(ms) timestamp(us) timeslice(us) rate(deg/s)");
imuTimesliceLogger.setSeparator(" ");
}
}
imuTimesliceLogger.setEnabled(enableImuTimesliceLogging);
}
/**
* @return the nonGreedyFlowComputingEnabled
*/
public boolean isNonGreedyFlowComputingEnabled() {
return nonGreedyFlowComputingEnabled;
}
/**
* @param nonGreedyFlowComputingEnabled the nonGreedyFlowComputingEnabled to
* set
*/
synchronized public void setNonGreedyFlowComputingEnabled(boolean nonGreedyFlowComputingEnabled) {
boolean old = this.nonGreedyFlowComputingEnabled;
this.nonGreedyFlowComputingEnabled = nonGreedyFlowComputingEnabled;
putBoolean("nonGreedyFlowComputingEnabled", nonGreedyFlowComputingEnabled);
if (nonGreedyFlowComputingEnabled) {
clearNonGreedyRegions();
}
getSupport().firePropertyChange("nonGreedyFlowComputingEnabled", old, nonGreedyFlowComputingEnabled);
}
/**
* @return the nonGreedyFractionToBeServiced
*/
public float getNonGreedyFractionToBeServiced() {
return nonGreedyFractionToBeServiced;
}
/**
* @param nonGreedyFractionToBeServiced the nonGreedyFractionToBeServiced to
* set
*/
public void setNonGreedyFractionToBeServiced(float nonGreedyFractionToBeServiced) {
this.nonGreedyFractionToBeServiced = nonGreedyFractionToBeServiced;
putFloat("nonGreedyFractionToBeServiced", nonGreedyFractionToBeServiced);
}
/**
* @return the adapativeSliceDurationProportionalErrorGain
*/
public float getAdapativeSliceDurationProportionalErrorGain() {
return adapativeSliceDurationProportionalErrorGain;
}
/**
* @param adapativeSliceDurationProportionalErrorGain the
* adapativeSliceDurationProportionalErrorGain to set
*/
public void setAdapativeSliceDurationProportionalErrorGain(float adapativeSliceDurationProportionalErrorGain) {
this.adapativeSliceDurationProportionalErrorGain = adapativeSliceDurationProportionalErrorGain;
putFloat("adapativeSliceDurationProportionalErrorGain", adapativeSliceDurationProportionalErrorGain);
}
/**
* @return the adapativeSliceDurationUseProportionalControl
*/
public boolean isAdapativeSliceDurationUseProportionalControl() {
return adapativeSliceDurationUseProportionalControl;
}
/**
* @param adapativeSliceDurationUseProportionalControl the
* adapativeSliceDurationUseProportionalControl to set
*/
public void setAdapativeSliceDurationUseProportionalControl(boolean adapativeSliceDurationUseProportionalControl) {
this.adapativeSliceDurationUseProportionalControl = adapativeSliceDurationUseProportionalControl;
putBoolean("adapativeSliceDurationUseProportionalControl", adapativeSliceDurationUseProportionalControl);
}
public boolean isPrintScaleCntStatEnabled() {
return printScaleCntStatEnabled;
}
public void setPrintScaleCntStatEnabled(boolean printScaleCntStatEnabled) {
this.printScaleCntStatEnabled = printScaleCntStatEnabled;
putBoolean("printScaleCntStatEnabled", printScaleCntStatEnabled);
}
/**
* @return the showSlicesScale
*/
public int getShowSlicesScale() {
return showSlicesScale;
}
/**
* @param showSlicesScale the showSlicesScale to set
*/
public void setShowSlicesScale(int showSlicesScale) {
if (showSlicesScale < 0) {
showSlicesScale = 0;
} else if (showSlicesScale > numScales - 1) {
showSlicesScale = numScales - 1;
}
this.showSlicesScale = showSlicesScale;
}
public int getSliceDurationMinLimitUS() {
return sliceDurationMinLimitUS;
}
public void setSliceDurationMinLimitUS(int sliceDurationMinLimitUS) {
this.sliceDurationMinLimitUS = sliceDurationMinLimitUS;
putInt("sliceDurationMinLimitUS", sliceDurationMinLimitUS);
}
public int getSliceDurationMaxLimitUS() {
return sliceDurationMaxLimitUS;
}
public void setSliceDurationMaxLimitUS(int sliceDurationMaxLimitUS) {
this.sliceDurationMaxLimitUS = sliceDurationMaxLimitUS;
putInt("sliceDurationMaxLimitUS", sliceDurationMaxLimitUS);
}
public boolean isShowCorners() {
return showCorners;
}
public void setShowCorners(boolean showCorners) {
this.showCorners = showCorners;
putBoolean("showCorners", showCorners);
}
public boolean isHWABMOFEnabled() {
return HWABMOFEnabled;
}
public void setHWABMOFEnabled(boolean HWABMOFEnabled) {
this.HWABMOFEnabled = HWABMOFEnabled;
}
public boolean isCalcOFonCornersEnabled() {
return calcOFonCornersEnabled;
}
public void setCalcOFonCornersEnabled(boolean calcOFonCornersEnabled) {
this.calcOFonCornersEnabled = calcOFonCornersEnabled;
putBoolean("calcOFonCornersEnabled", calcOFonCornersEnabled);
}
public float getCornerThr() {
return cornerThr;
}
public void setCornerThr(float cornerThr) {
this.cornerThr = cornerThr;
if (this.cornerThr > 1) {
this.cornerThr = 1;
}
putFloat("cornerThr", cornerThr);
}
public CornerCircleSelection getCornerCircleSelection() {
return cornerCircleSelection;
}
public void setCornerCircleSelection(CornerCircleSelection cornerCircleSelection) {
this.cornerCircleSelection = cornerCircleSelection;
putString("cornerCircleSelection", cornerCircleSelection.toString());
}
synchronized public void doStartRecordingForEDFLOW() {
JFileChooser c = new JFileChooser(lastFileName);
c.setFileFilter(new FileFilter() {
public boolean accept(File f) {
return f.isDirectory() || f.getName().toLowerCase().endsWith(".txt");
}
public String getDescription() {
return "text file";
}
});
c.setSelectedFile(new File(lastFileName));
int ret = c.showSaveDialog(null);
if (ret != JFileChooser.APPROVE_OPTION) {
return;
}
String basename = c.getSelectedFile().toString();
if (basename.toLowerCase().endsWith(".txt")) {
basename = basename.substring(0, basename.length() - 4);
}
lastFileName = basename;
putString("lastFileName", lastFileName);
String fn = basename + "-OFResult.txt";
try {
dvsWriter = new PrintWriter(new File(fn));
} catch (FileNotFoundException ex) {
Logger.getLogger(PatchMatchFlow.class.getName()).log(Level.SEVERE, null, ex);
}
dvsWriter.println("# created " + new Date().toString());
dvsWriter.println("# source-file: " + (chip.getAeInputStream() != null ? chip.getAeInputStream().getFile().toString() : "(live input)"));
dvsWriter.println("# dvs-events: One event per line: timestamp(us) x y polarity(0=off,1=on) dx dy OFRetValid rotateFlg SFAST");
}
synchronized public void doStopRecordingForEDFLOW() {
dvsWriter.close();
dvsWriter = null;
}
// This is the BFAST (or SFAST in paper) corner dector. EFAST refer to HWCornerPointRender
boolean PatchFastDetectorisFeature(PolarityEvent ein) {
boolean found_streak = false;
boolean found_streak_inner = false, found_streak_outer = false;
int innerI = 0, outerI = 0, innerStreakSize = 0, outerStreakSize = 0;
int scale = numScales - 1;
int pix_x = ein.x >> scale;
int pix_y = ein.y >> scale;
byte featureSlice[][] = slices[sliceIndex(1)][scale];
int circle3_[][] = innerCircle;
int circle4_[][] = outerCircle;
final int innerSize = circle3_.length;
final int outerSize = circle4_.length;
int innerStartX = 0, innerEndX = 0, innerStartY = 0, innerEndY = 0;
int outerStartX, outerEndX, outerStartY, outerEndY;
// only check if not too close to border
if (pix_x < 4 || pix_x >= (getChip().getSizeX() >> scale) - 4
|| pix_y < 4 || pix_y >= (getChip().getSizeY() >> scale) - 4) {
found_streak = false;
return found_streak;
}
found_streak_inner = false;
boolean exit_inner_loop = false;
int centerValue = 0;
int xInnerOffset[] = new int[innerCircleSize];
int yInnerOffset[] = new int[innerCircleSize];
// int innerTsValue[] = new int[innerCircleSize];
for (int i = 0; i < innerCircleSize; i++) {
xInnerOffset[i] = innerCircle[i][0];
yInnerOffset[i] = innerCircle[i][1];
innerTsValue[i] = featureSlice[pix_x + xInnerOffset[i]][pix_y + yInnerOffset[i]];
}
int xOuterOffset[] = new int[outerCircleSize];
int yOuterOffset[] = new int[outerCircleSize];
// int outerTsValue[] = new int[outerCircleSize];
for (int i = 0; i < outerCircleSize; i++) {
xOuterOffset[i] = outerCircle[i][0];
yOuterOffset[i] = outerCircle[i][1];
outerTsValue[i] = featureSlice[pix_x + xOuterOffset[i]][pix_y + yOuterOffset[i]];
}
isFeatureOutterLoop:
for (int i = 0; i < innerSize; i++) {
FastDetectorisFeature_label2:
for (int streak_size = innerCircleSize - 1; streak_size >= 2; streak_size = streak_size - 1) {
// check that streak event is larger than neighbor
if (Math.abs(featureSlice[pix_x + circle3_[i][0]][pix_y + circle3_[i][1]] - centerValue) < Math.abs(featureSlice[pix_x + circle3_[(i - 1 + innerSize) % innerSize][0]][pix_y + circle3_[(i - 1 + innerSize) % innerSize][1]] - centerValue)) {
continue;
}
// check that streak event is larger than neighbor
if (Math.abs(featureSlice[pix_x + circle3_[(i + streak_size - 1) % innerSize][0]][pix_y + circle3_[(i + streak_size - 1) % innerSize][1]] - centerValue) < Math.abs(featureSlice[pix_x + circle3_[(i + streak_size) % innerSize][0]][pix_y + circle3_[(i + streak_size) % innerSize][1]] - centerValue)) {
continue;
}
// find the smallest timestamp in corner min_t
double min_t = Math.abs(featureSlice[pix_x + circle3_[i][0]][pix_y + circle3_[i][1]] - centerValue);
FastDetectorisFeature_label1:
for (int j = 1; j < streak_size; j++) {
final double tj = Math.abs(featureSlice[pix_x + circle3_[(i + j) % innerSize][0]][pix_y + circle3_[(i + j) % innerSize][1]] - centerValue);
if (tj < min_t) {
min_t = tj;
}
}
//check if corner timestamp is higher than corner
boolean did_break = false;
double max_t = featureSlice[pix_x + circle3_[(i + streak_size) % innerSize][0]][pix_y + circle3_[(i + streak_size) % innerSize][1]];
FastDetectorisFeature_label0:
for (int j = streak_size; j < innerSize; j++) {
final double tj = Math.abs(featureSlice[pix_x + circle3_[(i + j) % innerSize][0]][pix_y + circle3_[(i + j) % innerSize][1]] - centerValue);
if (tj > max_t) {
max_t = tj;
}
if (tj >= min_t - cornerThr * getSliceMaxValue()) {
did_break = true;
break;
}
}
// The maximum value of the non-streak is on the border, remove it.
if (!did_break) {
if ((max_t >= 7) && (max_t == featureSlice[pix_x + circle3_[(i + streak_size) % innerSize][0]][pix_y + circle3_[(i + streak_size) % innerSize][1]]
|| max_t == featureSlice[pix_x + circle3_[(i + innerSize - 1) % innerSize][0]][pix_y + circle3_[(i + innerSize - 1) % innerSize][1]])) {
// did_break = true;
}
}
if (!did_break) {
innerI = i;
innerStreakSize = streak_size;
innerStartX = innerCircle[innerI % innerSize][0];
innerEndX = innerCircle[(innerI + innerStreakSize - 1) % innerSize][0];
innerStartY = innerCircle[innerI % innerSize][1];
innerEndY = innerCircle[(innerI + innerStreakSize - 1) % innerSize][1];
int condDiff = (streak_size % 2 == 1) ? 0 : 1; // If streak_size is even, then set it to 1. Otherwise 0.
if ((streak_size == innerCircleSize - 1) || Math.abs(innerStartX - innerEndX) <= condDiff || Math.abs(innerStartY - innerEndY) <= condDiff // || featureSlice[pix_x + innerStartX][pix_y + innerEndX] < 12
// || featureSlice[pix_x + innerEndX][pix_y + innerEndY] < 12
) {
found_streak_inner = false;
} else {
found_streak_inner = true;
}
exit_inner_loop = true;
break;
}
}
if (found_streak_inner || exit_inner_loop) {
break;
}
}
found_streak_outer = false;
// if (found_streak)
{
found_streak_outer = false;
boolean exit_outer_loop = false;
FastDetectorisFeature_label6:
for (int streak_size = outerCircleSize - 1; streak_size >= 3; streak_size
FastDetectorisFeature_label5:
for (int i = 0; i < outerSize; i++) {
// check that first event is larger than neighbor
if (Math.abs(featureSlice[pix_x + circle4_[i][0]][pix_y + circle4_[i][1]] - centerValue) < Math.abs(featureSlice[pix_x + circle4_[(i - 1 + outerSize) % outerSize][0]][pix_y + circle4_[(i - 1 + outerSize) % outerSize][1]] - centerValue)) {
continue;
}
// check that streak event is larger than neighbor
if (Math.abs(featureSlice[pix_x + circle4_[(i + streak_size - 1) % outerSize][0]][pix_y + circle4_[(i + streak_size - 1) % outerSize][1]] - centerValue) < Math.abs(featureSlice[pix_x + circle4_[(i + streak_size) % outerSize][0]][pix_y + circle4_[(i + streak_size) % outerSize][1]] - centerValue)) {
continue;
}
double min_t = Math.abs(featureSlice[pix_x + circle4_[i][0]][pix_y + circle4_[i][1]] - centerValue);
FastDetectorisFeature_label4:
for (int j = 1; j < streak_size; j++) {
final double tj = Math.abs(featureSlice[pix_x + circle4_[(i + j) % outerSize][0]][pix_y + circle4_[(i + j) % outerSize][1]] - centerValue);
if (tj < min_t) {
min_t = tj;
}
}
boolean did_break = false;
double max_t = featureSlice[pix_x + circle4_[(i + streak_size) % outerSize][0]][pix_y + circle4_[(i + streak_size) % outerSize][1]];
float thr = cornerThr * getSliceMaxValue();
if (streak_size >= 9) {
thr += 1;
}
FastDetectorisFeature_label3:
for (int j = streak_size; j < outerSize; j++) {
final double tj = Math.abs(featureSlice[pix_x + circle4_[(i + j) % outerSize][0]][pix_y + circle4_[(i + j) % outerSize][1]] - centerValue);
if (tj > max_t) {
max_t = tj;
}
if (tj >= min_t - thr) {
did_break = true;
break;
}
}
if (!did_break) {
if (streak_size == 9 && (max_t >= 7)) {
int tmp = 0;
}
}
if (!did_break) {
outerI = i;
outerStreakSize = streak_size;
outerStartX = outerCircle[outerI % outerSize][0];
outerEndX = outerCircle[(outerI + outerStreakSize - 1) % outerSize][0];
outerStartY = outerCircle[outerI % outerSize][1];
outerEndY = outerCircle[(outerI + outerStreakSize - 1) % outerSize][1];
int condDiff = (streak_size % 2 == 1) ? 0 : 1; // If streak_size is even, then set it to 1. Otherwise 0.
if ((streak_size == outerCircleSize - 1) || Math.abs(outerStartX - outerEndX) <= condDiff || Math.abs(outerStartY - outerEndY) <= condDiff // || featureSlice[pix_x + outerStartX][pix_y + outerStartY] < 12
// || featureSlice[pix_x + outerEndX][pix_y + outerEndX] < 12
) {
found_streak_outer = false;
} else {
found_streak_outer = true;
}
if (min_t - max_t != 15 || streak_size != 10) {
// found_streak_outer = false;
}
exit_outer_loop = true;
break;
}
}
if (found_streak_outer || exit_outer_loop) {
break;
}
}
}
switch (cornerCircleSelection) {
case InnerCircle:
found_streak = found_streak_inner;
break;
case OuterCircle:
found_streak = found_streak_outer;
break;
case OR:
found_streak = found_streak_inner || found_streak_outer;
break;
case AND:
found_streak = found_streak_inner && found_streak_outer;
break;
default:
found_streak = found_streak_inner && found_streak_outer;
break;
}
return found_streak;
}
/**
* @return the outlierRejectionEnabled
*/
public boolean isOutlierRejectionEnabled() {
return outlierRejectionEnabled;
}
/**
* @param outlierRejectionEnabled the outlierRejectionEnabled to set
*/
public void setOutlierRejectionEnabled(boolean outlierRejectionEnabled) {
this.outlierRejectionEnabled = outlierRejectionEnabled;
putBoolean("outlierRejectionEnabled", outlierRejectionEnabled);
}
/**
* @return the outlierRejectionThresholdSigma
*/
public float getOutlierRejectionThresholdSigma() {
return outlierRejectionThresholdSigma;
}
/**
* @param outlierRejectionThresholdSigma the outlierRejectionThresholdSigma
* to set
*/
public void setOutlierRejectionThresholdSigma(float outlierRejectionThresholdSigma) {
this.outlierRejectionThresholdSigma = outlierRejectionThresholdSigma;
putFloat("outlierRejectionThresholdSigma", outlierRejectionThresholdSigma);
}
private boolean isOutlierFlowVector(PatchMatchFlow.SADResult result) {
if (!outlierRejectionEnabled) {
return false;
}
GlobalMotion gm = outlierRejectionMotionFlowStatistics.getGlobalMotion();
// update global flow here before outlier rejection, otherwise stats are not updated and std shrinks to zero
gm.update(vx, vy, v, (x << getSubSampleShift()), (y << getSubSampleShift()));
float speed = (float) Math.sqrt(result.vx * result.vx + result.vy * result.vy);
// if the current vector speed is too many stds outside the mean speed then it is an outlier
if (Math.abs(speed - gm.meanGlobalSpeed)
> outlierRejectionThresholdSigma * gm.sdGlobalSpeed) {
return true;
}
// if((Math.abs(result.vx-gm.meanGlobalVx)>outlierRejectionThresholdSigma*gm.sdGlobalVx)
// || (Math.abs(result.vy-gm.meanGlobalVy)>outlierRejectionThresholdSigma*gm.sdGlobalVy))
// return true;
return false;
}
/**
* @return the useEFASTnotSFAST
*/
public boolean isUseEFASTnotSFAST() {
return useEFASTnotSFAST;
}
/**
* @param useEFASTnotSFAST the useEFASTnotSFAST to set
*/
public void setUseEFASTnotSFAST(boolean useEFASTnotSFAST) {
this.useEFASTnotSFAST = useEFASTnotSFAST;
putBoolean("useEFASTnotSFAST", useEFASTnotSFAST);
checkForEASTCornerDetectorEnclosedFilter();
}
private void checkForEASTCornerDetectorEnclosedFilter() {
if (useEFASTnotSFAST) {
// add enclosed filter if not there
if (keypointFilter == null) {
keypointFilter = new HWCornerPointRenderer(chip);
}
if (!getEnclosedFilterChain().contains(keypointFilter)) {
getEnclosedFilterChain().add(keypointFilter); // use for EFAST
}
keypointFilter.setFilterEnabled(isFilterEnabled());
getChip().getAeViewer().getFilterFrame().rebuildContents();
} else {
if (keypointFilter != null && getEnclosedFilterChain().contains(keypointFilter)) {
getEnclosedFilterChain().remove(keypointFilter);
getChip().getAeViewer().getFilterFrame().rebuildContents();
}
}
}
/**
* @return the outlierRejectionWindowSize
*/
public int getOutlierRejectionWindowSize() {
return outlierRejectionWindowSize;
}
/**
* @param outlierRejectionWindowSize the outlierRejectionWindowSize to set
*/
public void setOutlierRejectionWindowSize(int outlierRejectionWindowSize) {
this.outlierRejectionWindowSize = outlierRejectionWindowSize;
putInt("outlierRejectionWindowSize",outlierRejectionWindowSize);
outlierRejectionMotionFlowStatistics.setWindowSize(outlierRejectionWindowSize);
}
} |
package org.xwiki.rendering.display.html.internal;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.script.ScriptContext;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.util.ReflectionUtils;
import org.xwiki.displayer.HTMLDisplayer;
import org.xwiki.displayer.HTMLDisplayerException;
import org.xwiki.script.ScriptContextManager;
import org.xwiki.template.Template;
import org.xwiki.template.TemplateManager;
/**
* Default implementation of {@code HTMLDisplayer} using templates.
*
* @version $Id$
* @since 10.11RC1
*/
@Component
@Singleton
public class DefaultTemplateHTMLDisplayer implements HTMLDisplayer<Object>
{
/**
* Folder containing the HTML Displayers velocity templates.
*/
public static final String TEMPLATE_FOLDER = "html_displayer";
/**
* Name of the velocity variable containing the value, the mode and parameters of the displayer.
*/
public static final String DISPLAYER_VELOCITY_NAME = "displayer";
/**
* Template extension (velocity).
*/
public static final String TEMPLATE_EXTENSION = ".vm";
@Inject
protected TemplateManager templateManager;
@Inject
protected ScriptContextManager scriptContextManager;
/**
* {@inheritDoc}
* <p>
* Displays the value with the 'view' mode.
*/
@Override
public String display(Type type, Object value) throws HTMLDisplayerException
{
return display(type, value, Collections.emptyMap());
}
/**
* {@inheritDoc}
* <p>
* Displays the value with the 'view' mode.
*/
@Override
public String display(Type type, Object value, Map<String, String> parameters) throws HTMLDisplayerException
{
return display(type, value, parameters, "view");
}
@Override
public String display(Type type, Object value, Map<String, String> parameters, String mode)
throws HTMLDisplayerException
{
ScriptContext scriptContext = scriptContextManager.getCurrentScriptContext();
try {
Map<String, Object> displayer = new HashMap<>();
displayer.put("type", type);
displayer.put("value", value);
displayer.put("parameters", parameters);
displayer.put("mode", mode);
scriptContext.setAttribute(DISPLAYER_VELOCITY_NAME, displayer, ScriptContext.ENGINE_SCOPE);
Writer writer = new StringWriter();
templateManager.render(getTemplate(type, value, mode), writer);
return writer.toString();
} catch (Exception e) {
throw new HTMLDisplayerException("Couldn't render the template", e);
} finally {
scriptContext.removeAttribute(DISPLAYER_VELOCITY_NAME, ScriptContext.ENGINE_SCOPE);
}
}
/**
* Computes the template name.
* <p>
* The following names will be use in this priority order to find an existing template:
* <ul>
* <li>html_displayer/[type]/[mode].vm
* <li>html_displayer/[type].vm
* <li>html_displayer/[mode].vm
* <li>html_displayer/default.vm
* </ul>
* Please note that the following special characters: >, <, ? and spaces will be replaced by "." in the path.
*
* @return the template name used to make the rendering
*/
private Template getTemplate(Type type, Object value, String mode)
{
if (type != null || value == null) {
return getTemplate(type, mode);
} else {
return getTemplate(value.getClass(), mode);
}
}
private Template getTemplate(Type type, String mode)
{
Template template = null;
for (String path : getTemplatePaths(type, mode)) {
template = templateManager.getTemplate(TEMPLATE_FOLDER + '/' + path + TEMPLATE_EXTENSION);
if (template != null) {
break;
}
}
return template;
}
private String cleanPath(String path)
{
return path.replaceAll("<", "(").replaceAll(">", ")").replaceAll("\\?", "_").replaceAll(" ", "");
}
private List<String> getTemplatePaths(Type type, String mode)
{
List<String> paths = new ArrayList<>();
for (String typeName : getTypeNames(type)) {
if (mode != null) {
paths.add(cleanPath(typeName + '/' + mode));
}
paths.add(cleanPath(typeName));
}
if (mode != null) {
paths.add(cleanPath(mode));
}
paths.add("default");
return paths;
}
private List<String> getTypeNames(Type type)
{
List<String> typeNames = new ArrayList<>();
if (type instanceof Class) {
Class<?> aClass = (Class<?>) type;
typeNames.add(aClass.getSimpleName().toLowerCase());
if (aClass.isEnum()) {
typeNames.add("enum");
}
} else if (type != null) {
typeNames.add(ReflectionUtils.serializeType(type).toLowerCase());
}
return typeNames;
}
} |
package ome.scifio.formats;
import java.io.IOException;
import net.imglib2.meta.Axes;
import net.imglib2.meta.AxisType;
import ome.scifio.AbstractFormat;
import ome.scifio.AbstractMetadata;
import ome.scifio.AbstractParser;
import ome.scifio.AbstractWriter;
import ome.scifio.ByteArrayPlane;
import ome.scifio.ByteArrayReader;
import ome.scifio.DefaultImageMetadata;
import ome.scifio.DefaultTranslator;
import ome.scifio.FormatException;
import ome.scifio.ImageMetadata;
import ome.scifio.Plane;
import ome.scifio.Translator;
import ome.scifio.formats.tiff.IFD;
import ome.scifio.formats.tiff.IFDList;
import ome.scifio.formats.tiff.TiffParser;
import ome.scifio.io.RandomAccessInputStream;
import ome.scifio.util.FormatTools;
import org.scijava.Priority;
import org.scijava.plugin.Attr;
import org.scijava.plugin.Plugin;
@Plugin(type = EPSFormat.class)
public class EPSFormat extends AbstractFormat {
// -- Format API Methods --
public String getFormatName() {
return "Encapsulated PostScript";
}
public String[] getSuffixes() {
return new String[] {"eps", "epsi", "ps"};
}
// -- Nested classes --
/**
* @author Mark Hiner hinerm at gmail.com
*
*/
public static class Metadata extends AbstractMetadata {
// -- Constants --
public static final String CNAME = "ome.scifio.formats.EPSFormat$Metadata";
// -- Fields --
/** Starting line of pixel data. */
private int start;
/** Flag indicating binary data. */
private boolean binary;
private boolean isTiff;
private IFDList ifds;
// -- Constructor --
public Metadata() {
super();
add(new DefaultImageMetadata());
setLittleEndian(0, true);
}
// -- Field accessors and setters
public IFDList getIfds() {
return ifds;
}
public void setIfds(IFDList ifds) {
this.ifds = ifds;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public boolean isBinary() {
return binary;
}
public void setBinary(boolean binary) {
this.binary = binary;
}
public boolean isTiff() {
return isTiff;
}
public void setTiff(boolean isTiff) {
this.isTiff = isTiff;
}
// -- Metadata API Methods --
public void populateImageMetadata() {
if (getAxisLength(0, Axes.CHANNEL) == 0) setAxisLength(0, Axes.CHANNEL, 1);
setAxisLength(0, Axes.Z, 1);
setAxisLength(0, Axes.TIME, 1);
if (getPixelType(0) == 0) setPixelType(0, FormatTools.UINT8);
setBitsPerPixel(0, FormatTools.getBitsPerPixel(getPixelType(0)));
setRGB(0, getAxisLength(0, Axes.CHANNEL) == 3);
setInterleaved(0, true);
get(0).setPlaneCount(1);
}
// -- HasSource API Methods --
/*
* @see ome.scifio.AbstractMetadata#close(boolean)
*/
public void close(boolean fileOnly) throws IOException {
super.close(fileOnly);
if (!fileOnly) {
isTiff = false;
ifds = null;
start = 0;
binary = false;
}
}
}
/**
* @author Mark Hiner hinerm at gmail.com
*
*/
public static class Parser extends AbstractParser<Metadata> {
@Override
protected void typedParse(RandomAccessInputStream stream, Metadata meta)
throws IOException, FormatException
{
meta.createImageMetadata(1);
ImageMetadata m = meta.get(0);
LOGGER.info("Verifying EPS format");
String line = in.readLine();
if (!line.trim().startsWith("%!PS")) {
// read the TIFF preview
meta.setTiff(true);
in.order(true);
in.seek(20);
int offset = in.readInt();
int len = in.readInt();
byte[] b = new byte[len];
in.seek(offset);
in.read(b);
in = new RandomAccessInputStream(getContext(), b);
TiffParser tp = new TiffParser(getContext(), in);
meta.setIfds(tp.getIFDs());
IFD firstIFD = meta.getIfds().get(0);
m.setAxisLength(Axes.X, (int)firstIFD.getImageWidth());
m.setAxisLength(Axes.Y, (int)firstIFD.getImageLength());
m.setAxisLength(Axes.CHANNEL, firstIFD.getSamplesPerPixel());
m.setAxisLength(Axes.Z, 1);
m.setAxisLength(Axes.TIME, 1);
if (m.getAxisLength(Axes.CHANNEL) == 2)
m.setAxisLength(Axes.CHANNEL, 4);
m.setLittleEndian(firstIFD.isLittleEndian());
m.setInterleaved(true);
m.setRGB(m.getAxisLength(Axes.CHANNEL) > 1);
m.setPixelType(firstIFD.getPixelType());
m.setPlaneCount(1);
m.setMetadataComplete(true);
m.setIndexed(false);
m.setFalseColor(false);
return;
}
LOGGER.info("Finding image data");
meta.setBinary(false);
String image = "image";
int lineNum = 1;
line = in.readLine().trim();
m.setAxisTypes(new AxisType[]{Axes.X, Axes.Y, Axes.CHANNEL});
while (line != null && !line.equals("%%EOF")) {
if (line.endsWith(image)) {
if (!line.startsWith(image)) {
if (line.indexOf("colorimage") != -1) m.setAxisLength(Axes.CHANNEL, 3);
String[] t = line.split(" ");
try {
m.setAxisLength(Axes.X, Integer.parseInt(t[0]));
m.setAxisLength(Axes.Y, Integer.parseInt(t[1]));
}
catch (NumberFormatException exc) {
LOGGER.debug("Could not parse image dimensions", exc);
m.setAxisLength(Axes.CHANNEL, Integer.parseInt(t[3]));
}
}
meta.setStart(lineNum);
break;
}
else if (line.startsWith("%%")) {
if (line.startsWith("%%BoundingBox:")) {
line = line.substring(14).trim();
String[] t = line.split(" ");
try {
int originX = Integer.parseInt(t[0].trim());
int originY = Integer.parseInt(t[1].trim());
m.setAxisLength(Axes.X, Integer.parseInt(t[2].trim()) - originY);
m.setAxisLength(Axes.Y, Integer.parseInt(t[3].trim()) - originY);
addGlobalMeta("X-coordinate of origin", originX);
addGlobalMeta("Y-coordinate of origin", originY);
}
catch (NumberFormatException e) {
throw new FormatException(
"Files without image data are not supported.");
}
}
else if (line.startsWith("%%BeginBinary")) {
meta.setBinary(true);
}
else {
// parse key/value pairs
int ndx = line.indexOf(":");
if (ndx != -1) {
String key = line.substring(0, ndx);
String value = line.substring(ndx + 1);
addGlobalMeta(key, value);
}
}
}
else if (line.startsWith("%ImageData:")) {
line = line.substring(11);
String[] t = line.split(" ");
m.setAxisLength(Axes.X, Integer.parseInt(t[0]));
m.setAxisLength(Axes.Y, Integer.parseInt(t[1]));
m.setAxisLength(Axes.CHANNEL, Integer.parseInt(t[3]));
for (int i=4; i<t.length; i++) {
image = t[i].trim();
if (image.length() > 1) {
image = image.substring(1, image.length() - 1);
}
}
}
lineNum++;
line = in.readLine().trim();
}
}
}
/**
* @author Mark Hiner hinerm at gmail.com
*
*/
public static class Reader extends ByteArrayReader<Metadata> {
// -- Constructor --
public Reader() {
domains = new String[] {FormatTools.GRAPHICS_DOMAIN};
}
// -- Reader API Methods --
public ByteArrayPlane openPlane(int imageIndex, int planeIndex,
ByteArrayPlane plane, int x, int y, int w, int h)
throws FormatException, IOException
{
byte[] buf = plane.getData();
Metadata meta = getMetadata();
FormatTools.checkPlaneParameters(this, imageIndex, planeIndex, buf.length, x, y, w, h);
if (meta.isTiff()) {
long[] offsets = meta.getIfds().get(0).getStripOffsets();
getStream().seek(offsets[0]);
int[] map = meta.getIfds().get(0).getIFDIntArray(IFD.COLOR_MAP);
if (map == null) {
readPlane(getStream(), imageIndex, x, y, w, h, plane);
return plane;
}
byte[] b = new byte[w * h];
getStream().skipBytes(2 * y * meta.getAxisLength(imageIndex, Axes.X));
for (int row=0; row<h; row++) {
getStream().skipBytes(x * 2);
for (int col=0; col<w; col++) {
b[row * w + col] = (byte) (getStream().readShort() & 0xff);
}
getStream().skipBytes(2 * (meta.getAxisLength(imageIndex, Axes.X) - w - x));
}
for (int i=0; i<b.length; i++) {
int ndx = b[i] & 0xff;
for (int j=0; j<meta.getAxisLength(imageIndex, Axes.CHANNEL); j++) {
if (j < 3) {
buf[i*meta.getAxisLength(imageIndex, Axes.CHANNEL) + j] = (byte) map[ndx + j*256];
}
else {
boolean zero =
map[ndx] == 0 && map[ndx + 256] == 0 && map[ndx + 512] == 0;
buf[i * meta.getAxisLength(imageIndex, Axes.CHANNEL) + j] = zero ? (byte) 0 : (byte) 255;
}
}
}
return plane;
}
if (meta.getStart() == 0) {
throw new FormatException("Vector data not supported.");
}
getStream().seek(0);
for (int line=0; line<=meta.getStart(); line++) {
getStream().readLine();
}
int bytes = FormatTools.getBytesPerPixel(meta.getPixelType(imageIndex));
if (meta.isBinary()) {
// pixels are stored as raw bytes
readPlane(getStream(), imageIndex, x, y, w, h, plane);
}
else {
// pixels are stored as a 2 character hexadecimal value
String pix = getStream().readString((int) (getStream().length() - getStream().getFilePointer()));
pix = pix.replaceAll("\n", "");
pix = pix.replaceAll("\r", "");
int ndx = meta.getAxisLength(imageIndex, Axes.CHANNEL) * y* bytes *
meta.getAxisLength(imageIndex, Axes.X);
int destNdx = 0;
for (int row=0; row<h; row++) {
ndx += x * meta.getAxisLength(imageIndex, Axes.CHANNEL) * bytes;
for (int col=0; col<w*meta.getAxisLength(imageIndex, Axes.CHANNEL)*bytes; col++) {
buf[destNdx++] =
(byte) Integer.parseInt(pix.substring(2*ndx, 2*(ndx+1)), 16);
ndx++;
}
ndx += meta.getAxisLength(imageIndex, Axes.CHANNEL) * bytes *
(meta.getAxisLength(imageIndex, Axes.X) - w - x);
}
}
return plane;
}
public int getOptimalTileWidth(int imageIndex) {
try {
if (getMetadata().isTiff) {
return (int) getMetadata().getIfds().get(0).getTileWidth();
}
}
catch (FormatException e) {
LOGGER.debug("Could not retrieve tile width", e);
}
return super.getOptimalTileWidth(imageIndex);
}
public int getOptimalTileHeight(int imageIndex) {
try {
if (getMetadata().isTiff()) {
return (int) getMetadata().getIfds().get(0).getTileLength();
}
}
catch (FormatException e) {
LOGGER.debug("Could not retrieve tile height", e);
}
return super.getOptimalTileHeight(imageIndex);
}
}
/**
* @author Mark Hiner hinerm at gmail.com
*
*/
public static class Writer extends AbstractWriter<Metadata> {
// -- Constants --
private static final String DUMMY_PIXEL = "00";
// -- Fields --
private long planeOffset = 0;
// -- Writer API Methods --
public void savePlane(int imageIndex, int planeIndex, Plane plane, int x,
int y, int w, int h) throws FormatException, IOException
{
byte[] buf = plane.getBytes();
checkParams(imageIndex, planeIndex, buf, x, y, w, h);
int sizeX = getMetadata().getAxisLength(imageIndex, Axes.X);
int nChannels = getMetadata().getAxisLength(imageIndex, Axes.CHANNEL);
// write pixel data
// for simplicity, write 80 char lines
if (!initialized[imageIndex][planeIndex]) {
initialized[imageIndex][planeIndex] = true;
writeHeader(imageIndex);
if (!isFullPlane(imageIndex, x, y, w, h)) {
// write a dummy plane that will be overwritten in sections
int planeSize = w * h * nChannels;
for (int i=0; i<planeSize; i++) {
out.writeBytes(DUMMY_PIXEL);
}
}
}
int planeSize = w * h;
StringBuffer buffer = new StringBuffer();
int offset = y * sizeX * nChannels * 2;
out.seek(planeOffset + offset);
for (int row=0; row<h; row++) {
out.skipBytes(nChannels * x * 2);
for (int col=0; col<w*nChannels; col++) {
int i = row * w * nChannels + col;
int index = interleaved || nChannels == 1 ? i :
(i % nChannels) * planeSize + (i / nChannels);
String s = Integer.toHexString(buf[index]);
// only want last 2 characters of s
if (s.length() > 1) buffer.append(s.substring(s.length() - 2));
else {
buffer.append("0");
buffer.append(s);
}
}
out.writeBytes(buffer.toString());
buffer.delete(0, buffer.length());
out.skipBytes(nChannels * (sizeX - w - x) * 2);
}
// write footer
out.seek(out.length());
out.writeBytes("\nshowpage\n");
}
public int[] getPixelTypes(String codec) {
return new int[] {FormatTools.UINT8};
}
// -- Helper methods --
private void writeHeader(int imageIndex) throws IOException {
int width = getMetadata().getAxisLength(imageIndex, Axes.X);
int height = getMetadata().getAxisLength(imageIndex, Axes.Y);
int nChannels = getMetadata().getAxisLength(imageIndex, Axes.CHANNEL);
out.writeBytes("%!PS-Adobe-2.0 EPSF-1.2\n");
out.writeBytes("%%Title: " + getMetadata().getDatasetName() + "\n");
out.writeBytes("%%Creator: OME Bio-Formats\n");
out.writeBytes("%%Pages: 1\n");
out.writeBytes("%%BoundingBox: 0 0 " + width + " " + height + "\n");
out.writeBytes("%%EndComments\n\n");
out.writeBytes("/ld {load def} bind def\n");
out.writeBytes("/s /stroke ld /f /fill ld /m /moveto ld /l " +
"/lineto ld /c /curveto ld /rgb {255 div 3 1 roll 255 div 3 1 " +
"roll 255 div 3 1 roll setrgbcolor} def\n");
out.writeBytes("0 0 translate\n");
out.writeBytes(((float) width) + " " + ((float) height) + " scale\n");
out.writeBytes("/picstr 40 string def\n");
out.writeBytes(width + " " + height + " 8 [" + width + " 0 0 " +
(-1 * height) + " 0 " + height +
"] {currentfile picstr readhexstring pop} ");
if (nChannels == 1) {
out.writeBytes("image\n");
}
else {
out.writeBytes("false 3 colorimage\n");
}
planeOffset = out.getFilePointer();
}
}
/**
* Necessary dummy translator, so that an EPS-OMEXML translator can be used
*
* @author Mark Hiner hinerm at gmail.com
*
*/
@Plugin(type = Translator.class, attrs =
{@Attr(name = EPSTranslator.SOURCE, value = ome.scifio.Metadata.CNAME),
@Attr(name = EPSTranslator.DEST, value = Metadata.CNAME)},
priority = Priority.LOW_PRIORITY)
public static class EPSTranslator
extends DefaultTranslator
{ }
} |
package Karyon.Exceptions;
/**
* Data Migration Exceptions occur when a data store could not be upgraded or downgraded
*/
public class DataMigrationFailedException
extends Karyon.Exceptions.Exception
{
/**
* Creates a new instance of DataMigrationException
* @param toMigration the migration that caused the error
* @param toReason the error that occurred
*/
public DataMigrationFailedException(DataMigration toMigration, Throwable toReason)
{
this(toMigration.getClass(), toReason);
}
/**
* Creates a new instance of DataMigrationException
* @param toMigrationClass the migration that caused the error
* @param toReason the error that occurred
* @param <K> the type of the data migration
*/
public <K extends DataMigration> DataMigrationFailedException(Class<K> toMigrationClass, Throwable toReason)
{
super(toMigrationClass.getName() + " failed.", toReason);
}
} |
package com.antarescraft.kloudy.hologuiapi;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.commons.io.IOUtils;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import com.antarescraft.kloudy.hologuiapi.guicomponents.GUIComponent;
import com.antarescraft.kloudy.hologuiapi.guicomponents.GUIPage;
import com.antarescraft.kloudy.hologuiapi.imageprocessing.GifProcessor;
import com.antarescraft.kloudy.hologuiapi.imageprocessing.PngJpgProcessor;
import com.antarescraft.kloudy.hologuiapi.util.ConfigManager;
import net.md_5.bungee.api.ChatColor;
/**
* Represents an external plugin using the HoloGUIAPI to create GUI pages
*/
public abstract class HoloGUIPlugin extends JavaPlugin
{
private HashMap<String, GUIPage> guiPages = new HashMap<String, GUIPage>();
private ArrayList<String> yamlFiles = new ArrayList<String>(); // Array of resource yaml filenames within the jar
private ArrayList<String> imageFiles = new ArrayList<String>(); // Array of resource image filenames within the jar
private boolean guiPagesLoaded;
private String minSupportedApiVersion = "1.0";
public HoloGUIPlugin()
{
guiPagesLoaded = false;
initFileStructure();
// Pull out all resource files from the jar and save them to the correct plugin data folder.
CodeSource source = this.getClass().getProtectionDomain().getCodeSource();
if(source != null)
{
URL jar = source.getLocation();
try
{
ZipInputStream zip = new ZipInputStream( jar.openStream());
ZipEntry entry = null;
while((entry = zip.getNextEntry()) != null)
{
String entryName = entry.getName();
// Yaml files
if(entryName.startsWith(HoloGUIApi.PATH_TO_YAMLS) && entryName.endsWith(".yml") )
{
String[] pathTokens = entryName.split("/");
yamlFiles.add(pathTokens[pathTokens.length-1]);
}
// Image files
if(entryName.startsWith(HoloGUIApi.PATH_TO_IMAGES) &&
(entryName.endsWith(".png") || entryName.endsWith(".jpg") || entryName.endsWith(".gif")))
{
String[] pathTokens = entryName.split("/");
imageFiles.add(pathTokens[pathTokens.length-1]);
}
}
copyResourceConfigs();
copyResourceImages();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
/**
* Set the minimum version of HoloGUIApi that the plugin can run on
*/
public void setMinSupportedApiVersion(String version)
{
this.minSupportedApiVersion = version;
}
/**
* Checks to see if the version of HoloGUIApi installed on the server is at least
* the minSupportedApiVersion for this plugin.
*
* If the HoloGUIApi version is too old this method will unload the plugin
* and display an error message in the console alerting the server owner to
* update HoloGUIApi.
*/
public void checkMinApiVersion()
{
if(minSupportedApiVersion == null) minSupportedApiVersion = "1.0";
if(versionCompare(getHoloGUIApi().getDescription().getVersion(), minSupportedApiVersion) < 0)
{
Bukkit.getConsoleSender().sendMessage(ChatColor.RED + String.format("[%s]: HoloGUIApi-v%s is required to run the plugin. Please update HoloGUIApi with the latest version from Spigot.",
getName(), minSupportedApiVersion));
}
}
private int versionCompare(String v1, String v2)
{
if(v1.equals(v2)) return 0;
String[] v1Tokens = v1.split("\\.");
String[] v2Tokens = v2.split("\\.");
int length = v1Tokens.length;
if(v2Tokens.length > v1Tokens.length) length = v2Tokens.length;
for(int i = 0; i < length; i++)
{
if(i >= v1Tokens.length || i >= v2Tokens.length )//reached the end, return the longer version number
{
return (v1Tokens.length > v2Tokens.length) ? 1 : -1;
}
int v1Value = Integer.parseInt(v1Tokens[i]);
int v2Value = Integer.parseInt(v2Tokens[i]);
if(v1Value > v2Value)
{
return 1;
}
else if(v1Value < v2Value)
{
return -1;
}
}
return 0;
}
/**
* @return ArrayList<String> of all yaml files contained in /resources/yamls in the plugin jar
*/
public ArrayList<String> getYamlFilenames()
{
return yamlFiles;
}
/**
* @return an instance of the HoloGUIApi class.
*/
public HoloGUIApi getHoloGUIApi()
{
return (HoloGUIApi) Bukkit.getServer().getPluginManager().getPlugin("HoloGUIApi");
}
/**
* @return A HashMap<String, GUIPage>, where the key is the gui page id and the value is the GUIPage object
*/
public HashMap<String, GUIPage> getGUIPages()
{
return guiPages;
}
/**
*
* @param guiPageId
* @return GUIPage object with the given guiPageId. returns null if no gui page exists with the given guiPageId
*/
public GUIPage getGUIPage(String guiPageId)
{
return guiPages.get(guiPageId);
}
/**
* Returns the GUIComponent with the specified guiContainerId and guiComponentId.
*
* @param guiPageId Id of the GUIPage containing the component
* @param guiComponentId Id of the GUIComponent
* @return The GUIComponent contained in the guiContainer with the specified id
*/
public GUIComponent getGUIComponent(String guiPageId, String guiComponentId)
{
GUIPage guiPage = getGUIPages().get(guiPageId);
if(guiPage == null) return null;
return guiPage.getComponent(guiComponentId);
}
public boolean guiPagesLoaded()
{
return guiPagesLoaded;
}
public void setGUIPagesLoaded(boolean guiPagesLoaded)
{
this.guiPagesLoaded = guiPagesLoaded;
}
public void addGUIPage(String guiContainerId, GUIPage guiContainer)
{
guiPages.put(guiContainerId, guiContainer);
}
public void setGUIPages(HashMap<String, GUIPage> guiContainers)
{
this.guiPages = guiContainers;
}
/**
* Causes HoloGUI to load the gui containers async from yaml for this HoloGUIPlugin.
* A HoloGUIPagesLoadedEvent is triggered after the config values are finished loading
*/
public void loadGUIPages()
{
loadGUIPages(null);
}
/**
* Causes HoloGUI to load the gui containers async from yaml for this HoloGUIPlugin.
* A HoloGUIPagesLoadedEvent is triggered after the config values are finished loading
*
* @param callback callback function that executes when the guipages have finished loading
*/
public void loadGUIPages(final GUIPageLoadComplete callback)
{
guiPagesLoaded = false;
guiPages.clear();
final HoloGUIPlugin self = this;
new BukkitRunnable()
{
@Override
public void run()
{
for(String yamlFile : yamlFiles)
{
GUIPage guiPage = ConfigManager.loadGUIPage(self, new File(String.format("plugins/%s/gui configuration files/%s", getName(), yamlFile)));
guiPages.put(guiPage.getId(), guiPage);
}
if(callback != null)
{
callback.onGUIPageLoadComplete();
}
guiPagesLoaded = true;
}
}.runTaskAsynchronously(this);
}
/**
* Copy resource images into the plugin image data folder
*/
public void copyResourceImages()
{
copyResourceImages(false);
}
/**
* @param overwriteExistingImages (true|false) if the plugin should override images files from plugin folder with the images from inside the jar
* Copies the resource images from the plugin jar to plugins/<holoGUI_plugin_name>/images folder
*/
public void copyResourceImages(boolean overwriteExistingImages)
{
for(String imageName : imageFiles)
{
try
{
InputStream inputStream = getResource("resources/images/" + imageName);
File imagePath = new File(String.format("plugins/%s/images/%s",
getName(), imageName));
if((!overwriteExistingImages && !imagePath.exists()) || overwriteExistingImages)
{
FileOutputStream output = new FileOutputStream(imagePath);
output.write(IOUtils.toByteArray(inputStream));
inputStream.close();
output.close();
}
}
catch(Exception e){e.printStackTrace();}
}
}
/**
* * Copies the resource gui pages from the plugin jar to plugins/<holoGUI_plugin_name>/gui configuration files folder
*/
public void copyResourceConfigs()
{
copyResourceConfigs(false);
}
/**
* @param overwriteExistingYamls (true|false) if the plugin should override yaml files from plugin folder with the yamls from inside the jar
* Copies the resource gui pages from the plugin jar to plugins/<holoGUI_plugin_name>/gui configuration files folder
*/
public void copyResourceConfigs(boolean overwriteExistingYamls)
{
for(String yamlName : yamlFiles)
{
try
{
InputStream inputStream = getResource("resources/yamls/" + yamlName);
File yamlPath = new File(String.format("plugins/%s/gui configuration files/%s",
getName(), yamlName));
if((!overwriteExistingYamls && !yamlPath.exists()) || overwriteExistingYamls)
{
FileOutputStream output = new FileOutputStream(yamlPath);
output.write(IOUtils.toByteArray(inputStream));
inputStream.close();
output.close();
}
}
catch(Exception e){e.printStackTrace();}
}
}
/**
* Loads an image resource in the plugin jar.
* @param imageName The image filename to load from the plugin jar.
* @return InputStream for the image.
*/
public InputStream loadImageStream(String imageName)
{
if(imageName.contains(".jpg") || imageName.contains(".png") || imageName.contains(".gif"))
{
return getResource(HoloGUIApi.PATH_TO_IMAGES + "/" + imageName);
}
return null;
}
/**
* Resource images should be stored in 'resources/images' in the plugin jar
*
* Loads and processes the specified imageName. Returns the image as a String[][]. Returns null if the file couldn't be found.
*/
public String[][] loadImage(String imageName, int width, int height, boolean symmetrical)
{
String[][] imageLines = null;
InputStream inputStream = null;
try
{
inputStream = loadImageStream(imageName);
if(inputStream == null) return null;
if(imageName.endsWith(".gif"))
{
imageLines = GifProcessor.processGif(imageName, inputStream, width, height, symmetrical);
}
else if(imageName.endsWith(".jpg") || imageName.endsWith(".png"))
{
imageLines = PngJpgProcessor.processImage(imageName, inputStream, width, height, symmetrical);
}
}
catch(Exception e)
{
System.out.println("Error on opening resource: " + HoloGUIApi.PATH_TO_IMAGES + "/" + imageName);
e.printStackTrace();
}
finally
{
try
{
if(inputStream != null)inputStream.close();
}
catch (IOException e) {}
}
return imageLines;
}
/**
* Creates the plugin's data folder and gui_page_configs folder
*/
private void initFileStructure()
{
try
{
File folder = new File(String.format("plugins/%s", getName()));
if(!folder.exists())
{
folder.mkdir();
}
folder = new File(String.format("plugins/%s/gui configuration files", getName()));
if(!folder.exists())
{
folder.mkdir();
}
folder = new File(String.format("plugins/%s/images", getName()));
if(!folder.exists())
{
folder.mkdir();
}
}
catch(Exception e){}
}
} |
package org.xwiki.extension.repository.internal;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Developer;
import org.apache.maven.model.License;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.reflections.Reflections;
import org.reflections.scanners.ResourcesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;
import org.reflections.util.FilterBuilder;
import org.slf4j.Logger;
import org.xwiki.component.annotation.Component;
import org.xwiki.extension.DefaultExtensionAuthor;
import org.xwiki.extension.DefaultExtensionDependency;
import org.xwiki.extension.ExtensionId;
import org.xwiki.extension.ExtensionLicense;
import org.xwiki.extension.ExtensionLicenseManager;
import org.xwiki.properties.ConverterManager;
import com.google.common.base.Predicates;
/**
* Scan jars to find core extensions.
*
* @version $Id$
*/
@Component
@Singleton
public class DefaultCoreExtensionScanner implements CoreExtensionScanner
{
/**
* The package containing maven informations in a jar file.
*/
private static final String MAVENPACKAGE = "META-INF.maven";
/**
* Unknown.
*/
private static final String UNKNOWN = "unknown";
/**
* SNAPSHOT suffix in versions.
*/
private static final String SNAPSHOTSUFFIX = "-SNAPSHOT";
/**
* The logger to log.
*/
@Inject
private Logger logger;
/**
* Used to parse some custom properties.
*/
@Inject
private ConverterManager converter;
@Inject
private ExtensionLicenseManager licenseManager;
@Override
public Map<String, DefaultCoreExtension> loadExtensions(DefaultCoreExtensionRepository repository)
{
Set<URL> mavenURLs = ClasspathHelper.forPackage(MAVENPACKAGE);
ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
configurationBuilder.setScanners(new ResourcesScanner());
configurationBuilder.setUrls(mavenURLs);
configurationBuilder.filterInputsBy(new FilterBuilder.Include(FilterBuilder.prefix(MAVENPACKAGE)));
Reflections reflections = new Reflections(configurationBuilder);
Set<String> descriptors = reflections.getResources(Predicates.equalTo("pom.xml"));
Map<String, DefaultCoreExtension> extensions = new HashMap<String, DefaultCoreExtension>(descriptors.size());
List<Dependency> dependencies = new ArrayList<Dependency>();
List<Object[]> coreArtefactIds = new ArrayList<Object[]>();
for (String descriptor : descriptors) {
URL descriptorUrl = getClass().getClassLoader().getResource(descriptor);
InputStream descriptorStream = getClass().getClassLoader().getResourceAsStream(descriptor);
try {
MavenXpp3Reader reader = new MavenXpp3Reader();
Model mavenModel = reader.read(descriptorStream);
String version = resolveVersion(mavenModel.getVersion(), mavenModel, false);
String groupId = resolveGroupId(mavenModel.getGroupId(), mavenModel, false);
String extensionURLStr = descriptorUrl.toString();
extensionURLStr =
extensionURLStr.substring(0, descriptorUrl.toString().indexOf(MAVENPACKAGE.replace('.', '/')));
URL extensionURL = new URL(extensionURLStr);
DefaultCoreExtension coreExtension =
new DefaultCoreExtension(repository, extensionURL, new ExtensionId(groupId + ':'
+ mavenModel.getArtifactId(), version), packagingToType(mavenModel.getPackaging()));
coreExtension.setName(mavenModel.getName());
coreExtension.setSummary(mavenModel.getDescription());
for (Developer developer : mavenModel.getDevelopers()) {
URL authorURL = null;
if (developer.getUrl() != null) {
try {
authorURL = new URL(developer.getUrl());
} catch (MalformedURLException e) {
// TODO: log ?
}
}
coreExtension.addAuthor(new DefaultExtensionAuthor(developer.getId(), authorURL));
}
coreExtension.setWebsite(mavenModel.getUrl());
for (License license : mavenModel.getLicenses()) {
coreExtension.addLicense(getExtensionLicense(license));
}
// features
String featuresString = mavenModel.getProperties().getProperty("xwiki.extension.features");
if (StringUtils.isNotBlank(featuresString)) {
coreExtension.setFeatures(this.converter.<Collection<String>> convert(List.class, featuresString));
}
// custom properties
coreExtension.putProperty("maven.groupId", groupId);
coreExtension.putProperty("maven.artifactId", mavenModel.getArtifactId());
extensions.put(coreExtension.getId().getId(), coreExtension);
coreArtefactIds.add(new Object[] {mavenModel.getArtifactId(), coreExtension});
// dependencies
for (Dependency mavenDependency : mavenModel.getDependencies()) {
if (!mavenDependency.isOptional()
&& (mavenDependency.getScope() == null || mavenDependency.getScope().equals("compile") || mavenDependency
.getScope().equals("runtime"))) {
coreExtension.addDependency(new DefaultExtensionDependency(resolveGroupId(
mavenDependency.getGroupId(), mavenModel, true)
+ ':' + mavenDependency.getArtifactId(), resolveVersion(mavenDependency.getVersion(),
mavenModel, true)));
}
if (mavenDependency.getGroupId().equals("${project.groupId}")) {
mavenDependency.setGroupId(groupId);
}
if (mavenDependency.getVersion() == null) {
mavenDependency.setVersion(UNKNOWN);
} else if (mavenDependency.getVersion().equals("${project.version}")
|| mavenDependency.getVersion().equals("${pom.version}")) {
mavenDependency.setVersion(version);
}
dependencies.add(mavenDependency);
}
} catch (Exception e) {
this.logger.warn("Failed to parse descriptor [" + descriptorUrl
+ "], it will be ignored and not found in core extensions.", e);
} finally {
try {
descriptorStream.close();
} catch (IOException e) {
// Should not happen
this.logger.error("Failed to close descriptor stream [" + descriptorUrl + "]", e);
}
}
}
// Normalize and guess
Map<String, Object[]> fileNames = new HashMap<String, Object[]>();
Map<String, Object[]> guessedArtefacts = new HashMap<String, Object[]>();
Set<URL> urls = ClasspathHelper.forClassLoader();
for (URL url : urls) {
try {
String path = url.toURI().getPath();
String filename = path.substring(path.lastIndexOf('/') + 1);
String type = null;
int extIndex = filename.lastIndexOf('.');
if (extIndex != -1) {
type = filename.substring(extIndex + 1);
filename = filename.substring(0, extIndex);
}
int index;
if (!filename.endsWith(SNAPSHOTSUFFIX)) {
index = filename.lastIndexOf('-');
} else {
index = filename.lastIndexOf('-', filename.length() - SNAPSHOTSUFFIX.length());
}
if (index != -1) {
fileNames.put(filename, new Object[] {url});
String artefactname = filename.substring(0, index);
String version = filename.substring(index + 1);
guessedArtefacts.put(artefactname, new Object[] {version, url, type});
}
} catch (Exception e) {
this.logger.warn("Failed to parse resource name [" + url + "]", e);
}
}
// Try to resolve version no easy to find from the pom.xml
try {
for (Object[] coreArtefactId : coreArtefactIds) {
Object[] artefact = guessedArtefacts.get(coreArtefactId[0]);
DefaultCoreExtension coreExtension = (DefaultCoreExtension) coreArtefactId[1];
if (artefact != null) {
if (coreExtension.getId().getVersion().charAt(0) == '$') {
coreExtension.setId(new ExtensionId(coreExtension.getId().getId(), (String) artefact[0]));
coreExtension.setGuessed(true);
}
if (coreExtension.getType().charAt(0) == '$') {
coreExtension.setType((String) artefact[2]);
coreExtension.setGuessed(true);
}
}
}
// Add dependencies that does not provide proper pom.xml resource and can't be found in the classpath
for (Dependency dependency : dependencies) {
String dependencyId = dependency.getGroupId() + ':' + dependency.getArtifactId();
DefaultCoreExtension coreExtension = extensions.get(dependencyId);
if (coreExtension == null) {
String dependencyFileName = dependency.getArtifactId() + '-' + dependency.getVersion();
if (dependency.getClassifier() != null) {
dependencyFileName += '-' + dependency.getClassifier();
dependencyId += ':' + dependency.getClassifier();
}
Object[] filenameArtifact = fileNames.get(dependencyFileName);
Object[] guessedArtefact = guessedArtefacts.get(dependency.getArtifactId());
if (filenameArtifact != null) {
coreExtension =
new DefaultCoreExtension(repository, (URL) filenameArtifact[0], new ExtensionId(
dependencyId, dependency.getVersion()), packagingToType(dependency.getType()));
coreExtension.setGuessed(true);
} else if (guessedArtefact != null) {
coreExtension =
new DefaultCoreExtension(repository, (URL) guessedArtefact[1], new ExtensionId(
dependencyId, (String) guessedArtefact[0]), packagingToType(dependency.getType()));
coreExtension.setGuessed(true);
}
if (coreExtension != null) {
extensions.put(dependencyId, coreExtension);
}
}
}
} catch (Exception e) {
this.logger.warn("Failed to guess extra information about some extensions", e);
}
return extensions;
}
private String resolveVersion(String modelVersion, Model mavenModel, boolean dependency)
{
String version = modelVersion;
// TODO: download parents and resolve pom.xml properties using aether ? could be pretty expensive for
// the init
if (version == null) {
if (!dependency) {
Parent parent = mavenModel.getParent();
if (parent != null) {
version = parent.getVersion();
}
}
} else if (version.startsWith("$")) {
String propertyName = version.substring(2, version.length() - 1);
if (propertyName.equals("project.version") || propertyName.equals("pom.version")
|| propertyName.equals("version")) {
version = resolveVersion(mavenModel.getVersion(), mavenModel, false);
} else {
String value = mavenModel.getProperties().getProperty(propertyName);
if (value != null) {
version = value;
}
}
}
if (version == null) {
version = UNKNOWN;
}
return version;
}
private String resolveGroupId(String modelGroupId, Model mavenModel, boolean dependency)
{
String groupId = modelGroupId;
// TODO: download parents and resolve pom.xml properties using aether ? could be pretty expensive for
// the init
if (groupId == null) {
if (!dependency) {
Parent parent = mavenModel.getParent();
if (parent != null) {
groupId = parent.getGroupId();
}
}
} else if (groupId.startsWith("$")) {
String propertyName = groupId.substring(2, groupId.length() - 1);
String value = mavenModel.getProperties().getProperty(propertyName);
if (value != null) {
groupId = value;
}
}
if (groupId == null) {
groupId = UNKNOWN;
}
return groupId;
}
private ExtensionLicense getExtensionLicense(License license)
{
if (license.getName() == null) {
return new ExtensionLicense("noname", null);
}
ExtensionLicense extensionLicense = this.licenseManager.getLicense(license.getName());
return extensionLicense != null ? extensionLicense : new ExtensionLicense(license.getName(), null);
}
/**
* Get the extension type from maven packaging.
*
* @param packaging the maven packaging
* @return the extension type
*/
private String packagingToType(String packaging)
{
// support bundle packaging
if (packaging.equals("bundle")) {
return "jar";
}
return packaging;
}
} |
package agaricus.mods.highlighttips;
import cpw.mods.fml.client.registry.KeyBindingRegistry;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.ITickHandler;
import cpw.mods.fml.common.Mod;
import cpw.mods.fml.common.TickType;
import cpw.mods.fml.common.event.FMLPreInitializationEvent;
import cpw.mods.fml.common.network.NetworkMod;
import cpw.mods.fml.common.registry.TickRegistry;
import cpw.mods.fml.relauncher.FMLRelauncher;
import cpw.mods.fml.relauncher.Side;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.MobSpawnerBaseLogic;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityFurnace;
import net.minecraft.tileentity.TileEntityMobSpawner;
import net.minecraft.util.*;
import net.minecraft.world.World;
import net.minecraftforge.common.Configuration;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.liquids.ILiquidTank;
import net.minecraftforge.liquids.ITankContainer;
import net.minecraftforge.liquids.LiquidStack;
import java.util.EnumSet;
import java.util.logging.Level;
@Mod(modid = "HighlightTips", name = "HighlightTips", version = "1.0-SNAPSHOT") // TODO: version from resource
@NetworkMod(clientSideRequired = false, serverSideRequired = false)
public class HighlightTips implements ITickHandler {
private static final int DEFAULT_KEY_TOGGLE = 62;
private static final double DEFAULT_RANGE = 300;
private static final int DEFAULT_X = 0;
private static final int DEFAULT_Y = 0;
private static final int DEFAULT_COLOR = 0xffffff;
private boolean enable = true;
private int keyToggle = DEFAULT_KEY_TOGGLE;
private double range = DEFAULT_RANGE;
private int x = DEFAULT_X;
private int y = DEFAULT_Y;
private int color = DEFAULT_COLOR;
private ToggleKeyHandler toggleKeyHandler;
@Mod.PreInit
public void preInit(FMLPreInitializationEvent event) {
Configuration cfg = new Configuration(event.getSuggestedConfigurationFile());
try {
cfg.load();
enable = cfg.get(Configuration.CATEGORY_GENERAL, "enable", true).getBoolean(true);
keyToggle = cfg.get(Configuration.CATEGORY_GENERAL, "key.toggle", DEFAULT_KEY_TOGGLE).getInt(DEFAULT_KEY_TOGGLE);
range = cfg.get(Configuration.CATEGORY_GENERAL, "range", DEFAULT_RANGE).getDouble(DEFAULT_RANGE);
x = cfg.get(Configuration.CATEGORY_GENERAL, "x", DEFAULT_X).getInt(DEFAULT_X);
y = cfg.get(Configuration.CATEGORY_GENERAL, "y", DEFAULT_Y).getInt(DEFAULT_Y);
color = cfg.get(Configuration.CATEGORY_GENERAL, "color", DEFAULT_COLOR).getInt(DEFAULT_COLOR);
} catch (Exception e) {
FMLLog.log(Level.SEVERE, e, "HighlightTips had a problem loading it's configuration");
} finally {
cfg.save();
}
if (!FMLRelauncher.side().equals("CLIENT")) {
// gracefully disable on non-client (= server) instead of crashing
enable = false;
}
if (!enable) {
FMLLog.log(Level.INFO, "HighlightTips disabled");
return;
}
TickRegistry.registerTickHandler(this, Side.CLIENT);
KeyBindingRegistry.registerKeyBinding(toggleKeyHandler = new ToggleKeyHandler(keyToggle));
}
private String describeBlock(int id, int meta, TileEntity tileEntity) {
StringBuilder sb = new StringBuilder();
describeBlockID(sb, id, meta);
describeTileEntity(sb, tileEntity);
return sb.toString();
}
private void describeTileEntity(StringBuilder sb, TileEntity te) {
if (te == null) return;
if (te instanceof IInventory) {
IInventory inventory = (IInventory) te;
sb.append(" IInventory: ");
sb.append(inventoryName(inventory));
sb.append(" (");
sb.append(inventory.getSizeInventory());
sb.append(" slots)");
}
if (te instanceof ITankContainer) {
sb.append(" ITankContainer: ");
ILiquidTank[] tanks = ((ITankContainer) te).getTanks(ForgeDirection.UP);
for (ILiquidTank tank : tanks) {
sb.append(describeLiquidStack(tank.getLiquid()));
sb.append(' ');
//sb.append(tank.getTankPressure()); // TODO: tank capacity *used*? this is not it..
//sb.append('/');
sb.append(tank.getCapacity());
int pressure = tank.getTankPressure();
if (pressure < 0) {
sb.append(pressure);
} else {
sb.append('+');
sb.append(pressure);
}
sb.append(' ');
}
}
if (te instanceof TileEntityMobSpawner) {
MobSpawnerBaseLogic logic = ((TileEntityMobSpawner) te).func_98049_a();
sb.append(" Spawner: ");
sb.append(logic.getEntityNameToSpawn());
sb.append(' ');
sb.append(logic.spawnDelay);
}
sb.append(' ');
sb.append(te.getClass().getName());
}
private String inventoryName(IInventory inventory) {
if (!inventory.isInvNameLocalized()) {
return StatCollector.translateToLocal(inventory.getInvName());
} else {
return inventory.getInvName();
}
}
private String describeLiquidStack(LiquidStack liquidStack) {
if (liquidStack == null) return "Empty";
ItemStack itemStack = liquidStack.canonical().asItemStack();
if (itemStack == null) return "Empty";
return itemStack.getDisplayName();
}
private void describeBlockID(StringBuilder sb, int id, int meta) {
Block block = Block.blocksList[id];
if (block == null) {
sb.append("block
return;
}
// block info
sb.append(id);
sb.append(':');
sb.append(meta);
sb.append(' ');
String blockName = block.getLocalizedName();
if (!blockName.startsWith("You ran into")) // a serious Bug, if you have legitly acquired this Block, please report it immidietly"
sb.append(blockName);
// item info, if it was mined (this often has more user-friendly information, but sometimes is identical)
sb.append(" ");
int itemDropDamage = block.damageDropped(meta);
if (Item.itemsList[id + 256] != null) {
ItemStack itemDropStack = new ItemStack(id, 1, itemDropDamage);
String itemDropName = itemDropStack.getDisplayName();
if (!blockName.equals(itemDropName)) {
sb.append(itemDropName);
}
// item info guess if item damage corresponds to block metadata, not necessarily if mined - sometimes more informative
try {
ItemStack itemMetaStack = new ItemStack(id, 1, meta);
String itemMetaName = itemMetaStack.getDisplayName();
if (itemMetaName != null && !blockName.equals(itemMetaName) && !itemDropName.equals(itemMetaName)) {
sb.append(' ');
sb.append(itemMetaName);
}
} catch (Throwable t) {
}
}
if (itemDropDamage != meta) {
sb.append(' ');
sb.append(itemDropDamage);
}
}
// based on net/minecraft/item/Item, copied since it is needlessly protected
protected MovingObjectPosition getMovingObjectPositionFromPlayer(World par1World, EntityPlayer par2EntityPlayer)
{
float f = 1.0F;
float f1 = par2EntityPlayer.prevRotationPitch + (par2EntityPlayer.rotationPitch - par2EntityPlayer.prevRotationPitch) * f;
float f2 = par2EntityPlayer.prevRotationYaw + (par2EntityPlayer.rotationYaw - par2EntityPlayer.prevRotationYaw) * f;
double d0 = par2EntityPlayer.prevPosX + (par2EntityPlayer.posX - par2EntityPlayer.prevPosX) * (double)f;
double d1 = par2EntityPlayer.prevPosY + (par2EntityPlayer.posY - par2EntityPlayer.prevPosY) * (double)f + 1.62D - (double)par2EntityPlayer.yOffset;
double d2 = par2EntityPlayer.prevPosZ + (par2EntityPlayer.posZ - par2EntityPlayer.prevPosZ) * (double)f;
Vec3 vec3 = par1World.getWorldVec3Pool().getVecFromPool(d0, d1, d2);
float f3 = MathHelper.cos(-f2 * 0.017453292F - (float) Math.PI);
float f4 = MathHelper.sin(-f2 * 0.017453292F - (float) Math.PI);
float f5 = -MathHelper.cos(-f1 * 0.017453292F);
float f6 = MathHelper.sin(-f1 * 0.017453292F);
float f7 = f4 * f5;
float f8 = f3 * f5;
double d3 = 5.0D;
if (par2EntityPlayer instanceof EntityPlayerMP)
{
d3 = ((EntityPlayerMP)par2EntityPlayer).theItemInWorldManager.getBlockReachDistance();
}
Vec3 vec31 = vec3.addVector((double)f7 * d3, (double)f6 * d3, (double)f8 * d3);
return par1World.rayTraceBlocks_do_do(vec3, vec31, false, false); // "ray traces all blocks, including non-collideable ones"
}
@Override
public void tickEnd(EnumSet<TickType> type, Object... tickData) {
if (!toggleKeyHandler.showInfo) return;
Minecraft mc = Minecraft.getMinecraft();
GuiScreen screen = mc.currentScreen;
if (screen != null) return;
float partialTickTime = 1;
MovingObjectPosition mop = getMovingObjectPositionFromPlayer(mc.theWorld, mc.thePlayer);
String s;
if (mop == null) {
return;
} else if (mop.typeOfHit == EnumMovingObjectType.ENTITY) {
// TODO: find out why this apparently never triggers
s = "entity " + mop.entityHit.getClass().getName();
} else if (mop.typeOfHit == EnumMovingObjectType.TILE) {
int id = mc.thePlayer.worldObj.getBlockId(mop.blockX, mop.blockY, mop.blockZ);
int meta = mc.thePlayer.worldObj.getBlockMetadata(mop.blockX, mop.blockY, mop.blockZ);
TileEntity tileEntity = mc.thePlayer.worldObj.blockHasTileEntity(mop.blockX, mop.blockY, mop.blockZ) ? mc.thePlayer.worldObj.getBlockTileEntity(mop.blockX, mop.blockY, mop.blockZ) : null;
try {
s = describeBlock(id, meta, tileEntity);
} catch (Throwable t) {
s = id + ":" + meta + " - " + t;
t.printStackTrace();
}
} else {
s = "unknown";
}
mc.fontRenderer.drawStringWithShadow(s, x, y, color);
}
@Override
public void tickStart(EnumSet<TickType> type, Object... tickData) {
}
@Override
public EnumSet<TickType> ticks() {
return EnumSet.of(TickType.RENDER);
}
@Override
public String getLabel() {
return "HighlightTips";
}
} |
package at.ac.tuwien.inso.service;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.springframework.security.access.prepost.PreAuthorize;
import at.ac.tuwien.inso.entity.Lecturer;
import at.ac.tuwien.inso.entity.Subject;
public interface LecturerService {
/**
* returns the currently logged in lecturer
*
* user needs to be lecturer
*
* @return the logged in lecturer
*/
@PreAuthorize("hasRole('LECTURER')")
Lecturer getLoggedInLecturer();
/**
* returns all subjects that are owned by the currently logged in lecturer
*
* user needs to be lecturer
*
* @return
*/
@PreAuthorize("hasRole('LECTURER')")
Iterable<Subject> getOwnSubjects();
/**
* finds subjects for the given lecturer. lecturer should not be null
*
* user needs to be authenticated
*
* @param lecturer
* @return
*/
@PreAuthorize("isAuthenticated()")
List<Subject> findSubjectsFor(Lecturer lecturer);
/**
* generates the Qr code url
*
* @param lecturer, id, email and two factor secret should not be null
* @return the url as string
* @throws UnsupportedEncodingException
*/
@PreAuthorize("hasRole('ADMIN')")
String generateQRUrl(Lecturer lecturer) throws UnsupportedEncodingException;
} |
package org.apache.xerces.impl.v2;
import org.apache.xerces.impl.XMLErrorReporter;
import org.apache.xerces.util.SymbolTable;
import org.w3c.dom.Element;
import java.util.Hashtable;
/**
* Class <code>XSDAbstractTraverser</code> serves as the base class for all
* other <code>XSD???Traverser</code>s. It holds the common data and provide
* a unified way to initialize these data.
*
* @version $Id$
*/
abstract class XSDAbstractTraverser {
//Shared data
protected XSDHandler fSchemaHandler = null;
protected SymbolTable fSymbolTable = null;
protected XSAttributeChecker fAttrChecker = null;
private XMLErrorReporter fErrorReporter = null;
//REVISIT: should we add global fSchemaGrammar field
XSDAbstractTraverser (XSDHandler handler,
XMLErrorReporter errorReporter,
XSAttributeChecker attrChecker) {
fSchemaHandler = handler;
fErrorReporter = errorReporter;
fAttrChecker = attrChecker;
}
// REVISIT: should symbol table passed as parameter to constractor or
// be set using the following method?
void setSymbolTable (SymbolTable table) {
fSymbolTable = table;
}
// traver the annotation declaration
// REVISIT: store annotation information for PSVI
int traverseAnnotationDecl(Element annotationDecl, Hashtable parentAttrs) {
// General Attribute Checking
// There is no difference between global or local annotation,
// so we assume it's always global.
Hashtable attrValues = fAttrChecker.checkAttributes(annotationDecl, true);
for(Element child = XMLManipulator.getFirstChildElement(annotationDecl);
child != null;
child = XMLManipulator.getNextSiblingElement(child)) {
String name = child.getLocalName();
// the only valid children of "annotation" are
// "appinfo" and "documentation"
if(!((name.equals(SchemaSymbols.ELT_APPINFO)) ||
(name.equals(SchemaSymbols.ELT_DOCUMENTATION)))) {
reportSchemaError("an <annotation> can only contain <appinfo> and <documentation> elements", null);
}
// General Attribute Checking
// There is no difference between global or local appinfo/documentation,
// so we assume it's always global.
attrValues = fAttrChecker.checkAttributes(child, true);
}
// REVISIT: an annotation index should be returned when we support PSVI
return -1;
}
// REVISIT: is it how we want to handle error reporting?
void reportGenericSchemaError (String error) {
}
void reportSchemaError(String key, Object args[]) {
}
// Evaluates content of Annotation if present.
// @param: elm - parent element
// @param: content - the first child of <code>elm</code> that needs to be checked
// @param: isEmpty: -- true if the content allowed is (annotation?) only
// false if must have some element (with possible preceding <annotation?>)
//REVISIT: this function should be used in all traverse* methods!
//REVISIT: in fact, no one should call this method. To support PSVI, the
// traversers have to call traverseAnnotationDecl directly, and
// store the returned annotation index in their own structure.
Element checkContent( Element elm, Element content, boolean isEmpty ) {
return null;
}
} |
package bio.terra.stairway;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
public class RetryRuleRandomBackoff implements RetryRule {
private final long operationIncrementMilliseconds;
private final int maxConcurrency;
private final int maxCount;
// Initialized parameters
private int retryCount;
/**
* Retry with random backoff for concurrent threads Assume operation requires
* operationIncrementMilliseconds. We want to spread maxConcurrency threads so that we will do
* roughly one at a time. So we get a random integer between 0 and maxConcurrency-1 and multiply
* that by the operation time. We sleep that long and retry.
*
* @param operationIncrementMilliseconds - interval to spread across concurrency
* @param maxConcurrency - maximum concurrent threads to back off
* @param maxCount - maximum times to retry
*/
public RetryRuleRandomBackoff(
long operationIncrementMilliseconds, int maxConcurrency, int maxCount) {
this.operationIncrementMilliseconds = operationIncrementMilliseconds;
this.maxConcurrency = maxConcurrency;
this.maxCount = maxCount;
}
@Override
public void initialize() {
retryCount = 0;
}
@Override
public boolean retrySleep() throws InterruptedException {
if (retryCount >= maxCount) {
return false;
}
int sleepUnits = ThreadLocalRandom.current().nextInt(0, maxConcurrency);
TimeUnit.MILLISECONDS.sleep(sleepUnits * operationIncrementMilliseconds);
retryCount++;
return true;
}
} |
package org.apollo.game.message;
import java.util.HashMap;
import java.util.Map;
import org.apollo.game.model.entity.Player;
/**
* A group of {@link MessageHandlerChain}s classified by the {@link Message} type.
*
* @author Graham
* @author Ryley
* @author Major
*/
public final class MessageHandlerChainSet {
/**
* The {@link Map} of Message types to {@link MessageHandlerChain}s
*/
private final Map<Class<? extends Message>, MessageHandlerChain<? extends Message>> chains = new HashMap<>();
/**
* Notifies the appropriate {@link MessageHandlerChain} that a {@link Message} has been received.
*
* @param player The {@link Player} receiving the Message.
* @param message The Message.
* @return {@code true} if the Message propagated down the chain without being terminated or if the chain for the
* Message was not found, otherwise {@code false}.
*/
public <M extends Message> boolean notify(Player player, M message) {
@SuppressWarnings("unchecked")
MessageHandlerChain<M> chain = (MessageHandlerChain<M>) chains.get(message.getClass());
return (chain == null) || chain.notify(player, message);
}
/**
* Places the {@link MessageHandlerChain} into this set.
*
* @param clazz The {@link Class} to associate the MessageHandlerChain with.
* @param handler The MessageHandlerChain.
*/
@SuppressWarnings("unchecked")
public <M extends Message> void putHandler(Class<M> clazz, MessageHandler<? extends Message> handler) {
MessageHandlerChain<M> chain = (MessageHandlerChain<M>) chains.computeIfAbsent(clazz, MessageHandlerChain::new);
chain.addHandler((MessageHandler<M>) handler);
}
} |
package com.coderedrobotics.tiberius.statics;
/**
*
* @author austin
*/
public class Calibration {
public static double pickupClearSetpoint = 0.7;
public static double pickupExtendedSetpoint = 1.244;
public static double pickupExtendedLimit = 1.244;
public static double pickupRetractedLimit = 0.2867;
public static double pickupClearLimit = 0.6312;
public static double leftOuterLimit = 2.51;
public static double leftInnerLimit = 2.96;
public static double rightOuterLimit = 2.31;
public static double rightInnerLimit = 2.55;
} |
package br.com.dbsoft.ui.component.chart;
import javax.faces.component.FacesComponent;
import javax.faces.component.behavior.ClientBehaviorHolder;
import br.com.dbsoft.ui.component.DBSUIData;
import br.com.dbsoft.ui.core.DBSFaces;
import br.com.dbsoft.util.DBSNumber;
@FacesComponent(DBSChart.COMPONENT_TYPE)
public class DBSChart extends DBSUIData implements ClientBehaviorHolder{
public final static String COMPONENT_TYPE = DBSFaces.DOMAIN_UI_COMPONENT + "." + DBSFaces.ID.CHART;
public final static String RENDERER_TYPE = COMPONENT_TYPE;
public static enum TYPE {
BAR ("bar", true),
LINE ("line", true),
PIE ("pie", false);
private String wName;
private Boolean wMatrix;
private TYPE(String pName, Boolean pMatrix) {
this.wName = pName;
this.wMatrix = pMatrix;
}
public String getName() {
return wName;
}
public Boolean isMatrix(){
return wMatrix;
}
public static TYPE get(String pCode) {
if (pCode == null){
return LINE;
}
pCode = pCode.trim().toLowerCase();
switch (pCode) {
case "bar":
return BAR;
case "line":
return LINE;
case "pie":
return PIE;
default:
return LINE;
}
}
}
protected enum PropertyKeys {
type,
hue,
itensCount,
index,
columnScale,
totalValue;
String toString;
PropertyKeys(String toString) {
this.toString = toString;
}
PropertyKeys() {}
@Override
public String toString() {
return ((this.toString != null) ? this.toString : super.toString());
}
}
public DBSChart(){
setRendererType(DBSChart.RENDERER_TYPE);
}
public String getType() {
return (String) getStateHelper().eval(PropertyKeys.type, null);
}
public void setType(String pType) {
getStateHelper().put(PropertyKeys.type, pType);
handleAttribute("type", pType);
}
public Double getTotalValue() {
return DBSNumber.toDouble(getStateHelper().eval(PropertyKeys.totalValue, 0D));
}
public void setTotalValue(Double pTotalValue) {
getStateHelper().put(PropertyKeys.totalValue, pTotalValue);
handleAttribute("totalValue", pTotalValue);
}
public Integer getIndex() {
return (Integer) getStateHelper().eval(PropertyKeys.index, 1);
}
public void setIndex(Integer pIndex) {
getStateHelper().put(PropertyKeys.index, pIndex);
handleAttribute("index", pIndex);
}
public Integer getItensCount() {
return (Integer) getStateHelper().eval(PropertyKeys.itensCount, 0);
}
public void setItensCount(Integer pItensCount) {
getStateHelper().put(PropertyKeys.itensCount, pItensCount);
handleAttribute("itensCount", pItensCount);
}
public Double getColumnScale() {
return (Double) getStateHelper().eval(PropertyKeys.columnScale, 0D);
}
public void setColumnScale(Double pColumnScale) {
getStateHelper().put(PropertyKeys.columnScale, pColumnScale);
handleAttribute("columnScale", pColumnScale);
}
public Float getHue() {
return (Float) getStateHelper().eval(PropertyKeys.hue, null);
}
public void setHue(Float pHue) {
if (pHue != null){
if (pHue > 1
|| pHue < 0){
pHue = null;
}
}
getStateHelper().put(PropertyKeys.hue, pHue);
handleAttribute("hue", pHue);
}
} |
package com.ecyrd.jspwiki.auth.user;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Properties;
import org.apache.catalina.util.HexUtils;
import org.apache.log4j.Logger;
import com.ecyrd.jspwiki.NoRequiredPropertyException;
import com.ecyrd.jspwiki.WikiEngine;
import com.ecyrd.jspwiki.auth.NoSuchPrincipalException;
import com.ecyrd.jspwiki.auth.WikiPrincipal;
import com.ecyrd.jspwiki.auth.WikiSecurityException;
{
protected static final Logger log = Logger.getLogger( AbstractUserDatabase.class );
protected static final String SHA_PREFIX = "{SHA}";
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#commit()
*/
public abstract void commit() throws WikiSecurityException;
/**
* Looks up and returns the first {@link UserProfile}in the user database
* that whose login name, full name, or wiki name matches the supplied
* string. This method provides a "forgiving" search algorithm for resolving
* principal names when the exact profile attribute that supplied the name
* is unknown.
* @param index the login name, full name, or wiki name
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#find(java.lang.String)
*/
public UserProfile find( String index ) throws NoSuchPrincipalException
{
UserProfile profile = null;
// Try finding by full name
try {
profile = findByFullName( index );
}
catch ( NoSuchPrincipalException e )
{
}
if ( profile != null )
{
return profile;
}
// Try finding by wiki name
try {
profile = findByWikiName( index );
}
catch ( NoSuchPrincipalException e )
{
}
if ( profile != null )
{
return profile;
}
// Try finding by login name
try {
profile = findByLoginName( index );
}
catch ( NoSuchPrincipalException e )
{
}
if ( profile != null )
{
return profile;
}
throw new NoSuchPrincipalException( "Not in database: " + index );
}
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#findByEmail(java.lang.String)
*/
public abstract UserProfile findByEmail( String index ) throws NoSuchPrincipalException;
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#findByFullName(java.lang.String)
*/
public abstract UserProfile findByFullName( String index ) throws NoSuchPrincipalException;
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#findByLoginName(java.lang.String)
*/
public abstract UserProfile findByLoginName( String index ) throws NoSuchPrincipalException;
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#findByWikiName(java.lang.String)
*/
public abstract UserProfile findByWikiName( String index ) throws NoSuchPrincipalException;
/**
* <p>Looks up the Principals representing a user from the user database. These
* are defined as a set of WikiPrincipals manufactured from the login name,
* full name, and wiki name. If the user database does not contain a user
* with the supplied identifier, throws a {@link NoSuchPrincipalException}.</p>
* <p>When this method creates WikiPrincipals, the Principal containing
* the user's full name is marked as containing the common name (see
* {@link com.ecyrd.jspwiki.auth.WikiPrincipal#WikiPrincipal(String, String)}).
* @param identifier the name of the principal to retrieve; this corresponds to
* value returned by the user profile's
* {@link UserProfile#getLoginName()}method.
* @return the array of Principals representing the user
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#getPrincipals(java.lang.String)
*/
public Principal[] getPrincipals( String identifier ) throws NoSuchPrincipalException
{
try
{
UserProfile profile = findByLoginName( identifier );
ArrayList principals = new ArrayList();
if ( profile.getLoginName() != null && profile.getLoginName().length() > 0 )
{
principals.add( new WikiPrincipal( profile.getLoginName(), WikiPrincipal.LOGIN_NAME ) );
}
if ( profile.getFullname() != null && profile.getFullname().length() > 0 )
{
principals.add( new WikiPrincipal( profile.getFullname(), WikiPrincipal.FULL_NAME ) );
}
if ( profile.getWikiName() != null && profile.getWikiName().length() > 0 )
{
principals.add( new WikiPrincipal( profile.getWikiName(), WikiPrincipal.WIKI_NAME ) );
}
return (Principal[]) principals.toArray( new Principal[principals.size()] );
}
catch( NoSuchPrincipalException e )
{
throw e;
}
}
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#initialize(com.ecyrd.jspwiki.WikiEngine, java.util.Properties)
*/
public abstract void initialize( WikiEngine engine, Properties props ) throws NoRequiredPropertyException;
/**
* Factory method that instantiates a new DefaultUserProfile.
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#newProfile()
*/
public UserProfile newProfile()
{
return new DefaultUserProfile();
}
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#save(com.ecyrd.jspwiki.auth.user.UserProfile)
*/
public abstract void save( UserProfile profile ) throws WikiSecurityException;
/**
* Validates the password for a given user. If the user does not exist in
* the user database, this method always returns <code>false</code>. If
* the user exists, the supplied password is compared to the stored
* password. Note that if the stored password's value starts with
* <code>{SHA}</code>, the supplied password is hashed prior to the
* comparison.
* @param loginName the user's login name
* @param password the user's password (obtained from user input, e.g., a web form)
* @return <code>true</code> if the supplied user password matches the
* stored password
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#validatePassword(java.lang.String,
* java.lang.String)
*/
public boolean validatePassword( String loginName, String password )
{
String hashedPassword = getHash( password );
try
{
UserProfile profile = findByLoginName( loginName );
String storedPassword = profile.getPassword();
if ( storedPassword.startsWith( SHA_PREFIX ) )
{
storedPassword = storedPassword.substring( SHA_PREFIX.length() );
}
return ( hashedPassword.equals( storedPassword ) );
}
catch( NoSuchPrincipalException e )
{
return false;
}
}
/**
* Private method that calculates the SHA-1 hash of a given
* <code>String</code>
* @param text the text to hash
* @return the result hash
*/
protected String getHash( String text )
{
String hash = null;
try
{
MessageDigest md = MessageDigest.getInstance( "SHA" );
md.update( text.getBytes() );
byte digestedBytes[] = md.digest();
hash = HexUtils.convert( digestedBytes );
}
catch( NoSuchAlgorithmException e )
{
log.error( "Error creating SHA password hash:" + e.getMessage() );
hash = text;
}
return hash;
}
} |
package com.chirag.RNMail;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.Callback;
import java.util.List;
import java.io.File;
/**
* NativeModule that allows JS to open emails sending apps chooser.
*/
public class RNMailModule extends ReactContextBaseJavaModule {
ReactApplicationContext reactContext;
public RNMailModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
}
@Override
public String getName() {
return "RNMail";
}
/**
* Converts a ReadableArray to a String array
*
* @param r the ReadableArray instance to convert
*
* @return array of strings
*/
private String[] readableArrayToStringArray(ReadableArray r) {
int length = r.size();
String[] stringArray = new String[length];
for (int keyIndex = 0; keyIndex < length; keyIndex++) {
stringArray[keyIndex] = r.getString(keyIndex);
}
return stringArray;
}
@ReactMethod
public void mail(ReadableMap options, Callback callback) {
Intent i = new Intent(Intent.ACTION_SENDTO);
i.setData(Uri.parse("mailto:"));
if (options.hasKey("subject") && !options.isNull("subject")) {
i.putExtra(Intent.EXTRA_SUBJECT, options.getString("subject"));
}
if (options.hasKey("body") && !options.isNull("body")) {
i.putExtra(Intent.EXTRA_TEXT, options.getString("body"));
}
if (options.hasKey("recipients") && !options.isNull("recipients")) {
ReadableArray recipients = options.getArray("recipients");
i.putExtra(Intent.EXTRA_EMAIL, readableArrayToStringArray(recipients));
}
if (options.hasKey("ccRecipients") && !options.isNull("ccRecipients")) {
ReadableArray ccRecipients = options.getArray("ccRecipients");
i.putExtra(Intent.EXTRA_CC, readableArrayToStringArray(ccRecipients));
}
if (options.hasKey("bccRecipients") && !options.isNull("bccRecipients")) {
ReadableArray bccRecipients = options.getArray("bccRecipients");
i.putExtra(Intent.EXTRA_BCC, readableArrayToStringArray(bccRecipients));
}
if (options.hasKey("attachment") && !options.isNull("attachment")) {
ReadableMap attachment = options.getMap("attachment");
if (attachment.hasKey("path") && !attachment.isNull("path")) {
String path = attachment.getString("path");
File file = new File(path);
Uri p = Uri.fromFile(file);
i.putExtra(Intent.EXTRA_STREAM, p);
}
}
PackageManager manager = reactContext.getPackageManager();
List<ResolveInfo> list = manager.queryIntentActivities(i, 0);
if (list == null || list.size() == 0) {
callback.invoke("not_available");
return;
}
Intent chooser = Intent.createChooser(i, "Send Mail");
chooser.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
reactContext.startActivity(chooser);
} catch (Exception ex) {
callback.invoke("error");
}
}
} |
package org.drooms.impl.util;
import java.io.File;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.drooms.impl.GameController;
/**
* Command-line interface for the application. It enforces two options on the
* command line:
*
* <dl>
* <dt>-p <file></dt>
* <dd>Provides a player configuration file, as described in
* {@link GameController#play(String, java.util.Properties, java.util.Properties)}
* .</dd>
* <dt>-g <file></dt>
* <dd>Provides a game configuration file, as described in
* {@link GameController#play(String, java.util.Properties, java.util.Properties)}
* .</dd>
* </dl>
*
* Not providing any of those or pointing to unreadable (non-existent) files
* should result in a help message being printed out and the application being
* terminated.
*/
public class CLI {
private static final CLI INSTANCE = new CLI();
/**
* Return the single instance of this class.
*
* @return The instance.
*/
public static CLI getInstance() {
return CLI.INSTANCE;
}
private final Options options = new Options();
private final Option players = new Option("p", "players", true,
"A path to the player config file.");
private final Option game = new Option("g", "game", true,
"A path to the game config file.");
private String errorMessage = null;
private boolean isError = false;
/**
* The constructor is hidden, as should be with the singleton pattern.
*/
private CLI() {
this.game.setRequired(true);
this.options.addOption(this.game);
this.players.setRequired(true);
this.options.addOption(this.players);
}
/**
* Prints a help message, describing the usage of the app from the
* command-line.
*/
public void printHelp() {
if (this.isError) {
System.out.println(this.errorMessage);
}
final HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("java -jar drooms.jar", this.options, true);
}
/**
* Process the command-line arguments.
*
* @param args
* The arguments.
* @return A pair of config files. Game config is the first, player config
* the second.
*/
public Pair<File, File> process(final String[] args) {
final CommandLineParser parser = new GnuParser();
try {
final CommandLine cli = parser.parse(this.options, args);
final File gameConfig = new File(cli.getOptionValue(this.game
.getOpt()));
if (!gameConfig.exists() || !gameConfig.canRead()) {
this.setError("Provided game config file cannot be read!");
return null;
}
final File playerConfig = new File(cli.getOptionValue(this.players
.getOpt()));
if (!playerConfig.exists() || !playerConfig.canRead()) {
this.setError("Provided player config file cannot be read!");
return null;
}
return ImmutablePair.of(gameConfig, playerConfig);
} catch (final ParseException e) {
this.setError(e.getMessage());
return null;
}
}
private boolean setError(final String message) {
if (!this.isError) {
this.isError = true;
this.errorMessage = message;
return true;
}
return false;
}
} |
package br.gov.servicos.v3.schema;
import com.github.slugify.Slugify;
import lombok.SneakyThrows;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
import java.util.stream.Stream;
@XmlType(name = "AreaDeInteresse")
@XmlEnum
public enum AreaDeInteresse {
@XmlEnumValue("Abastecimento")
VCGE1_ABASTECIMENTO("Abastecimento"),
@XmlEnumValue("Administração financeira")
VCGE1_ADMINISTRACAO_FINANCEIRA("Administração financeira"),
@XmlEnumValue("Agricultura orgânica")
VCGE1_AGRICULTURA_ORGANICA("Agricultura orgânica"),
@XmlEnumValue("Agropecuária")
VCGE1_AGROPECUARIA("Agropecuária"),
@XmlEnumValue("Alimento")
VCGE1_ALIMENTO("Alimento"),
@XmlEnumValue("Ambiente e saúde")
VCGE1_AMBIENTE_E_SAUDE("Ambiente e saúde"),
@XmlEnumValue("Comunicações")
VCGE1_COMUNICACOES("Comunicações"),
@XmlEnumValue("Comércio e Serviços")
VCGE1_COMERCIO_E_SERVICOS("Comércio e Serviços"),
@XmlEnumValue("Economia e Finanças")
VCGE1_ECONOMIA_E_FINANCAS("Economia e Finanças"),
@XmlEnumValue("Educação")
VCGE1_EDUCACAO("Educação"),
@XmlEnumValue("Educação básica")
VCGE1_EDUCACAO_BASICA("Educação básica"),
@XmlEnumValue("Educação superior")
VCGE1_EDUCACAO_SUPERIOR("Educação superior"),
@XmlEnumValue("Educação à distância")
VCGE1_EDUCACAO_A_DISTANCIA("Educação à distância"),
@XmlEnumValue("Emergências e Urgências")
VCGE1_EMERGENCIAS_E_URGENCIAS("Emergências e Urgências"),
@XmlEnumValue("Encargos financeiros")
VCGE1_ENCARGOS_FINANCEIROS("Encargos financeiros"),
@XmlEnumValue("Esporte e Lazer")
VCGE1_ESPORTE_E_LAZER("Esporte e Lazer"),
@XmlEnumValue("Finanças")
VCGE1_FINANCAS("Finanças"),
@XmlEnumValue("Habitação")
VCGE1_HABITACAO("Habitação"),
@XmlEnumValue("Humanização na saúde")
VCGE1_HUMANIZACAO_NA_SAUDE("Humanização na saúde"),
@XmlEnumValue("Indústria")
VCGE1_INDUSTRIA("Indústria"),
@XmlEnumValue("Meio ambiente")
VCGE1_MEIO_AMBIENTE("Meio ambiente"),
@XmlEnumValue("Pecuária")
VCGE1_PECUARIA("Pecuária"),
@XmlEnumValue("Pessoa")
VCGE1_PESSOA("Pessoa"),
@XmlEnumValue("Previdência Social")
VCGE1_PREVIDENCIA_SOCIAL("Previdência Social"),
@XmlEnumValue("Profissionais da educação")
VCGE1_PROFISSIONAIS_DA_EDUCACAO("Profissionais da educação"),
@XmlEnumValue("Proteção social")
VCGE1_PROTECAO_SOCIAL("Proteção social"),
@XmlEnumValue("Qualidade ambiental")
VCGE1_QUALIDADE_AMBIENTAL("Qualidade ambiental"),
@XmlEnumValue("Relações Internacionais")
VCGE1_RELACOES_INTERNACIONAIS("Relações Internacionais"),
@XmlEnumValue("Saúde")
VCGE1_SAUDE("Saúde"),
@XmlEnumValue("Saúde da criança")
VCGE1_SAUDE_DA_CRIANCA("Saúde da criança"),
@XmlEnumValue("Saúde da família")
VCGE1_SAUDE_DA_FAMILIA("Saúde da família"),
@XmlEnumValue("Saúde da mulher")
VCGE1_SAUDE_DA_MULHER("Saúde da mulher"),
@XmlEnumValue("Saúde do homem")
VCGE1_SAUDE_DO_HOMEM("Saúde do homem"),
@XmlEnumValue("Saúde do idoso")
VCGE1_SAUDE_DO_IDOSO("Saúde do idoso"),
@XmlEnumValue("Saúde dos portadores de deficiências")
VCGE1_SAUDE_DOS_PORTADORES_DE_DEFICIENCIAS("Saúde dos portadores de deficiências"),
@XmlEnumValue("Segurança e Ordem Pública")
VCGE1_SEGURANCA_E_ORDEM_PUBLICA("Segurança e Ordem Pública"),
@XmlEnumValue("Trabalho")
VCGE1_TRABALHO("Trabalho"),
@XmlEnumValue("Transportes")
VCGE1_TRANSPORTES("Transportes"),
@XmlEnumValue("Turismo")
VCGE1_TURISMO("Turismo"),
@XmlEnumValue("Urbanismo")
VCGE1_URBANISMO("Urbanismo"),
@XmlEnumValue("Águas")
VCGE1_AGUAS("Águas"),
@XmlEnumValue("Abastecimento")
VCGE2_ABASTECIMENTO("Abastecimento"),
@XmlEnumValue("Administração")
VCGE2_ADMINISTRACAO("Administração"),
@XmlEnumValue("Agropecuária")
VCGE2_AGROPECUARIA("Agropecuária"),
@XmlEnumValue("Assistência Hospitalar e Ambulatorial")
VCGE2_ASSISTENCIA_HOSPITALAR_E_AMBULATORIAL("Assistência Hospitalar e Ambulatorial"),
@XmlEnumValue("Assistência ao Idoso")
VCGE2_ASSISTENCIA_AO_IDOSO("Assistência ao Idoso"),
@XmlEnumValue("Assistência ao Portador de Deficiência")
VCGE2_ASSISTENCIA_AO_PORTADOR_DE_DEFICIENCIA("Assistência ao Portador de Deficiência"),
@XmlEnumValue("Assistência à Criança e ao Adolescente")
VCGE2_ASSISTENCIA_A_CRIANCA_E_AO_ADOLESCENTE("Assistência à Criança e ao Adolescente"),
@XmlEnumValue("Atendimento básico")
VCGE2_ATENDIMENTO_BASICO("Atendimento básico"),
@XmlEnumValue("Biodiversidade")
VCGE2_BIODIVERSIDADE("Biodiversidade"),
@XmlEnumValue("Cidadania")
VCGE2_CIDADANIA("Cidadania"),
@XmlEnumValue("Clima")
VCGE2_CLIMA("Clima"),
@XmlEnumValue("Combate a desigualdade")
VCGE2_COMBATE_A_DESIGUALDADE("Combate a desigualdade"),
@XmlEnumValue("Combate a epidemias")
VCGE2_COMBATE_A_EPIDEMIAS("Combate a epidemias"),
@XmlEnumValue("Combustíveis")
VCGE2_COMBUSTIVEIS("Combustíveis"),
@XmlEnumValue("Comercio externo")
VCGE2_COMERCIO_EXTERNO("Comercio externo"),
@XmlEnumValue("Compras governamentais")
VCGE2_COMPRAS_GOVERNAMENTAIS("Compras governamentais"),
@XmlEnumValue("Comunicações")
VCGE2_COMUNICACOES("Comunicações"),
@XmlEnumValue("Comunicações Postais")
VCGE2_COMUNICACOES_POSTAIS("Comunicações Postais"),
@XmlEnumValue("Comércio e Serviços")
VCGE2_COMERCIO_E_SERVICOS("Comércio e Serviços"),
@XmlEnumValue("Cooperação Internacional")
VCGE2_COOPERACAO_INTERNACIONAL("Cooperação Internacional"),
@XmlEnumValue("Cultura")
VCGE2_CULTURA("Cultura"),
@XmlEnumValue("Defesa Civil")
VCGE2_DEFESA_CIVIL("Defesa Civil"),
@XmlEnumValue("Defesa Nacional")
VCGE2_DEFESA_NACIONAL("Defesa Nacional"),
@XmlEnumValue("Defesa agropecuária")
VCGE2_DEFESA_AGROPECUARIA("Defesa agropecuária"),
@XmlEnumValue("Defesa do Consumidor")
VCGE2_DEFESA_DO_CONSUMIDOR("Defesa do Consumidor"),
@XmlEnumValue("Defesa militar")
VCGE2_DEFESA_MILITAR("Defesa militar"),
@XmlEnumValue("Difusão")
VCGE2_DIFUSAO("Difusão"),
@XmlEnumValue("Difusão Cultural")
VCGE2_DIFUSAO_CULTURAL("Difusão Cultural"),
@XmlEnumValue("Economia e Finanças")
VCGE2_ECONOMIA_E_FINANCAS("Economia e Finanças"),
@XmlEnumValue("Educação")
VCGE2_EDUCACAO("Educação"),
@XmlEnumValue("Educação básica")
VCGE2_EDUCACAO_BASICA("Educação básica"),
@XmlEnumValue("Educação profissionalizante")
VCGE2_EDUCACAO_PROFISSIONALIZANTE("Educação profissionalizante"),
@XmlEnumValue("Educação superior")
VCGE2_EDUCACAO_SUPERIOR("Educação superior"),
@XmlEnumValue("Empregabilidade")
VCGE2_EMPREGABILIDADE("Empregabilidade"),
@XmlEnumValue("Energia")
VCGE2_ENERGIA("Energia"),
@XmlEnumValue("Energia elétrica")
VCGE2_ENERGIA_ELETRICA("Energia elétrica"),
@XmlEnumValue("Esporte comunitário")
VCGE2_ESPORTE_COMUNITARIO("Esporte comunitário"),
@XmlEnumValue("Esporte e Lazer")
VCGE2_ESPORTE_E_LAZER("Esporte e Lazer"),
@XmlEnumValue("Esporte profissional")
VCGE2_ESPORTE_PROFISSIONAL("Esporte profissional"),
@XmlEnumValue("Fiscalização do Estado")
VCGE2_FISCALIZACAO_DO_ESTADO("Fiscalização do Estado"),
@XmlEnumValue("Fomento ao Trabalho")
VCGE2_FOMENTO_AO_TRABALHO("Fomento ao Trabalho"),
@XmlEnumValue("Habitação")
VCGE2_HABITACAO("Habitação"),
@XmlEnumValue("Habitação Rural")
VCGE2_HABITACAO_RURAL("Habitação Rural"),
@XmlEnumValue("Habitação Urbana")
VCGE2_HABITACAO_URBANA("Habitação Urbana"),
@XmlEnumValue("Indústria")
VCGE2_INDUSTRIA("Indústria"),
@XmlEnumValue("Infraestrutura Urbana")
VCGE2_INFRAESTRUTURA_URBANA("Infraestrutura Urbana"),
@XmlEnumValue("Lazer")
VCGE2_LAZER("Lazer"),
@XmlEnumValue("Medicamentos e aparelhos")
VCGE2_MEDICAMENTOS_E_APARELHOS("Medicamentos e aparelhos"),
@XmlEnumValue("Meio ambiente")
VCGE2_MEIO_AMBIENTE("Meio ambiente"),
@XmlEnumValue("Mineração")
VCGE2_MINERACAO("Mineração"),
@XmlEnumValue("Normalização e Qualidade")
VCGE2_NORMALIZACAO_E_QUALIDADE("Normalização e Qualidade"),
@XmlEnumValue("Operações de dívida pública")
VCGE2_OPERACOES_DE_DIVIDA_PUBLICA("Operações de dívida pública"),
@XmlEnumValue("Orçamento")
VCGE2_ORCAMENTO("Orçamento"),
@XmlEnumValue("Patrimônio")
VCGE2_PATRIMONIO("Patrimônio"),
@XmlEnumValue("Patrimônio Cultural")
VCGE2_PATRIMONIO_CULTURAL("Patrimônio Cultural"),
@XmlEnumValue("Pesquisa e Desenvolvimento")
VCGE2_PESQUISA_E_DESENVOLVIMENTO("Pesquisa e Desenvolvimento"),
@XmlEnumValue("Planejamento")
VCGE2_PLANEJAMENTO("Planejamento"),
@XmlEnumValue("Policiamento")
VCGE2_POLICIAMENTO("Policiamento"),
@XmlEnumValue("Politica econômica")
VCGE2_POLITICA_ECONOMICA("Politica econômica"),
@XmlEnumValue("Preservação e Conservação Ambiental")
VCGE2_PRESERVACAO_E_CONSERVACAO_AMBIENTAL("Preservação e Conservação Ambiental"),
@XmlEnumValue("Previdência Básica")
VCGE2_PREVIDENCIA_BASICA("Previdência Básica"),
@XmlEnumValue("Previdência Complementar")
VCGE2_PREVIDENCIA_COMPLEMENTAR("Previdência Complementar"),
@XmlEnumValue("Previdência Social")
VCGE2_PREVIDENCIA_SOCIAL("Previdência Social"),
@XmlEnumValue("Produção Industrial")
VCGE2_PRODUCAO_INDUSTRIAL("Produção Industrial"),
@XmlEnumValue("Produção agropecuária")
VCGE2_PRODUCAO_AGROPECUARIA("Produção agropecuária"),
@XmlEnumValue("Propriedade Industrial")
VCGE2_PROPRIEDADE_INDUSTRIAL("Propriedade Industrial"),
@XmlEnumValue("Proteção Social")
VCGE2_PROTECAO_SOCIAL("Proteção Social"),
@XmlEnumValue("Proteção e Benefícios ao Trabalhador")
VCGE2_PROTECAO_E_BENEFICIOS_AO_TRABALHADOR("Proteção e Benefícios ao Trabalhador"),
@XmlEnumValue("Recursos humanos")
VCGE2_RECURSOS_HUMANOS("Recursos humanos"),
@XmlEnumValue("Relações Diplomáticas")
VCGE2_RELACOES_DIPLOMATICAS("Relações Diplomáticas"),
@XmlEnumValue("Relações Internacionais")
VCGE2_RELACOES_INTERNACIONAIS("Relações Internacionais"),
@XmlEnumValue("Relações de Trabalho")
VCGE2_RELACOES_DE_TRABALHO("Relações de Trabalho"),
@XmlEnumValue("Saneamento")
VCGE2_SANEAMENTO("Saneamento"),
@XmlEnumValue("Saneamento Básico Rural")
VCGE2_SANEAMENTO_BASICO_RURAL("Saneamento Básico Rural"),
@XmlEnumValue("Saneamento Básico Urbano")
VCGE2_SANEAMENTO_BASICO_URBANO("Saneamento Básico Urbano"),
@XmlEnumValue("Saúde")
VCGE2_SAUDE("Saúde"),
@XmlEnumValue("Segurança e Ordem Pública")
VCGE2_SEGURANCA_E_ORDEM_PUBLICA("Segurança e Ordem Pública"),
@XmlEnumValue("Serviços Públicos")
VCGE2_SERVICOS_PUBLICOS("Serviços Públicos"),
@XmlEnumValue("Serviços Urbanos")
VCGE2_SERVICOS_URBANOS("Serviços Urbanos"),
@XmlEnumValue("Sistema Financeiro")
VCGE2_SISTEMA_FINANCEIRO("Sistema Financeiro"),
@XmlEnumValue("Telecomunicações")
VCGE2_TELECOMUNICACOES("Telecomunicações"),
@XmlEnumValue("Trabalho")
VCGE2_TRABALHO("Trabalho"),
@XmlEnumValue("Transporte Aéreo")
VCGE2_TRANSPORTE_AEREO("Transporte Aéreo"),
@XmlEnumValue("Transporte Ferroviário")
VCGE2_TRANSPORTE_FERROVIARIO("Transporte Ferroviário"),
@XmlEnumValue("Transporte Hidroviário")
VCGE2_TRANSPORTE_HIDROVIARIO("Transporte Hidroviário"),
@XmlEnumValue("Transporte Rodoviário")
VCGE2_TRANSPORTE_RODOVIARIO("Transporte Rodoviário"),
@XmlEnumValue("Transportes")
VCGE2_TRANSPORTES("Transportes"),
@XmlEnumValue("Turismo")
VCGE2_TURISMO("Turismo"),
@XmlEnumValue("Urbanismo")
VCGE2_URBANISMO("Urbanismo"),
@XmlEnumValue("Vigilância Sanitária")
VCGE2_VIGILANCIA_SANITARIA("Vigilância Sanitária"),
@XmlEnumValue("Água")
VCGE2_AGUA("Água");
private final String id;
private final String value;
@SneakyThrows
AreaDeInteresse(String v) {
id = new Slugify().slugify(v);
value = v;
}
public static AreaDeInteresse findById(String v) {
return Stream.of(values())
.filter(c -> c.getId().equals(v))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException(v));
}
public String getValue() {
return value;
}
public String getId() {
return id;
}
} |
package com.ecyrd.jspwiki.auth.user;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Properties;
import org.apache.catalina.util.HexUtils;
import org.apache.log4j.Logger;
import com.ecyrd.jspwiki.NoRequiredPropertyException;
import com.ecyrd.jspwiki.WikiEngine;
import com.ecyrd.jspwiki.auth.NoSuchPrincipalException;
import com.ecyrd.jspwiki.auth.WikiPrincipal;
import com.ecyrd.jspwiki.auth.WikiSecurityException;
/**
* Abstract UserDatabase class that provides convenience methods for finding
* profiles, building Principal collections and hashing passwords.
* @author Andrew R. Jaquith
* @since 2.3
*/
public abstract class AbstractUserDatabase implements UserDatabase
{
protected static final Logger log = Logger.getLogger( AbstractUserDatabase.class );
protected static final String SHA_PREFIX = "{SHA}";
protected static final String PROP_SHARED_WITH_CONTAINER = "jspwiki.userdatabase.isSharedWithContainer";
/**
* No-op method that in previous versions of JSPWiki was intended to
* atomically commit changes to the user database. Now, the {@link #rename(String, String)},
* {@link #save(UserProfile)} and {@link #deleteByLoginName(String)} methods
* are atomic themselves.
* @throws WikiSecurityException
* @deprecated there is no need to call this method because the save, rename and
* delete methods contain their own commit logic
*/
public synchronized void commit() throws WikiSecurityException
{ }
/**
* Looks up and returns the first {@link UserProfile}in the user database
* that whose login name, full name, or wiki name matches the supplied
* string. This method provides a "forgiving" search algorithm for resolving
* principal names when the exact profile attribute that supplied the name
* is unknown.
* @param index the login name, full name, or wiki name
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#find(java.lang.String)
*/
public UserProfile find( String index ) throws NoSuchPrincipalException
{
UserProfile profile = null;
// Try finding by full name
try
{
profile = findByFullName( index );
}
catch ( NoSuchPrincipalException e )
{
}
if ( profile != null )
{
return profile;
}
// Try finding by wiki name
try
{
profile = findByWikiName( index );
}
catch ( NoSuchPrincipalException e )
{
}
if ( profile != null )
{
return profile;
}
// Try finding by login name
try
{
profile = findByLoginName( index );
}
catch ( NoSuchPrincipalException e )
{
}
if ( profile != null )
{
return profile;
}
throw new NoSuchPrincipalException( "Not in database: " + index );
}
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#findByEmail(java.lang.String)
*/
public abstract UserProfile findByEmail( String index ) throws NoSuchPrincipalException;
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#findByFullName(java.lang.String)
*/
public abstract UserProfile findByFullName( String index ) throws NoSuchPrincipalException;
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#findByLoginName(java.lang.String)
*/
public abstract UserProfile findByLoginName( String index ) throws NoSuchPrincipalException;
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#findByWikiName(java.lang.String)
*/
public abstract UserProfile findByWikiName( String index ) throws NoSuchPrincipalException;
/**
* <p>Looks up the Principals representing a user from the user database. These
* are defined as a set of WikiPrincipals manufactured from the login name,
* full name, and wiki name. If the user database does not contain a user
* with the supplied identifier, throws a {@link NoSuchPrincipalException}.</p>
* <p>When this method creates WikiPrincipals, the Principal containing
* the user's full name is marked as containing the common name (see
* {@link com.ecyrd.jspwiki.auth.WikiPrincipal#WikiPrincipal(String, String)}).
* @param identifier the name of the principal to retrieve; this corresponds to
* value returned by the user profile's
* {@link UserProfile#getLoginName()}method.
* @return the array of Principals representing the user
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#getPrincipals(java.lang.String)
*/
public Principal[] getPrincipals( String identifier ) throws NoSuchPrincipalException
{
try
{
UserProfile profile = findByLoginName( identifier );
ArrayList principals = new ArrayList();
if ( profile.getLoginName() != null && profile.getLoginName().length() > 0 )
{
principals.add( new WikiPrincipal( profile.getLoginName(), WikiPrincipal.LOGIN_NAME ) );
}
if ( profile.getFullname() != null && profile.getFullname().length() > 0 )
{
principals.add( new WikiPrincipal( profile.getFullname(), WikiPrincipal.FULL_NAME ) );
}
if ( profile.getWikiName() != null && profile.getWikiName().length() > 0 )
{
principals.add( new WikiPrincipal( profile.getWikiName(), WikiPrincipal.WIKI_NAME ) );
}
return (Principal[]) principals.toArray( new Principal[principals.size()] );
}
catch( NoSuchPrincipalException e )
{
throw e;
}
}
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#initialize(com.ecyrd.jspwiki.WikiEngine, java.util.Properties)
*/
public abstract void initialize( WikiEngine engine, Properties props ) throws NoRequiredPropertyException;
/**
* Factory method that instantiates a new DefaultUserProfile.
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#newProfile()
*/
public UserProfile newProfile()
{
return new DefaultUserProfile();
}
/**
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#save(com.ecyrd.jspwiki.auth.user.UserProfile)
*/
public abstract void save( UserProfile profile ) throws WikiSecurityException;
/**
* Validates the password for a given user. If the user does not exist in
* the user database, this method always returns <code>false</code>. If
* the user exists, the supplied password is compared to the stored
* password. Note that if the stored password's value starts with
* <code>{SHA}</code>, the supplied password is hashed prior to the
* comparison.
* @param loginName the user's login name
* @param password the user's password (obtained from user input, e.g., a web form)
* @return <code>true</code> if the supplied user password matches the
* stored password
* @see com.ecyrd.jspwiki.auth.user.UserDatabase#validatePassword(java.lang.String,
* java.lang.String)
*/
public boolean validatePassword( String loginName, String password )
{
String hashedPassword = getHash( password );
try
{
UserProfile profile = findByLoginName( loginName );
String storedPassword = profile.getPassword();
if ( storedPassword.startsWith( SHA_PREFIX ) )
{
storedPassword = storedPassword.substring( SHA_PREFIX.length() );
}
return hashedPassword.equals( storedPassword );
}
catch( NoSuchPrincipalException e )
{
return false;
}
}
/**
* Private method that calculates the SHA-1 hash of a given
* <code>String</code>
* @param text the text to hash
* @return the result hash
*/
protected String getHash( String text )
{
String hash = null;
try
{
MessageDigest md = MessageDigest.getInstance( "SHA" );
md.update( text.getBytes("UTF-8") );
byte[] digestedBytes = md.digest();
hash = HexUtils.convert( digestedBytes );
}
catch( NoSuchAlgorithmException e )
{
log.error( "Error creating SHA password hash:" + e.getMessage() );
hash = text;
}
catch (UnsupportedEncodingException e)
{
log.fatal("UTF-8 not supported!?!");
}
return hash;
}
} |
package com.zmxv.RNSound;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.media.AudioManager;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.modules.core.ExceptionsManagerModule;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.io.IOException;
import android.util.Log;
public class RNSoundModule extends ReactContextBaseJavaModule implements AudioManager.OnAudioFocusChangeListener {
Map<Double, MediaPlayer> playerPool = new HashMap<>();
ReactApplicationContext context;
final static Object NULL = null;
String category;
Boolean mixWithOthers = true;
Double focusedPlayerKey;
Boolean wasPlayingBeforeFocusChange = false;
public RNSoundModule(ReactApplicationContext context) {
super(context);
this.context = context;
this.category = null;
}
private void setOnPlay(boolean isPlaying, final Double playerKey) {
final ReactContext reactContext = this.context;
WritableMap params = Arguments.createMap();
params.putBoolean("isPlaying", isPlaying);
params.putDouble("playerKey", playerKey);
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("onPlayChange", params);
}
@Override
public String getName() {
return "RNSound";
}
@ReactMethod
public void prepare(final String fileName, final Double key, final ReadableMap options, final Callback callback) {
MediaPlayer player = createMediaPlayer(fileName);
if (player == null) {
WritableMap e = Arguments.createMap();
e.putInt("code", -1);
e.putString("message", "resource not found");
callback.invoke(e, NULL);
return;
}
this.playerPool.put(key, player);
final RNSoundModule module = this;
if (module.category != null) {
Integer category = null;
switch (module.category) {
case "Playback":
category = AudioManager.STREAM_MUSIC;
break;
case "Ambient":
category = AudioManager.STREAM_NOTIFICATION;
break;
case "System":
category = AudioManager.STREAM_SYSTEM;
break;
case "Voice":
category = AudioManager.STREAM_VOICE_CALL;
break;
case "Ring":
category = AudioManager.STREAM_RING;
break;
case "Alarm":
category = AudioManager.STREAM_ALARM;
break;
default:
Log.e("RNSoundModule", String.format("Unrecognised category %s", module.category));
break;
}
if (category != null) {
player.setAudioStreamType(category);
}
}
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
boolean callbackWasCalled = false;
@Override
public synchronized void onPrepared(MediaPlayer mp) {
if (callbackWasCalled) return;
callbackWasCalled = true;
WritableMap props = Arguments.createMap();
props.putDouble("duration", mp.getDuration() * .001);
try {
callback.invoke(NULL, props);
} catch(RuntimeException runtimeException) {
// The callback was already invoked
Log.e("RNSoundModule", "Exception", runtimeException);
}
}
});
player.setOnErrorListener(new OnErrorListener() {
boolean callbackWasCalled = false;
@Override
public synchronized boolean onError(MediaPlayer mp, int what, int extra) {
if (callbackWasCalled) return true;
callbackWasCalled = true;
try {
WritableMap props = Arguments.createMap();
props.putInt("what", what);
props.putInt("extra", extra);
callback.invoke(props, NULL);
} catch(RuntimeException runtimeException) {
// The callback was already invoked
Log.e("RNSoundModule", "Exception", runtimeException);
}
return true;
}
});
try {
if(options.hasKey("loadSync") && options.getBoolean("loadSync")) {
player.prepare();
} else {
player.prepareAsync();
}
} catch (Exception ignored) {
// When loading files from a file, we useMediaPlayer.create, which actually
// prepares the audio for us already. So we catch and ignore this error
Log.e("RNSoundModule", "Exception", ignored);
}
}
protected MediaPlayer createMediaPlayer(final String fileName) {
int res = this.context.getResources().getIdentifier(fileName, "raw", this.context.getPackageName());
MediaPlayer mediaPlayer = new MediaPlayer();
if (res != 0) {
try {
AssetFileDescriptor afd = context.getResources().openRawResourceFd(res);
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
afd.close();
} catch (IOException e) {
Log.e("RNSoundModule", "Exception", e);
return null;
}
return mediaPlayer;
}
if (fileName.startsWith("http:
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
Log.i("RNSoundModule", fileName);
try {
mediaPlayer.setDataSource(fileName);
} catch(IOException e) {
Log.e("RNSoundModule", "Exception", e);
return null;
}
return mediaPlayer;
}
if (fileName.startsWith("asset:/")){
try {
AssetFileDescriptor descriptor = this.context.getAssets().openFd(fileName.replace("asset:/", ""));
mediaPlayer.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
return mediaPlayer;
} catch(IOException e) {
Log.e("RNSoundModule", "Exception", e);
return null;
}
}
File file = new File(fileName);
if (file.exists()) {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
Log.i("RNSoundModule", fileName);
try {
mediaPlayer.setDataSource(fileName);
} catch(IOException e) {
Log.e("RNSoundModule", "Exception", e);
return null;
}
return mediaPlayer;
}
return null;
}
@ReactMethod
public void play(final Double key, final Callback callback) {
MediaPlayer player = this.playerPool.get(key);
if (player == null) {
setOnPlay(false, key);
if (callback != null) {
callback.invoke(false);
}
return;
}
if (player.isPlaying()) {
return;
}
// Request audio focus in Android system
if (!this.mixWithOthers) {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
this.focusedPlayerKey = key;
}
player.setOnCompletionListener(new OnCompletionListener() {
boolean callbackWasCalled = false;
@Override
public synchronized void onCompletion(MediaPlayer mp) {
if (!mp.isLooping()) {
setOnPlay(false, key);
if (callbackWasCalled) return;
callbackWasCalled = true;
try {
callback.invoke(true);
} catch (Exception e) {
}
}
}
});
player.setOnErrorListener(new OnErrorListener() {
boolean callbackWasCalled = false;
@Override
public synchronized boolean onError(MediaPlayer mp, int what, int extra) {
setOnPlay(false, key);
if (callbackWasCalled) return true;
callbackWasCalled = true;
try {
callback.invoke(true);
} catch (Exception e) {
}
return true;
}
});
player.start();
setOnPlay(true, key);
}
@ReactMethod
public void pause(final Double key, final Callback callback) {
MediaPlayer player = this.playerPool.get(key);
if (player != null && player.isPlaying()) {
player.pause();
}
if (callback != null) {
callback.invoke();
}
}
@ReactMethod
public void stop(final Double key, final Callback callback) {
MediaPlayer player = this.playerPool.get(key);
if (player != null && player.isPlaying()) {
player.pause();
player.seekTo(0);
}
// Release audio focus in Android system
if (!this.mixWithOthers && key == this.focusedPlayerKey) {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.abandonAudioFocus(this);
}
callback.invoke();
}
@ReactMethod
public void reset(final Double key) {
MediaPlayer player = this.playerPool.get(key);
if (player != null) {
player.reset();
}
}
@ReactMethod
public void release(final Double key) {
MediaPlayer player = this.playerPool.get(key);
if (player != null) {
player.reset();
player.release();
this.playerPool.remove(key);
// Release audio focus in Android system
if (!this.mixWithOthers && key == this.focusedPlayerKey) {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.abandonAudioFocus(this);
}
}
}
@Override
public void onCatalystInstanceDestroy() {
java.util.Iterator it = this.playerPool.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
MediaPlayer player = (MediaPlayer)entry.getValue();
if (player != null) {
player.reset();
player.release();
}
it.remove();
}
}
@ReactMethod
public void setVolume(final Double key, final Float left, final Float right) {
MediaPlayer player = this.playerPool.get(key);
if (player != null) {
player.setVolume(left, right);
}
}
@ReactMethod
public void getSystemVolume(final Callback callback) {
try {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
callback.invoke((float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) / audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
} catch (Exception error) {
WritableMap e = Arguments.createMap();
e.putInt("code", -1);
e.putString("message", error.getMessage());
callback.invoke(e);
}
}
@ReactMethod
public void setSystemVolume(final Float value) {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
int volume = Math.round(audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC) * value);
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
}
@ReactMethod
public void setLooping(final Double key, final Boolean looping) {
MediaPlayer player = this.playerPool.get(key);
if (player != null) {
player.setLooping(looping);
}
}
@ReactMethod
public void setSpeed(final Double key, final Float speed) {
if (android.os.Build.VERSION.SDK_INT < 23) {
Log.w("RNSoundModule", "setSpeed ignored due to sdk limit");
return;
}
MediaPlayer player = this.playerPool.get(key);
if (player != null) {
player.setPlaybackParams(player.getPlaybackParams().setSpeed(speed));
}
}
@ReactMethod
public void setPitch(final Double key, final Float pitch) {
if (android.os.Build.VERSION.SDK_INT < 23) {
Log.w("RNSoundModule", "setPitch ignored due to sdk limit");
return;
}
MediaPlayer player = this.playerPool.get(key);
if (player != null) {
player.setPlaybackParams(player.getPlaybackParams().setPitch(pitch));
}
}
@ReactMethod
public void setCurrentTime(final Double key, final Float sec) {
MediaPlayer player = this.playerPool.get(key);
if (player != null) {
player.seekTo((int)Math.round(sec * 1000));
}
}
@ReactMethod
public void getCurrentTime(final Double key, final Callback callback) {
MediaPlayer player = this.playerPool.get(key);
if (player == null) {
callback.invoke(-1, false);
return;
}
callback.invoke(player.getCurrentPosition() * .001, player.isPlaying());
}
//turn speaker on
@ReactMethod
public void setSpeakerphoneOn(final Double key, final Boolean speaker) {
MediaPlayer player = this.playerPool.get(key);
if (player != null) {
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
AudioManager audioManager = (AudioManager)this.context.getSystemService(this.context.AUDIO_SERVICE);
if(speaker){
audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
}else{
audioManager.setMode(AudioManager.MODE_NORMAL);
}
audioManager.setSpeakerphoneOn(speaker);
}
}
@ReactMethod
public void setCategory(final String category, final Boolean mixWithOthers) {
this.category = category;
this.mixWithOthers = mixWithOthers;
}
@Override
public void onAudioFocusChange(int focusChange) {
if (!this.mixWithOthers) {
MediaPlayer player = this.playerPool.get(this.focusedPlayerKey);
if (player != null) {
if (focusChange <= 0) {
this.wasPlayingBeforeFocusChange = player.isPlaying();
if (this.wasPlayingBeforeFocusChange) {
this.pause(this.focusedPlayerKey, null);
}
} else {
if (this.wasPlayingBeforeFocusChange) {
this.play(this.focusedPlayerKey, null);
this.wasPlayingBeforeFocusChange = false;
}
}
}
}
}
@ReactMethod
public void enable(final Boolean enabled) {
// no op
}
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put("IsAndroid", true);
return constants;
}
@ReactMethod
public void addListener(String eventName) {
// Keep: Required for RN built in Event Emitter Calls.
}
@ReactMethod
public void removeListeners(Integer count) {
// Keep: Required for RN built in Event Emitter Calls.
}
} |
package org.askerov.dynamicgrid;
import android.animation.*;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListAdapter;
import java.util.*;
public class DynamicGridView extends GridView {
private static final int INVALID_ID = -1;
private static final int MOVE_DURATION = 300;
private static final int SMOOTH_SCROLL_AMOUNT_AT_EDGE = 8;
private BitmapDrawable mHoverCell;
private Rect mHoverCellCurrentBounds;
private Rect mHoverCellOriginalBounds;
private int mTotalOffsetY = 0;
private int mTotalOffsetX = 0;
private int mDownX = -1;
private int mDownY = -1;
private int mLastEventY = -1;
private int mLastEventX = -1;
//used to distinguish straight line and diagonal switching
private int mOverlapIfSwitchStraightLine;
private List<Long> idList = new ArrayList<Long>();
private long mMobileItemId = INVALID_ID;
private boolean mCellIsMobile = false;
private int mActivePointerId = INVALID_ID;
private boolean mIsMobileScrolling;
private int mSmoothScrollAmountAtEdge = 0;
private boolean mIsWaitingForScrollFinish = false;
private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE;
private boolean mIsEditMode = false;
private List<ObjectAnimator> mWobbleAnimators = new LinkedList<ObjectAnimator>();
private boolean mHoverAnimation;
private boolean mReorderAnimation;
private boolean mWobbleInEditMode = true;
private boolean mIsEditModeEnabled = true;
private OnDropListener mDropListener;
private OnDragListener mDragListener;
private OnEditModeChangeListener mEditModeChangeListener;
private OnItemClickListener mUserItemClickListener;
private OnItemClickListener mLocalItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (!isEditMode() && isEnabled() && mUserItemClickListener != null) {
mUserItemClickListener.onItemClick(parent, view, position, id);
}
}
};
private boolean mUndoSupportEnabled;
private Stack<DynamicGridModification> mModificationStack;
private DynamicGridModification mCurrentModification;
private OnSelectedItemBitmapCreationListener mSelectedItemBitmapCreationListener;
private View mMobileView;
public DynamicGridView(Context context) {
super(context);
init(context);
}
public DynamicGridView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public DynamicGridView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
public void setOnDropListener(OnDropListener dropListener) {
this.mDropListener = dropListener;
}
public void setOnDragListener(OnDragListener dragListener) {
this.mDragListener = dragListener;
}
/**
* Start edit mode without starting drag;
*/
public void startEditMode() {
startEditMode(-1);
}
/**
* Start edit mode with position. Useful for start edit mode in
* {@link android.widget.AdapterView.OnItemClickListener}
* or {@link android.widget.AdapterView.OnItemLongClickListener}
*/
public void startEditMode(int position) {
if (!mIsEditModeEnabled)
return;
requestDisallowInterceptTouchEvent(true);
if (isPostHoneycomb() && mWobbleInEditMode)
startWobbleAnimation();
if (position != -1 && mDragListener != null) {
startDragAtPosition(position);
}
mIsEditMode = true;
if (mEditModeChangeListener != null)
mEditModeChangeListener.onEditModeChanged(true);
}
public void stopEditMode() {
mIsEditMode = false;
requestDisallowInterceptTouchEvent(false);
if (isPostHoneycomb() && mWobbleInEditMode)
stopWobble(true);
if (mEditModeChangeListener != null)
mEditModeChangeListener.onEditModeChanged(false);
}
public boolean isEditModeEnabled() {
return mIsEditModeEnabled;
}
public void setEditModeEnabled(boolean enabled) {
this.mIsEditModeEnabled = enabled;
}
public void setOnEditModeChangeListener(OnEditModeChangeListener editModeChangeListener) {
this.mEditModeChangeListener = editModeChangeListener;
}
public boolean isEditMode() {
return mIsEditMode;
}
public boolean isWobbleInEditMode() {
return mWobbleInEditMode;
}
public void setWobbleInEditMode(boolean wobbleInEditMode) {
this.mWobbleInEditMode = wobbleInEditMode;
}
@Override
public void setOnItemClickListener(OnItemClickListener listener) {
this.mUserItemClickListener = listener;
super.setOnItemClickListener(mLocalItemClickListener);
}
public boolean isUndoSupportEnabled() {
return mUndoSupportEnabled;
}
public void setUndoSupportEnabled(boolean undoSupportEnabled) {
if (this.mUndoSupportEnabled != undoSupportEnabled) {
if (undoSupportEnabled) {
this.mModificationStack = new Stack<DynamicGridModification>();
} else {
this.mModificationStack = null;
}
}
this.mUndoSupportEnabled = undoSupportEnabled;
}
public void undoLastModification() {
if (mUndoSupportEnabled) {
if (mModificationStack != null && !mModificationStack.isEmpty()) {
DynamicGridModification modification = mModificationStack.pop();
undoModification(modification);
}
}
}
public void undoAllModifications() {
if (mUndoSupportEnabled) {
if (mModificationStack != null && !mModificationStack.isEmpty()) {
while (!mModificationStack.isEmpty()) {
DynamicGridModification modification = mModificationStack.pop();
undoModification(modification);
}
}
}
}
public boolean hasModificationHistory() {
if (mUndoSupportEnabled) {
if (mModificationStack != null && !mModificationStack.isEmpty()) {
return true;
}
}
return false;
}
public void clearModificationHistory() {
mModificationStack.clear();
}
public void setOnSelectedItemBitmapCreationListener(OnSelectedItemBitmapCreationListener selectedItemBitmapCreationListener) {
this.mSelectedItemBitmapCreationListener = selectedItemBitmapCreationListener;
}
private void undoModification(DynamicGridModification modification) {
for (Pair<Integer, Integer> transition : modification.getTransitions()) {
reorderElements(transition.second, transition.first);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void startWobbleAnimation() {
for (int i = 0; i < getChildCount(); i++) {
View v = getChildAt(i);
if (v != null && Boolean.TRUE != v.getTag(R.id.dgv_wobble_tag)) {
if (i % 2 == 0)
animateWobble(v);
else
animateWobbleInverse(v);
v.setTag(R.id.dgv_wobble_tag, true);
}
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void stopWobble(boolean resetRotation) {
for (Animator wobbleAnimator : mWobbleAnimators) {
wobbleAnimator.cancel();
}
mWobbleAnimators.clear();
for (int i = 0; i < getChildCount(); i++) {
View v = getChildAt(i);
if (v != null) {
if (resetRotation) v.setRotation(0);
v.setTag(R.id.dgv_wobble_tag, false);
}
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void restartWobble() {
stopWobble(false);
startWobbleAnimation();
}
public void init(Context context) {
setOnScrollListener(mScrollListener);
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
mSmoothScrollAmountAtEdge = (int) (SMOOTH_SCROLL_AMOUNT_AT_EDGE * metrics.density + 0.5f);
mOverlapIfSwitchStraightLine = getResources().getDimensionPixelSize(R.dimen.dgv_overlap_if_switch_straight_line);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void animateWobble(View v) {
ObjectAnimator animator = createBaseWobble(v);
animator.setFloatValues(-2, 2);
animator.start();
mWobbleAnimators.add(animator);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void animateWobbleInverse(View v) {
ObjectAnimator animator = createBaseWobble(v);
animator.setFloatValues(2, -2);
animator.start();
mWobbleAnimators.add(animator);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private ObjectAnimator createBaseWobble(final View v) {
if(!isPreL())
v.setLayerType(LAYER_TYPE_SOFTWARE, null);
ObjectAnimator animator = new ObjectAnimator();
animator.setDuration(180);
animator.setRepeatMode(ValueAnimator.REVERSE);
animator.setRepeatCount(ValueAnimator.INFINITE);
animator.setPropertyName("rotation");
animator.setTarget(v);
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
v.setLayerType(LAYER_TYPE_NONE, null);
}
});
return animator;
}
private void reorderElements(int originalPosition, int targetPosition) {
if (mDragListener != null)
mDragListener.onDragPositionsChanged(originalPosition, targetPosition);
getAdapterInterface().reorderItems(originalPosition, targetPosition);
}
private int getColumnCount() {
return getAdapterInterface().getColumnCount();
}
private DynamicGridAdapterInterface getAdapterInterface() {
return ((DynamicGridAdapterInterface) getAdapter());
}
/**
* Creates the hover cell with the appropriate bitmap and of appropriate
* size. The hover cell's BitmapDrawable is drawn on top of the bitmap every
* single time an invalidate call is made.
*/
private BitmapDrawable getAndAddHoverView(View v) {
int w = v.getWidth();
int h = v.getHeight();
int top = v.getTop();
int left = v.getLeft();
Bitmap b = getBitmapFromView(v);
BitmapDrawable drawable = new BitmapDrawable(getResources(), b);
mHoverCellOriginalBounds = new Rect(left, top, left + w, top + h);
mHoverCellCurrentBounds = new Rect(mHoverCellOriginalBounds);
drawable.setBounds(mHoverCellCurrentBounds);
return drawable;
}
/**
* Returns a bitmap showing a screenshot of the view passed in.
*/
private Bitmap getBitmapFromView(View v) {
Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
v.draw(canvas);
return bitmap;
}
private void updateNeighborViewsForId(long itemId) {
idList.clear();
int draggedPos = getPositionForID(itemId);
for (int pos = getFirstVisiblePosition(); pos <= getLastVisiblePosition(); pos++) {
if (draggedPos != pos) {
idList.add(getId(pos));
}
}
}
/**
* Retrieves the position in the grid corresponding to <code>itemId</code>
*/
public int getPositionForID(long itemId) {
View v = getViewForId(itemId);
if (v == null) {
return -1;
} else {
return getPositionForView(v);
}
}
public View getViewForId(long itemId) {
int firstVisiblePosition = getFirstVisiblePosition();
ListAdapter adapter = getAdapter();
for (int i = 0; i < getChildCount(); i++) {
View v = getChildAt(i);
int position = firstVisiblePosition + i;
long id = adapter.getItemId(position);
if (id == itemId) {
return v;
}
}
return null;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mDownX = (int) event.getX();
mDownY = (int) event.getY();
mActivePointerId = event.getPointerId(0);
if (mIsEditMode && isEnabled()) {
layoutChildren();
int position = pointToPosition(mDownX, mDownY);
startDragAtPosition(position);
} else if (!isEnabled()) {
return false;
}
break;
case MotionEvent.ACTION_MOVE:
if (mActivePointerId == INVALID_ID) {
break;
}
int pointerIndex = event.findPointerIndex(mActivePointerId);
mLastEventY = (int) event.getY(pointerIndex);
mLastEventX = (int) event.getX(pointerIndex);
int deltaY = mLastEventY - mDownY;
int deltaX = mLastEventX - mDownX;
if (mCellIsMobile) {
mHoverCellCurrentBounds.offsetTo(mHoverCellOriginalBounds.left + deltaX + mTotalOffsetX,
mHoverCellOriginalBounds.top + deltaY + mTotalOffsetY);
mHoverCell.setBounds(mHoverCellCurrentBounds);
invalidate();
handleCellSwitch();
mIsMobileScrolling = false;
handleMobileCellScroll();
return false;
}
break;
case MotionEvent.ACTION_UP:
touchEventsEnded();
if (mUndoSupportEnabled) {
if (mCurrentModification != null && !mCurrentModification.getTransitions().isEmpty()) {
mModificationStack.push(mCurrentModification);
mCurrentModification = new DynamicGridModification();
}
}
if (mHoverCell != null) {
if (mDropListener != null) {
mDropListener.onActionDrop();
}
}
break;
case MotionEvent.ACTION_CANCEL:
touchEventsCancelled();
if (mHoverCell != null) {
if (mDropListener != null) {
mDropListener.onActionDrop();
}
}
break;
case MotionEvent.ACTION_POINTER_UP:
/* If a multitouch event took place and the original touch dictating
* the movement of the hover cell has ended, then the dragging event
* ends and the hover cell is animated to its corresponding position
* in the listview. */
pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = event.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
touchEventsEnded();
}
break;
default:
break;
}
return super.onTouchEvent(event);
}
private void startDragAtPosition(int position) {
mTotalOffsetY = 0;
mTotalOffsetX = 0;
int itemNum = position - getFirstVisiblePosition();
View selectedView = getChildAt(itemNum);
if (selectedView != null) {
mMobileItemId = getAdapter().getItemId(position);
if (mSelectedItemBitmapCreationListener != null)
mSelectedItemBitmapCreationListener.onPreSelectedItemBitmapCreation(selectedView, position, mMobileItemId);
mHoverCell = getAndAddHoverView(selectedView);
if (mSelectedItemBitmapCreationListener != null)
mSelectedItemBitmapCreationListener.onPostSelectedItemBitmapCreation(selectedView, position, mMobileItemId);
if (isPostHoneycomb())
selectedView.setVisibility(View.INVISIBLE);
mCellIsMobile = true;
updateNeighborViewsForId(mMobileItemId);
if (mDragListener != null) {
mDragListener.onDragStarted(position);
}
}
}
private void handleMobileCellScroll() {
mIsMobileScrolling = handleMobileCellScroll(mHoverCellCurrentBounds);
}
public boolean handleMobileCellScroll(Rect r) {
int offset = computeVerticalScrollOffset();
int height = getHeight();
int extent = computeVerticalScrollExtent();
int range = computeVerticalScrollRange();
int hoverViewTop = r.top;
int hoverHeight = r.height();
if (hoverViewTop <= 0 && offset > 0) {
smoothScrollBy(-mSmoothScrollAmountAtEdge, 0);
return true;
}
if (hoverViewTop + hoverHeight >= height && (offset + extent) < range) {
smoothScrollBy(mSmoothScrollAmountAtEdge, 0);
return true;
}
return false;
}
@Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
}
private void touchEventsEnded() {
final View mobileView = getViewForId(mMobileItemId);
if (mobileView != null && (mCellIsMobile || mIsWaitingForScrollFinish)) {
mCellIsMobile = false;
mIsWaitingForScrollFinish = false;
mIsMobileScrolling = false;
mActivePointerId = INVALID_ID;
// If the autoscroller has not completed scrolling, we need to wait for it to
// finish in order to determine the final location of where the hover cell
// should be animated to.
if (mScrollState != OnScrollListener.SCROLL_STATE_IDLE) {
mIsWaitingForScrollFinish = true;
return;
}
mHoverCellCurrentBounds.offsetTo(mobileView.getLeft(), mobileView.getTop());
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB) {
animateBounds(mobileView);
} else {
mHoverCell.setBounds(mHoverCellCurrentBounds);
invalidate();
reset(mobileView);
}
} else {
touchEventsCancelled();
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void animateBounds(final View mobileView) {
TypeEvaluator<Rect> sBoundEvaluator = new TypeEvaluator<Rect>() {
public Rect evaluate(float fraction, Rect startValue, Rect endValue) {
return new Rect(interpolate(startValue.left, endValue.left, fraction),
interpolate(startValue.top, endValue.top, fraction),
interpolate(startValue.right, endValue.right, fraction),
interpolate(startValue.bottom, endValue.bottom, fraction));
}
public int interpolate(int start, int end, float fraction) {
return (int) (start + fraction * (end - start));
}
};
ObjectAnimator hoverViewAnimator = ObjectAnimator.ofObject(mHoverCell, "bounds",
sBoundEvaluator, mHoverCellCurrentBounds);
hoverViewAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
invalidate();
}
});
hoverViewAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
mHoverAnimation = true;
updateEnableState();
}
@Override
public void onAnimationEnd(Animator animation) {
mHoverAnimation = false;
updateEnableState();
reset(mobileView);
}
});
hoverViewAnimator.start();
}
private void reset(View mobileView) {
idList.clear();
mMobileItemId = INVALID_ID;
mobileView.setVisibility(View.VISIBLE);
mHoverCell = null;
if (!mIsEditMode && isPostHoneycomb() && mWobbleInEditMode && isPreL())
stopWobble(true);
if (mIsEditMode && isPostHoneycomb() && mWobbleInEditMode && isPreL())
restartWobble();
invalidate();
}
private void updateEnableState() {
setEnabled(!mHoverAnimation && !mReorderAnimation);
}
/**
* Seems that GridView before HONEYCOMB not support stable id in proper way.
* That cause bugs on view recycle if we will animate or change visibility state for items.
*
* @return
*/
private boolean isPostHoneycomb() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
}
/**
* The GridView from Android L requires some different setVisibility() logic
* when switching cells. Unfortunately, both 4.4W and the pre-release L
* report 20 for the SDK_INT, but we want to return true for 4.4W and false
* for Android L. So, we check the release name for "L" if we see SDK 20.
* Hopefully, Android L will actually be SDK 21 or later when it ships.
*
* @return
*/
public static boolean isPreL() {
final int KITKAT_WATCH = 20;
return (Build.VERSION.SDK_INT < KITKAT_WATCH) ||
((Build.VERSION.SDK_INT == KITKAT_WATCH) && !"L".equals(Build.VERSION.RELEASE));
}
private void touchEventsCancelled() {
View mobileView = getViewForId(mMobileItemId);
if (mCellIsMobile) {
reset(mobileView);
}
mCellIsMobile = false;
mIsMobileScrolling = false;
mActivePointerId = INVALID_ID;
}
private void handleCellSwitch() {
final int deltaY = mLastEventY - mDownY;
final int deltaX = mLastEventX - mDownX;
final int deltaYTotal = mHoverCellOriginalBounds.centerY() + mTotalOffsetY + deltaY;
final int deltaXTotal = mHoverCellOriginalBounds.centerX() + mTotalOffsetX + deltaX;
mMobileView = getViewForId(mMobileItemId);
View targetView = null;
float vX = 0;
float vY = 0;
Point mobileColumnRowPair = getColumnAndRowForView(mMobileView);
for (Long id : idList) {
View view = getViewForId(id);
if (view != null) {
Point targetColumnRowPair = getColumnAndRowForView(view);
if ((aboveRight(targetColumnRowPair, mobileColumnRowPair)
&& deltaYTotal < view.getBottom() && deltaXTotal > view.getLeft()
|| aboveLeft(targetColumnRowPair, mobileColumnRowPair)
&& deltaYTotal < view.getBottom() && deltaXTotal < view.getRight()
|| belowRight(targetColumnRowPair, mobileColumnRowPair)
&& deltaYTotal > view.getTop() && deltaXTotal > view.getLeft()
|| belowLeft(targetColumnRowPair, mobileColumnRowPair)
&& deltaYTotal > view.getTop() && deltaXTotal < view.getRight()
|| above(targetColumnRowPair, mobileColumnRowPair)
&& deltaYTotal < view.getBottom() - mOverlapIfSwitchStraightLine
|| below(targetColumnRowPair, mobileColumnRowPair)
&& deltaYTotal > view.getTop() + mOverlapIfSwitchStraightLine
|| right(targetColumnRowPair, mobileColumnRowPair)
&& deltaXTotal > view.getLeft() + mOverlapIfSwitchStraightLine
|| left(targetColumnRowPair, mobileColumnRowPair)
&& deltaXTotal < view.getRight() - mOverlapIfSwitchStraightLine)) {
float xDiff = Math.abs(DynamicGridUtils.getViewX(view) - DynamicGridUtils.getViewX(mMobileView));
float yDiff = Math.abs(DynamicGridUtils.getViewY(view) - DynamicGridUtils.getViewY(mMobileView));
if (xDiff >= vX && yDiff >= vY) {
vX = xDiff;
vY = yDiff;
targetView = view;
}
}
}
}
if (targetView != null) {
final int originalPosition = getPositionForView(mMobileView);
int targetPosition = getPositionForView(targetView);
if (targetPosition == INVALID_POSITION) {
updateNeighborViewsForId(mMobileItemId);
return;
}
reorderElements(originalPosition, targetPosition);
if (mUndoSupportEnabled) {
mCurrentModification.addTransition(originalPosition, targetPosition);
}
mDownY = mLastEventY;
mDownX = mLastEventX;
SwitchCellAnimator switchCellAnimator;
if(isPostHoneycomb() && isPreL()) //Between Android 3.0 and Android L
switchCellAnimator = new KitKatSwitchCellAnimator(deltaX, deltaY);
else if(isPreL()) //Before Android 3.0
switchCellAnimator = new PreHoneycombCellAnimator(deltaX, deltaY);
else //Android L
switchCellAnimator = new LSwitchCellAnimator(deltaX, deltaY);
updateNeighborViewsForId(mMobileItemId);
switchCellAnimator.animateSwitchCell(originalPosition, targetPosition);
}
}
private interface SwitchCellAnimator {
void animateSwitchCell(final int originalPosition, final int targetPosition);
}
private class PreHoneycombCellAnimator implements SwitchCellAnimator {
private int mDeltaY;
private int mDeltaX;
public PreHoneycombCellAnimator(int deltaX, int deltaY) {
mDeltaX = deltaX;
mDeltaY = deltaY;
}
@Override
public void animateSwitchCell(int originalPosition, int targetPosition) {
mTotalOffsetY += mDeltaY;
mTotalOffsetX += mDeltaX;
}
}
/**
* A {@link org.askerov.dynamicgrid.DynamicGridView.SwitchCellAnimator} for versions KitKat and below.
*/
private class KitKatSwitchCellAnimator implements SwitchCellAnimator {
private int mDeltaY;
private int mDeltaX;
public KitKatSwitchCellAnimator(int deltaX, int deltaY) {
mDeltaX = deltaX;
mDeltaY = deltaY;
}
@Override
public void animateSwitchCell(final int originalPosition, final int targetPosition) {
assert mMobileView != null;
getViewTreeObserver().addOnPreDrawListener(new AnimateSwitchViewOnPreDrawListener(mMobileView, originalPosition, targetPosition));
mMobileView = getViewForId(mMobileItemId);
}
private class AnimateSwitchViewOnPreDrawListener implements ViewTreeObserver.OnPreDrawListener {
private final View mPreviousMobileView;
private final int mOriginalPosition;
private final int mTargetPosition;
AnimateSwitchViewOnPreDrawListener(final View previousMobileView, final int originalPosition, final int targetPosition) {
mPreviousMobileView = previousMobileView;
mOriginalPosition = originalPosition;
mTargetPosition = targetPosition;
}
@Override
public boolean onPreDraw() {
getViewTreeObserver().removeOnPreDrawListener(this);
mTotalOffsetY += mDeltaY;
mTotalOffsetX += mDeltaX;
animateReorder(mOriginalPosition, mTargetPosition);
mPreviousMobileView.setVisibility(View.VISIBLE);
if (mMobileView != null) {
mMobileView.setVisibility(View.INVISIBLE);
}
return true;
}
}
}
/**
* A {@link org.askerov.dynamicgrid.DynamicGridView.SwitchCellAnimator} for versions L and above.
*/
private class LSwitchCellAnimator implements SwitchCellAnimator {
private int mDeltaY;
private int mDeltaX;
public LSwitchCellAnimator(int deltaX, int deltaY) {
mDeltaX = deltaX;
mDeltaY = deltaY;
}
@Override
public void animateSwitchCell(final int originalPosition, final int targetPosition) {
getViewTreeObserver().addOnPreDrawListener(new AnimateSwitchViewOnPreDrawListener(originalPosition, targetPosition));
}
private class AnimateSwitchViewOnPreDrawListener implements ViewTreeObserver.OnPreDrawListener {
private final int mOriginalPosition;
private final int mTargetPosition;
AnimateSwitchViewOnPreDrawListener(final int originalPosition, final int targetPosition) {
mOriginalPosition = originalPosition;
mTargetPosition = targetPosition;
}
@Override
public boolean onPreDraw() {
getViewTreeObserver().removeOnPreDrawListener(this);
mTotalOffsetY += mDeltaY;
mTotalOffsetX += mDeltaX;
animateReorder(mOriginalPosition, mTargetPosition);
assert mMobileView != null;
mMobileView.setVisibility(View.VISIBLE);
mMobileView = getViewForId(mMobileItemId);
assert mMobileView != null;
mMobileView.setVisibility(View.INVISIBLE);
return true;
}
}
}
private boolean belowLeft(Point targetColumnRowPair, Point mobileColumnRowPair) {
return targetColumnRowPair.y > mobileColumnRowPair.y && targetColumnRowPair.x < mobileColumnRowPair.x;
}
private boolean belowRight(Point targetColumnRowPair, Point mobileColumnRowPair) {
return targetColumnRowPair.y > mobileColumnRowPair.y && targetColumnRowPair.x > mobileColumnRowPair.x;
}
private boolean aboveLeft(Point targetColumnRowPair, Point mobileColumnRowPair) {
return targetColumnRowPair.y < mobileColumnRowPair.y && targetColumnRowPair.x < mobileColumnRowPair.x;
}
private boolean aboveRight(Point targetColumnRowPair, Point mobileColumnRowPair) {
return targetColumnRowPair.y < mobileColumnRowPair.y && targetColumnRowPair.x > mobileColumnRowPair.x;
}
private boolean above(Point targetColumnRowPair, Point mobileColumnRowPair) {
return targetColumnRowPair.y < mobileColumnRowPair.y && targetColumnRowPair.x == mobileColumnRowPair.x;
}
private boolean below(Point targetColumnRowPair, Point mobileColumnRowPair) {
return targetColumnRowPair.y > mobileColumnRowPair.y && targetColumnRowPair.x == mobileColumnRowPair.x;
}
private boolean right(Point targetColumnRowPair, Point mobileColumnRowPair) {
return targetColumnRowPair.y == mobileColumnRowPair.y && targetColumnRowPair.x > mobileColumnRowPair.x;
}
private boolean left(Point targetColumnRowPair, Point mobileColumnRowPair) {
return targetColumnRowPair.y == mobileColumnRowPair.y && targetColumnRowPair.x < mobileColumnRowPair.x;
}
private Point getColumnAndRowForView(View view) {
int pos = getPositionForView(view);
int columns = getColumnCount();
int column = pos % columns;
int row = pos / columns;
return new Point(column, row);
}
private long getId(int position) {
return getAdapter().getItemId(position);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void animateReorder(final int oldPosition, final int newPosition) {
boolean isForward = newPosition > oldPosition;
List<Animator> resultList = new LinkedList<Animator>();
if (isForward) {
for (int pos = Math.min(oldPosition, newPosition); pos < Math.max(oldPosition, newPosition); pos++) {
View view = getViewForId(getId(pos));
if ((pos + 1) % getColumnCount() == 0) {
resultList.add(createTranslationAnimations(view, -view.getWidth() * (getColumnCount() - 1), 0,
view.getHeight(), 0));
} else {
resultList.add(createTranslationAnimations(view, view.getWidth(), 0, 0, 0));
}
}
} else {
for (int pos = Math.max(oldPosition, newPosition); pos > Math.min(oldPosition, newPosition); pos
View view = getViewForId(getId(pos));
if ((pos + getColumnCount()) % getColumnCount() == 0) {
resultList.add(createTranslationAnimations(view, view.getWidth() * (getColumnCount() - 1), 0,
-view.getHeight(), 0));
} else {
resultList.add(createTranslationAnimations(view, -view.getWidth(), 0, 0, 0));
}
}
}
AnimatorSet resultSet = new AnimatorSet();
resultSet.playTogether(resultList);
resultSet.setDuration(MOVE_DURATION);
resultSet.setInterpolator(new AccelerateDecelerateInterpolator());
resultSet.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
mReorderAnimation = true;
updateEnableState();
}
@Override
public void onAnimationEnd(Animator animation) {
mReorderAnimation = false;
updateEnableState();
}
});
resultSet.start();
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private AnimatorSet createTranslationAnimations(View view, float startX, float endX, float startY, float endY) {
ObjectAnimator animX = ObjectAnimator.ofFloat(view, "translationX", startX, endX);
ObjectAnimator animY = ObjectAnimator.ofFloat(view, "translationY", startY, endY);
AnimatorSet animSetXY = new AnimatorSet();
animSetXY.playTogether(animX, animY);
return animSetXY;
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if (mHoverCell != null) {
mHoverCell.draw(canvas);
}
}
public interface OnDropListener {
void onActionDrop();
}
public interface OnDragListener {
public void onDragStarted(int position);
public void onDragPositionsChanged(int oldPosition, int newPosition);
}
public interface OnEditModeChangeListener {
public void onEditModeChanged(boolean inEditMode);
}
public interface OnSelectedItemBitmapCreationListener {
public void onPreSelectedItemBitmapCreation(View selectedView, int position, long itemId);
public void onPostSelectedItemBitmapCreation(View selectedView, int position, long itemId);
}
/**
* This scroll listener is added to the gridview in order to handle cell swapping
* when the cell is either at the top or bottom edge of the gridview. If the hover
* cell is at either edge of the gridview, the gridview will begin scrolling. As
* scrolling takes place, the gridview continuously checks if new cells became visible
* and determines whether they are potential candidates for a cell swap.
*/
private OnScrollListener mScrollListener = new OnScrollListener() {
private int mPreviousFirstVisibleItem = -1;
private int mPreviousVisibleItemCount = -1;
private int mCurrentFirstVisibleItem;
private int mCurrentVisibleItemCount;
private int mCurrentScrollState;
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
mCurrentFirstVisibleItem = firstVisibleItem;
mCurrentVisibleItemCount = visibleItemCount;
mPreviousFirstVisibleItem = (mPreviousFirstVisibleItem == -1) ? mCurrentFirstVisibleItem
: mPreviousFirstVisibleItem;
mPreviousVisibleItemCount = (mPreviousVisibleItemCount == -1) ? mCurrentVisibleItemCount
: mPreviousVisibleItemCount;
checkAndHandleFirstVisibleCellChange();
checkAndHandleLastVisibleCellChange();
mPreviousFirstVisibleItem = mCurrentFirstVisibleItem;
mPreviousVisibleItemCount = mCurrentVisibleItemCount;
if (isPostHoneycomb() && mWobbleInEditMode) {
updateWobbleState(visibleItemCount);
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void updateWobbleState(int visibleItemCount) {
for (int i = 0; i < visibleItemCount; i++) {
View child = getChildAt(i);
if (child != null) {
if (mMobileItemId != INVALID_ID && Boolean.TRUE != child.getTag(R.id.dgv_wobble_tag)) {
if (i % 2 == 0)
animateWobble(child);
else
animateWobbleInverse(child);
child.setTag(R.id.dgv_wobble_tag, true);
} else if (mMobileItemId == INVALID_ID && child.getRotation() != 0) {
child.setRotation(0);
child.setTag(R.id.dgv_wobble_tag, false);
}
}
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mCurrentScrollState = scrollState;
mScrollState = scrollState;
isScrollCompleted();
}
/**
* This method is in charge of invoking 1 of 2 actions. Firstly, if the gridview
* is in a state of scrolling invoked by the hover cell being outside the bounds
* of the gridview, then this scrolling event is continued. Secondly, if the hover
* cell has already been released, this invokes the animation for the hover cell
* to return to its correct position after the gridview has entered an idle scroll
* state.
*/
private void isScrollCompleted() {
if (mCurrentVisibleItemCount > 0 && mCurrentScrollState == SCROLL_STATE_IDLE) {
if (mCellIsMobile && mIsMobileScrolling) {
handleMobileCellScroll();
} else if (mIsWaitingForScrollFinish) {
touchEventsEnded();
}
}
}
/**
* Determines if the gridview scrolled up enough to reveal a new cell at the
* top of the list. If so, then the appropriate parameters are updated.
*/
public void checkAndHandleFirstVisibleCellChange() {
if (mCurrentFirstVisibleItem != mPreviousFirstVisibleItem) {
if (mCellIsMobile && mMobileItemId != INVALID_ID) {
updateNeighborViewsForId(mMobileItemId);
handleCellSwitch();
}
}
}
/**
* Determines if the gridview scrolled down enough to reveal a new cell at the
* bottom of the list. If so, then the appropriate parameters are updated.
*/
public void checkAndHandleLastVisibleCellChange() {
int currentLastVisibleItem = mCurrentFirstVisibleItem + mCurrentVisibleItemCount;
int previousLastVisibleItem = mPreviousFirstVisibleItem + mPreviousVisibleItemCount;
if (currentLastVisibleItem != previousLastVisibleItem) {
if (mCellIsMobile && mMobileItemId != INVALID_ID) {
updateNeighborViewsForId(mMobileItemId);
handleCellSwitch();
}
}
}
};
private static class DynamicGridModification {
private List<Pair<Integer, Integer>> transitions;
DynamicGridModification() {
super();
this.transitions = new Stack<Pair<Integer, Integer>>();
}
public boolean hasTransitions() {
return !transitions.isEmpty();
}
public void addTransition(int oldPosition, int newPosition) {
transitions.add(new Pair<Integer, Integer>(oldPosition, newPosition));
}
public List<Pair<Integer, Integer>> getTransitions() {
Collections.reverse(transitions);
return transitions;
}
}
} |
package au.gov.amsa.animator;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.geotools.data.FileDataStore;
import org.geotools.data.FileDataStoreFinder;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.wms.WebMapServer;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.JTSFactoryFinder;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.geotools.map.FeatureLayer;
import org.geotools.map.Layer;
import org.geotools.map.MapContent;
import org.geotools.map.WMSLayer;
import org.geotools.ows.ServiceException;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.geotools.renderer.lite.StreamingRenderer;
import org.geotools.styling.SLD;
import org.geotools.styling.Style;
import org.geotools.swing.JMapPane;
import org.geotools.swing.wms.WMSLayerChooser;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import rx.Scheduler.Worker;
import rx.internal.util.SubscriptionList;
import rx.schedulers.Schedulers;
import rx.schedulers.SwingScheduler;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.Point;
public class Animator {
private static final float CANBERRA_LAT = -35.3075f;
private static final float CANBERRA_LONG = 149.1244f;
private final Model model = new Model();
private final View view = new View();
private volatile JMapPane mapPane;
private volatile BufferedImage image;
private volatile BufferedImage backgroundImage;
private volatile BufferedImage offscreenImage;
final JPanel panel = createMapPanel();
final MapContent map;
private final SubscriptionList subscriptions;
private Worker worker;
private BufferedImage offScreenImage;
public Animator() {
map = createMap();
subscriptions = new SubscriptionList();
worker = Schedulers.newThread().createWorker();
subscriptions.add(worker);
}
private JPanel createMapPanel() {
JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
};
panel.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
}
});
return panel;
}
public void start() {
SwingScheduler
.getInstance()
.createWorker()
.schedule(
() -> {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
FramePreferences.restoreLocationAndSize(frame, 100,
100, 800, 600, Animator.class);
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
super.componentResized(e);
backgroundImage = null;
redraw();
}
@Override
public void componentShown(ComponentEvent e) {
super.componentShown(e);
backgroundImage = null;
redraw();
}
});
frame.setVisible(true);
});
final AtomicInteger timeStep = new AtomicInteger();
worker.schedulePeriodically(() -> {
model.updateModel(timeStep.getAndIncrement());
}, 0, 50, TimeUnit.MILLISECONDS);
}
private void redraw() {
ReferencedEnvelope mapBounds = map.getMaxBounds();
// get the frame width and height
int width = panel.getParent().getWidth();
double ratio = mapBounds.getHeight() / mapBounds.getWidth();
int proportionalHeight = (int) Math.round(width * ratio);
Rectangle imageBounds = new Rectangle(0, 0, width, proportionalHeight);
if (backgroundImage == null) {
BufferedImage backgroundImage = new BufferedImage(
imageBounds.width, imageBounds.height,
BufferedImage.TYPE_INT_RGB);
Graphics2D gr = backgroundImage.createGraphics();
gr.setPaint(Color.WHITE);
gr.fill(imageBounds);
StreamingRenderer renderer = new StreamingRenderer();
renderer.setMapContent(map);
renderer.paint(gr, imageBounds, mapBounds);
this.backgroundImage = backgroundImage;
this.offScreenImage = new BufferedImage(imageBounds.width,
imageBounds.height, BufferedImage.TYPE_INT_RGB);
offScreenImage.createGraphics();
}
offScreenImage.getGraphics().drawImage(backgroundImage, 0, 0, null);
view.draw(model, offScreenImage);
this.image = offScreenImage;
panel.repaint();
}
private MapContent createMap() {
final MapContent map = new MapContent();
map.setTitle("Animator");
map.getViewport();
map.addLayer(createCoastlineLayer());
map.addLayer(createExtraFeatures());
// addWms(map);
return map;
}
private Layer createCoastlineLayer() {
try {
// File file = new File(
// "/home/dxm/Downloads/shapefile-australia-coastline-polygon/cstauscd_r.shp");
File file = new File("src/main/resources/shapes/countries.shp");
FileDataStore store = FileDataStoreFinder.getDataStore(file);
SimpleFeatureSource featureSource = store.getFeatureSource();
Style style = SLD.createSimpleStyle(featureSource.getSchema());
Layer layer = new FeatureLayer(featureSource, style);
return layer;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static Layer createExtraFeatures() {
SimpleFeatureTypeBuilder b = new SimpleFeatureTypeBuilder();
b.setName("Location");
b.setCRS(DefaultGeographicCRS.WGS84);
// picture location
b.add("geom", Point.class);
final SimpleFeatureType TYPE = b.buildFeatureType();
GeometryFactory gf = JTSFactoryFinder.getGeometryFactory();
Point point = gf
.createPoint(new Coordinate(CANBERRA_LONG, CANBERRA_LAT));
SimpleFeatureBuilder builder = new SimpleFeatureBuilder(TYPE);
builder.add(point);
SimpleFeature feature = builder.buildFeature("Canberra");
DefaultFeatureCollection features = new DefaultFeatureCollection(null,
null);
features.add(feature);
Style style = SLD.createPointStyle("Star", Color.BLUE, Color.BLUE,
0.3f, 10);
return new FeatureLayer(features, style);
}
static void addWms(MapContent map) {
// URL wmsUrl = WMSChooser.showChooseWMS();
WebMapServer wms;
try {
String url = "http://129.206.228.72/cached/osm?Request=GetCapabilities";
wms = new WebMapServer(new URL(url));
} catch (ServiceException | IOException e) {
throw new RuntimeException(e);
}
List<org.geotools.data.ows.Layer> wmsLayers = WMSLayerChooser
.showSelectLayer(wms);
for (org.geotools.data.ows.Layer wmsLayer : wmsLayers) {
System.out.println("adding " + wmsLayer.getTitle());
WMSLayer displayLayer = new WMSLayer(wms, wmsLayer);
map.addLayer(displayLayer);
}
}
public static void main(String[] args) throws Exception {
System.setProperty("http.proxyHost", "proxy.amsa.gov.au");
System.setProperty("http.proxyPort", "8080");
System.setProperty("https.proxyHost", "proxy.amsa.gov.au");
System.setProperty("https.proxyPort", "8080");
new Animator().start();
}
} |
package com.stanfy.views.list;
import static com.stanfy.views.StateHelper.*;
import java.util.ArrayList;
import android.content.Context;
import android.database.DataSetObserver;
import android.support.v4.content.Loader;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.WrapperListAdapter;
import com.stanfy.DebugFlags;
import com.stanfy.app.CrucialGUIOperationManager.CrucialGUIOperationListener;
import com.stanfy.app.loader.LoadmoreLoader;
import com.stanfy.views.StateHelper;
public abstract class LoaderAdapter<MT> implements WrapperListAdapter, FetchableListAdapter, CrucialGUIOperationListener {
/** Logging tag. */
private static final String TAG = "LoaderAdapter";
/** Debug flag. */
private static final boolean DEBUG = DebugFlags.DEBUG_GUI;
/** Context. */
private final Context context;
/** Core adapter. */
private final ListAdapter core;
/** Loader instance. */
private Loader<MT> loader;
/** Listener. */
private OnListItemsLoadedListener listener;
/** Pending operations. */
private final ArrayList<Runnable> afterAnimationOperations = new ArrayList<Runnable>(3);
/** Animations running flag. */
private boolean animationsRunning = false;
/** State helper. */
private final StateHelper stateHelper;
/** State code. */
private int state = STATE_LOADING;
/** Last response data. */
private MT lastResponseData;
/** Used to sync states with core. */
private final DataSetObserver observer;
/** Listener call runnable. */
private CallOnListItemsLoadedListener callOnListItemsLoadedListener;
public LoaderAdapter(final Context context, final ListAdapter coreAdapter) {
this(context, coreAdapter, new StateHelper());
}
public LoaderAdapter(final Context context, final ListAdapter coreAdapter, final StateHelper stateHelper) {
this.stateHelper = stateHelper;
this.context = context;
this.core = coreAdapter;
this.observer = new Observer();
this.core.registerDataSetObserver(observer);
}
protected void setState(final int state) { this.state = state; }
protected MT getLastResponseData() { return lastResponseData; }
protected ListAdapter getCore() { return core; }
public StateHelper getStateHelper() { return stateHelper; }
public int getState() { return state; }
@Override
public boolean areAllItemsEnabled() {
if (state != STATE_NORMAL) { return false; }
return core.areAllItemsEnabled();
}
@Override
public boolean isEnabled(final int position) {
if (state != STATE_NORMAL) { return false; }
return core.isEnabled(position);
}
@Override
public void registerDataSetObserver(final DataSetObserver observer) {
core.registerDataSetObserver(observer);
}
@Override
public void unregisterDataSetObserver(final DataSetObserver observer) {
core.unregisterDataSetObserver(observer);
}
@Override
public int getCount() {
if (state == STATE_NORMAL) { return core.getCount(); }
return stateHelper.hasState(state) ? 1 : 0;
}
@Override
public Object getItem(final int position) {
if (state != STATE_NORMAL) { return null; }
return core.getItem(position);
}
@Override
public long getItemId(final int position) {
if (state != STATE_NORMAL) { return -1; }
return core.getItemId(position);
}
@Override
public boolean hasStableIds() { return core.hasStableIds(); }
@Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
if (state == STATE_NORMAL) {
return core.getView(position, convertView, parent);
}
return stateHelper.getCustomStateView(state, context, lastResponseData, parent);
}
@Override
public int getItemViewType(final int position) {
return state == STATE_NORMAL ? core.getItemViewType(position) : AdapterView.ITEM_VIEW_TYPE_IGNORE;
}
@Override
public int getViewTypeCount() { return core.getViewTypeCount(); }
@Override
public boolean isEmpty() { return getCount() == 0; }
@Override
public void loadMoreRecords() {
if (loader instanceof LoadmoreLoader) {
if (DEBUG) { Log.d(TAG, "Force loader to fetch more elements"); }
((LoadmoreLoader) loader).forceLoadMore();
}
}
@Override
public boolean moreElementsAvailable() {
return loader instanceof LoadmoreLoader
? ((LoadmoreLoader) loader).moreElementsAvailable()
: false;
}
@Override
public boolean isBusy() {
final boolean loaderBusy = loader instanceof LoadmoreLoader
? ((LoadmoreLoader) loader).isBusy()
: false;
return loaderBusy || !afterAnimationOperations.isEmpty();
}
@Override
public final ListAdapter getWrappedAdapter() { return core; }
@Override
public void onStartCrucialGUIOperation() {
animationsRunning = true;
}
@Override
public void onFinishCrucialGUIOperation() {
animationsRunning = false;
final ArrayList<Runnable> afterAnimationOperations = this.afterAnimationOperations;
final int count = afterAnimationOperations.size();
for (int i = 0; i < count; i++) {
afterAnimationOperations.get(i).run();
}
afterAnimationOperations.clear();
}
@Override
public void setOnListItemsLoadedListener(final OnListItemsLoadedListener listener) {
this.listener = listener;
}
public void onLoadStart() {
state = STATE_LOADING;
notifyDataSetChanged();
}
public void onLoaderReset(final Loader<MT> loader) {
if (DEBUG) { Log.i(TAG, "Loader <" + loader + "> reset; adapter: <" + this + ">"); }
lastResponseData = null;
}
public void onLoadFinished(final Loader<MT> loader, final MT data) {
this.loader = loader;
lastResponseData = data;
if (isResponseSuccessful(data)) {
if (isResponseEmpty(data)) {
onDataEmpty(data);
} else {
onDataSuccess(data);
}
} else {
onDataError(data);
}
}
protected abstract boolean isResponseSuccessful(final MT data);
protected abstract boolean isResponseEmpty(final MT data);
protected abstract void replaceDataInCore(final MT data);
final void addNewData(final MT data) {
state = STATE_NORMAL;
// this will cause notifyDataSetChanged
replaceDataInCore(data);
// notify listener
if (listener != null) { listener.onListItemsLoaded(); }
}
protected void onDataSuccess(final MT data) {
if (animationsRunning) {
afterAnimationOperations.add(new AddDataRunnable(data));
} else {
addNewData(data);
}
}
protected void onDataError(final MT data) {
state = STATE_MESSAGE;
notifyDataSetChanged();
}
protected void onDataEmpty(final MT data) {
if (core.isEmpty()) {
state = STATE_EMPTY;
notifyDataSetChanged();
}
// notify listener
if (listener != null) {
if (animationsRunning) {
if (callOnListItemsLoadedListener == null) {
callOnListItemsLoadedListener = new CallOnListItemsLoadedListener();
}
afterAnimationOperations.add(callOnListItemsLoadedListener);
} else {
listener.onListItemsLoaded();
}
}
}
/** Add data runnable. */
private final class AddDataRunnable implements Runnable {
/** Data. */
private final MT data;
public AddDataRunnable(final MT data) { this.data = data; }
@Override
public void run() { addNewData(data); }
}
/** Call listener runnable. */
private final class CallOnListItemsLoadedListener implements Runnable {
@Override
public void run() {
if (listener != null) { listener.onListItemsLoaded(); }
}
}
/** Data set observer. */
private final class Observer extends DataSetObserver {
@Override
public void onChanged() {
if (state == STATE_NORMAL && core.isEmpty()) {
state = STATE_EMPTY;
notifyDataSetChanged();
} else if (state == STATE_EMPTY && !core.isEmpty()) {
state = STATE_NORMAL;
notifyDataSetChanged();
}
}
}
} |
package codechicken.lib.datagen;
import com.google.gson.JsonObject;
import net.minecraft.data.DataGenerator;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.Item;
import net.minecraft.world.level.ItemLike;
import net.minecraft.world.level.block.Block;
import net.minecraftforge.client.model.generators.ItemModelBuilder;
import net.minecraftforge.client.model.generators.ModelFile;
import net.minecraftforge.client.model.generators.ModelProvider;
import net.minecraftforge.common.data.ExistingFileHelper;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.Nullable;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.Supplier;
public abstract class ItemModelProvider extends ModelProvider<ItemModelBuilder> {
private static final Logger LOGGER = LogManager.getLogger();
protected static final ModelFile.UncheckedModelFile GENERATED = new ModelFile.UncheckedModelFile("item/generated");
protected static final ModelFile.UncheckedModelFile HANDHELD = new ModelFile.UncheckedModelFile("item/handheld");
public ItemModelProvider(DataGenerator generator, String modid, ExistingFileHelper existingFileHelper) {
super(generator, modid, ITEM_FOLDER, WrappedItemModelBuilder::new, existingFileHelper);
}
//region Location helpers
protected String name(ItemLike item) {
return item.asItem().getRegistryName().getPath();
}
protected ResourceLocation itemTexture(ItemLike item) {
return itemTexture(item, "");
}
protected ResourceLocation itemTexture(Supplier<? extends Item> item) {
return itemTexture(item, "");
}
protected ResourceLocation itemTexture(ItemLike item, String folder) {
String f = "";
if (!StringUtils.isEmpty(folder)) {
f = StringUtils.appendIfMissing(folder, "/");
}
return modLoc("item/" + f + name(item));
}
protected ResourceLocation itemTexture(Supplier<? extends Item> item, String folder) {
return itemTexture(item.get(), folder);
}
protected ResourceLocation blockTexture(Block block) {
return itemTexture(block, "");
}
protected ResourceLocation blockTexture(Supplier<? extends Block> block) {
return blockTexture(block, "");
}
protected ResourceLocation blockTexture(Block block, String folder) {
String f = "";
if (!StringUtils.isEmpty(folder)) {
f = StringUtils.appendIfMissing(folder, "/");
}
return modLoc("block/" + f + name(block));
}
protected ResourceLocation blockTexture(Supplier<? extends Block> block, String folder) {
return blockTexture(block.get(), folder);
}
//endregion
//region Builder helpers.
protected ItemModelBuilder getBuilder(ItemLike item) {
return getBuilder(name(item));
}
protected ItemModelBuilder getBuilder(Supplier<? extends Item> item) {
return getBuilder(name(item.get()));
}
//endregion
//region Simple builder
protected SimpleItemModelBuilder getSimple(ItemLike item) {
WrappedItemModelBuilder builder = (WrappedItemModelBuilder) getBuilder(item);
if (builder.simpleBuilder == null) {
builder.simpleBuilder = new SimpleItemModelBuilder(this, builder, item.asItem());
}
return builder.simpleBuilder;
}
protected SimpleItemModelBuilder getSimple(Supplier<? extends Item> item) {
return getSimple(item.get());
}
protected SimpleItemModelBuilder generated(ItemLike item) {
return getSimple(item)
.parent(GENERATED);
}
protected SimpleItemModelBuilder generated(Supplier<? extends Item> item) {
return generated(item.get());
}
protected SimpleItemModelBuilder handheld(ItemLike item) {
return getSimple(item)
.parent(HANDHELD);
}
protected SimpleItemModelBuilder handheld(Supplier<? extends Item> item) {
return handheld(item.get());
}
protected void simpleItemBlock(Block block) {
getSimple(block)
.parent(new ModelFile.UncheckedModelFile(modLoc("block/" + name(block))))
.noTexture();
}
//endregion
private ExistingFileHelper getExistingFileHelper() {
return existingFileHelper;
}
public static class SimpleItemModelBuilder {
private final ItemModelProvider provider;
private final ItemModelBuilder builder;
private final Item item;
private final Map<String, ResourceLocation> layers = new HashMap<>();
private ModelFile parent;
private boolean noTexture = false;
private String folder = "";
@Nullable
private CustomLoaderBuilder loader;
private boolean built = false;
private SimpleItemModelBuilder(ItemModelProvider provider, ItemModelBuilder builder, Item item) {
this.provider = provider;
this.builder = builder;
this.item = item;
}
public SimpleItemModelBuilder parent(ModelFile parent) {
this.parent = Objects.requireNonNull(parent);
return this;
}
public SimpleItemModelBuilder texture(ResourceLocation texture) {
if (texture == null) throw new IllegalStateException("Use '.noTexture()' instead of '.texture(null)'");
return texture("layer0", texture);
}
public SimpleItemModelBuilder texture(String layer, ResourceLocation texture) {
if (noTexture) throw new IllegalStateException("Unable to set texture. NoTexture set.");
if (!StringUtils.isEmpty(folder)) throw new IllegalArgumentException("Adding texture would ignore existing folder.");
ResourceLocation existing = layers.put(layer, Objects.requireNonNull(texture));
if (existing != null) {
LOGGER.warn("Overwriting layer '{}' texture '{}' with '{}'", layer, existing, texture);
}
return this;
}
public SimpleItemModelBuilder folder(String folder) {
if (!layers.isEmpty()) throw new IllegalStateException("Textures set, folder would be ignored.");
if (noTexture) throw new IllegalStateException("No Texture set, folder would be ignored.");
this.folder = Objects.requireNonNull(folder);
return this;
}
public SimpleItemModelBuilder noTexture() {
if (!layers.isEmpty()) throw new IllegalStateException("Setting No Texture would ignore textures.");
if (!StringUtils.isEmpty(folder)) throw new IllegalArgumentException("Setting No Texture would ignore existing folder.");
this.noTexture = true;
return this;
}
public <L extends CustomLoaderBuilder> L customLoader(Function<SimpleItemModelBuilder, L> factory) {
if (loader != null) throw new IllegalStateException("Loader already set!");
L loader = factory.apply(this);
this.loader = loader;
return loader;
}
private void build() {
if (!built) {
builder.parent(parent);
if (!noTexture) {
if (layers.isEmpty()) {
builder.texture("layer0", provider.itemTexture(item, folder));
} else {
layers.forEach(builder::texture);
}
}
if (loader != null) {
loader.build(builder);
}
built = true;
}
}
}
private static class WrappedItemModelBuilder extends ItemModelBuilder {
private SimpleItemModelBuilder simpleBuilder;
public WrappedItemModelBuilder(ResourceLocation outputLocation, ExistingFileHelper existingFileHelper) {
super(outputLocation, existingFileHelper);
}
@Override
public JsonObject toJson() {
if (simpleBuilder != null) {
simpleBuilder.build();
if (simpleBuilder.loader != null) {
return simpleBuilder.loader.toJson(super.toJson());
}
}
return super.toJson();
}
}
public static class CustomLoaderBuilder {
protected final ResourceLocation loaderId;
protected final SimpleItemModelBuilder parent;
protected final ExistingFileHelper existingFileHelper;
protected final Map<String, Boolean> visibility = new LinkedHashMap<>();
protected CustomLoaderBuilder(ResourceLocation loaderId, SimpleItemModelBuilder parent) {
this.loaderId = loaderId;
this.parent = parent;
existingFileHelper = parent.provider.getExistingFileHelper();
}
public CustomLoaderBuilder visibility(String partName, boolean show) {
this.visibility.put(partName, show);
return this;
}
public SimpleItemModelBuilder end() {
return parent;
}
protected void build(ItemModelBuilder builder) {
}
protected JsonObject toJson(JsonObject json) {
json.addProperty("loader", loaderId.toString());
if (!visibility.isEmpty()) {
JsonObject visibilityObj = new JsonObject();
for (Map.Entry<String, Boolean> entry : visibility.entrySet()) {
visibilityObj.addProperty(entry.getKey(), entry.getValue());
}
json.add("visibility", visibilityObj);
}
return json;
}
}
} |
package org.jsecurity.web.servlet;
import org.jsecurity.web.WebInterceptor;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
/**
* A <tt>WebInterceptorFilter</tt> is a Servlet Filter that merely delegates all filter operations to a single internally
* wrapped {@link org.jsecurity.web.WebInterceptor} instance. It is a simple utility class to cleanly use a
* <tt>WebInterceptor</tt> as a servlet filter if so desired - the benefit is that you only have to code one
* WebInterceptor class, and you can re-use it in multiple environments such as in a servlet container,
* in Spring or Pico, JBoss, etc. This Filter represents the mechanism to use that one WebInterceptor directly in a
* Servlet environment.
*
* @author Les Hazlewood
* @since 0.2
*/
public class WebInterceptorFilter extends SecurityManagerFilter {
protected WebInterceptor webInterceptor;
public WebInterceptor getWebInterceptor() {
return this.webInterceptor;
}
public void setWebInterceptor(WebInterceptor webInterceptor) {
this.webInterceptor = webInterceptor;
}
public void afterSecurityManagerSet() {
WebInterceptor interceptor = getWebInterceptor();
if (interceptor == null) {
throw new IllegalStateException("WebInterceptor property must be set.");
}
afterWebInterceptorSet();
}
protected void afterWebInterceptorSet() {
}
protected void continueChain(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
chain.doFilter(request, response);
if (log.isTraceEnabled()) {
log.trace("Completed chain execution.");
}
}
protected void doFilterInternal(
ServletRequest request, ServletResponse response, FilterChain chain)
throws ServletException, IOException {
Exception exception = null;
WebInterceptor interceptor = getWebInterceptor();
try {
boolean continueChain = interceptor.preHandle(request, response);
if (log.isTraceEnabled()) {
log.trace("Invked interceptor.preHandle method. Continuing chain?: [" + continueChain + "]");
}
if (continueChain) {
continueChain(request, response, chain);
}
interceptor.postHandle(request, response);
if (log.isTraceEnabled()) {
log.trace("Successfully invoked interceptor.postHandle method");
}
} catch (Exception e) {
exception = e;
} finally {
try {
interceptor.afterCompletion(request, response, exception);
if (log.isTraceEnabled()) {
log.trace("Successfully invoked interceptor.afterCompletion method.");
}
} catch (Exception e) {
if (exception == null) {
exception = e;
}
}
if (exception != null) {
if (exception instanceof ServletException) {
throw (ServletException) exception;
} else if (exception instanceof IOException) {
throw (IOException) exception;
} else {
String msg = "Filter execution resulted in a Exception " +
"(not IOException or ServletException as the Filter api recommends). " +
"Wrapping in ServletException and propagating.";
throw new ServletException(msg, exception);
}
}
}
}
} |
package com.googlecode.totallylazy.records;
import com.googlecode.totallylazy.Callable1;
import com.googlecode.totallylazy.Callable2;
import com.googlecode.totallylazy.Pair;
import com.googlecode.totallylazy.Predicate;
import com.googlecode.totallylazy.Sequence;
import com.googlecode.totallylazy.Sequences;
import java.util.HashMap;
import java.util.Map;
import static com.googlecode.totallylazy.Callables.first;
import static com.googlecode.totallylazy.Predicates.in;
import static com.googlecode.totallylazy.Predicates.is;
import static com.googlecode.totallylazy.Predicates.where;
import static com.googlecode.totallylazy.Sequences.sequence;
import static com.googlecode.totallylazy.Strings.equalIgnoringCase;
import static com.googlecode.totallylazy.records.Keywords.keyword;
import static com.googlecode.totallylazy.records.Keywords.name;
public class RecordMethods {
@SuppressWarnings({"unchecked"})
public static Callable2<? super Record, ? super Pair<Keyword, Object>, Record> updateValues() {
return new Callable2<Record, Pair<Keyword, Object>, Record>() {
public Record call(Record record, Pair<Keyword, Object> field) throws Exception {
return record.set(field.first(), field.second());
}
};
}
public static Callable1<? super Record, Record> merge(final Record other) {
return merge(other.fields());
}
public static Callable1<? super Record, Record> merge(final Sequence<Pair<Keyword, Object>> fields) {
return new Callable1<Record, Record>() {
public Record call(Record record) throws Exception {
return fields.fold(record, updateValues());
}
};
}
public static Keyword getKeyword(String name, Sequence<Keyword> definitions) {
return definitions.find(where(name(), equalIgnoringCase(name))).getOrElse(keyword(name));
}
public static Callable1<? super Record, Sequence<Object>> getValuesFor(final Sequence<Keyword> fields) {
return new Callable1<Record, Sequence<Object>>() {
public Sequence<Object> call(Record record) throws Exception {
return record.getValuesFor(fields);
}
};
}
public static Record filter(Record original, Keyword... fields) {
return filter(original, Sequences.sequence(fields));
}
public static Record filter(Record original, Sequence<Keyword> fields) {
return record(original.fields().filter(where(first(Keyword.class), is(in(fields)))));
}
public static Record record(final Pair<Keyword, Object>... fields) {
return Sequences.sequence(fields).fold(new MapRecord(), updateValues());
}
public static Record record(final Sequence<Pair<Keyword, Object>> fields) {
return fields.fold(new MapRecord(), updateValues());
}
public static Sequence<Pair<? extends Predicate<? super Record>, Record>> update(final Callable1<Record, Predicate<? super Record>> callable, final Record... records) {
return update(callable, sequence(records));
}
public static Sequence<Pair<? extends Predicate<? super Record>, Record>> update(final Callable1<Record, Predicate<? super Record>> callable, final Sequence<Record> records) {
return records.map(toPair(callable));
}
public static Callable1<Record, Pair<? extends Predicate<? super Record>, Record>> toPair(final Callable1<Record, Predicate<? super Record>> callable) {
return new Callable1<Record, Pair<? extends Predicate<? super Record>, Record>>() {
public Pair<? extends Predicate<? super Record>, Record> call(Record record) throws Exception {
return Pair.pair(callable.call(record), record);
}
};
}
public static Callable1<? super Record, Map<String, Object>> asMap() {
return new Callable1<Record, Map<String, Object>>() {
public Map<String, Object> call(Record record) throws Exception {
return toMap(record);
}
};
}
public static Map<String, Object> toMap(Record record) {
return record.fields().fold(new HashMap<String, Object>(), intoMap());
}
public static Callable2<? super Map<String, Object>, ? super Pair<Keyword, Object>, Map<String, Object>> intoMap() {
return new Callable2<Map<String, Object>, Pair<Keyword, Object>, Map<String, Object>>() {
public Map<String, Object> call(Map<String, Object> map, Pair<Keyword, Object> pair) throws Exception {
map.put(pair.first().toString(), pair.second());
return map;
}
};
}
} |
package org.jboss.marshalling;
import java.io.InputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.Closeable;
import java.nio.ByteBuffer;
import java.util.Queue;
import java.util.ArrayDeque;
/**
* A {@code ByteInput} implementation which is populated asynchronously with {@link ByteBuffer} instances.
*/
public class NioByteInput extends InputStream implements ByteInput {
private final Queue<Pair<ByteBuffer, BufferReturn>> queue;
private final InputHandler inputHandler;
// protected by "queue"
private boolean eof;
private IOException failure;
/**
* Construct a new instance. The given {@code inputHandler} will
* be invoked after each buffer is fully read and when the stream is closed.
*
* @param inputHandler the input events handler
*/
public NioByteInput(final InputHandler inputHandler) {
this.inputHandler = inputHandler;
queue = new ArrayDeque<Pair<ByteBuffer, BufferReturn>>();
}
/**
* Push a buffer into the queue. There is no mechanism to limit the number of pushed buffers; if such a mechanism
* is desired, it must be implemented externally, for example maybe using a {@link java.util.concurrent.Semaphore Semaphore}.
*
* @param buffer the buffer from which more data should be read
*/
public void push(final ByteBuffer buffer) {
synchronized (this) {
if (!eof && failure == null) {
queue.add(Pair.create(buffer, (BufferReturn) null));
notifyAll();
}
}
}
/**
* Push a buffer into the queue. There is no mechanism to limit the number of pushed buffers; if such a mechanism
* is desired, it must be implemented externally, for example maybe using a {@link java.util.concurrent.Semaphore Semaphore}.
*
* @param buffer the buffer from which more data should be read
* @param bufferReturn the buffer return to send this buffer to when it is exhausted
*/
public void push(final ByteBuffer buffer, final BufferReturn bufferReturn) {
synchronized (this) {
if (!eof && failure == null) {
queue.add(Pair.create(buffer, bufferReturn));
notifyAll();
} else {
bufferReturn.returnBuffer(buffer);
}
}
}
/**
* Push the EOF condition into the queue. After this method is called, no further buffers may be pushed into this
* instance.
*/
public void pushEof() {
synchronized (this) {
eof = true;
notifyAll();
}
}
/**
* Push an exception condition into the queue. After this method is called, no further buffers may be pushed into this
* instance.
*
* @param e the exception to push
*/
public void pushException(IOException e) {
synchronized (this) {
if (! eof) {
failure = e;
notifyAll();
}
}
}
/** {@inheritDoc} */
public int read() throws IOException {
final Queue<Pair<ByteBuffer, BufferReturn>> queue = this.queue;
synchronized (this) {
while (queue.isEmpty()) {
if (eof) {
return -1;
}
checkFailure();
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new InterruptedIOException("Interrupted on read()");
}
}
final Pair<ByteBuffer, BufferReturn> pair = queue.peek();
final ByteBuffer buf = pair.getA();
final BufferReturn bufferReturn = pair.getB();
final int v = buf.get() & 0xff;
if (buf.remaining() == 0) {
if (bufferReturn != null) {
bufferReturn.returnBuffer(buf);
}
queue.poll();
try {
inputHandler.acknowledge();
} catch (IOException e) {
eof = true;
clearQueue();
notifyAll();
throw e;
}
}
return v;
}
}
private void clearQueue() {
synchronized (this) {
Pair<ByteBuffer, BufferReturn> pair;
while ((pair = queue.poll()) != null) {
final ByteBuffer buffer = pair.getA();
final BufferReturn ret = pair.getB();
if (ret != null) {
ret.returnBuffer(buffer);
}
}
}
}
/** {@inheritDoc} */
public int read(final byte[] b, final int off, int len) throws IOException {
if (len == 0) {
return 0;
}
final Queue<Pair<ByteBuffer, BufferReturn>> queue = this.queue;
synchronized (this) {
while (queue.isEmpty()) {
if (eof) {
return -1;
}
checkFailure();
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new InterruptedIOException("Interrupted on read()");
}
}
int total = 0;
while (len > 0) {
final Pair<ByteBuffer, BufferReturn> pair = queue.peek();
if (pair == null) {
break;
}
final ByteBuffer buffer = pair.getA();
final BufferReturn bufferReturn = pair.getB();
final int bytecnt = Math.min(buffer.remaining(), len);
buffer.get(b, off, bytecnt);
total += bytecnt;
len -= bytecnt;
if (buffer.remaining() == 0) {
if (bufferReturn != null) {
bufferReturn.returnBuffer(buffer);
}
queue.poll();
try {
inputHandler.acknowledge();
} catch (IOException e) {
eof = true;
clearQueue();
notifyAll();
throw e;
}
}
}
return total;
}
}
/** {@inheritDoc} */
public int available() throws IOException {
synchronized (this) {
int total = 0;
for (Pair<ByteBuffer, BufferReturn> pair : queue) {
total += pair.getA().remaining();
if (total < 0) {
return Integer.MAX_VALUE;
}
}
return total;
}
}
public long skip(long qty) throws IOException {
final Queue<Pair<ByteBuffer, BufferReturn>> queue = this.queue;
synchronized (this) {
while (queue.isEmpty()) {
if (eof) {
return 0L;
}
checkFailure();
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new InterruptedIOException("Interrupted on read()");
}
}
long skipped = 0L;
while (qty > 0L) {
final Pair<ByteBuffer, BufferReturn> pair = queue.peek();
if (pair == null) {
break;
}
final ByteBuffer buffer = pair.getA();
final BufferReturn bufferReturn = pair.getB();
final int bytecnt = Math.min(buffer.remaining(), (int) Math.max((long)Integer.MAX_VALUE, qty));
buffer.position(buffer.position() + bytecnt);
skipped += bytecnt;
qty -= bytecnt;
if (buffer.remaining() == 0) {
queue.poll();
if (bufferReturn != null) {
bufferReturn.returnBuffer(buffer);
}
try {
inputHandler.acknowledge();
} catch (IOException e) {
eof = true;
notifyAll();
clearQueue();
throw e;
}
}
}
return skipped;
}
}
/** {@inheritDoc} */
public void close() throws IOException {
synchronized (this) {
if (! eof) {
clearQueue();
eof = true;
notifyAll();
inputHandler.close();
}
}
}
private void checkFailure() throws IOException {
final IOException failure = this.failure;
if (failure != null) {
failure.fillInStackTrace();
try {
throw failure;
} finally {
eof = true;
clearQueue();
notifyAll();
this.failure = null;
}
}
}
/**
* A handler for events relating to the consumption of data from a {@link NioByteInput} instance.
*/
public interface InputHandler extends Closeable {
/**
* Acknowledges the successful processing of an input buffer.
*
* @throws IOException if an I/O error occurs sending the acknowledgement
*/
void acknowledge() throws IOException;
/**
* Signifies that the user of the enclosing {@link NioByteInput} has called the {@code close()} method
* explicitly.
*
* @throws IOException if an I/O error occurs
*/
void close() throws IOException;
}
/**
* A handler for returning buffers which are have been exhausted.
*/
public interface BufferReturn {
/**
* Accept a returned buffer.
*
* @param buffer the buffer
*/
void returnBuffer(ByteBuffer buffer);
}
} |
package server;
import gui.WebServerGui;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
/**
* This represents a welcoming server for the incoming
* TCP request from a HTTP client such as a web browser.
*
* @author Chandan R. Rupakheti (rupakhet@rose-hulman.edu)
*/
public class Server implements Runnable {
private String rootDirectory;
private int port;
private boolean stop;
private ServerSocket welcomeSocket;
private long connections;
private long serviceTime;
public static int numberOfRequests = 0;
public static int numberOfResponses = 0;
private WebServerGui window;
/**
* @param rootDirectory
* @param port
*/
public Server(String rootDirectory, int port, WebServerGui window) {
this.rootDirectory = rootDirectory;
this.port = port;
this.stop = false;
this.connections = 0;
this.serviceTime = 0;
this.window = window;
}
/**
* Gets the root directory for this web server.
*
* @return the rootDirectory
*/
public String getRootDirectory() {
return rootDirectory;
}
/**
* Gets the port number for this web server.
*
* @return the port
*/
public int getPort() {
return port;
}
/**
* Returns connections serviced per second.
* Synchronized to be used in threaded environment.
*
* @return
*/
public synchronized double getServiceRate() {
if(this.serviceTime == 0)
return Long.MIN_VALUE;
double rate = this.connections/(double)this.serviceTime;
rate = rate * 1000;
return rate;
}
/**
* Increments number of connection by the supplied value.
* Synchronized to be used in threaded environment.
*
* @param value
*/
public synchronized void incrementConnections(long value) {
this.connections += value;
}
/**
* Increments the service time by the supplied value.
* Synchronized to be used in threaded environment.
*
* @param value
*/
public synchronized void incrementServiceTime(long value) {
this.serviceTime += value;
}
/**
* The entry method for the main server thread that accepts incoming
* TCP connection request and creates a {@link ConnectionHandler} for
* the request.
*/
public void run() {
try {
this.welcomeSocket = new ServerSocket(port);
// Now keep welcoming new connections until stop flag is set to true
while(true) {
// Listen for incoming socket connection
// This method block until somebody makes a request
Socket connectionSocket = this.welcomeSocket.accept();
Server.numberOfRequests++;
// Come out of the loop if the stop flag is set
if(this.stop)
break;
// Create a handler for this incoming connection and start the handler in a new thread
ConnectionHandler handler = new ConnectionHandler(this, connectionSocket);
new Thread(handler).start();
}
this.welcomeSocket.close();
}
catch(Exception e) {
window.showSocketException(e);
}
}
/**
* Stops the server from listening further.
*/
public synchronized void stop() {
if(this.stop)
return;
// Set the stop flag to be true
this.stop = true;
try {
// This will force welcomeSocket to come out of the blocked accept() method
// in the main loop of the start() method
Socket socket = new Socket(InetAddress.getLocalHost(), port);
// We do not have any other job for this socket so just close it
socket.close();
}
catch(Exception e){}
}
/**
* Checks if the server is stopeed or not.
* @return
*/
public boolean isStopped() {
if(this.welcomeSocket != null)
return this.welcomeSocket.isClosed();
return true;
}
} |
package com.akiban.sql.optimizer;
import com.akiban.sql.StandardException;
import com.akiban.sql.compiler.TypeComputer;
import com.akiban.sql.parser.CreateViewNode;
import com.akiban.sql.parser.FromSubquery;
import com.akiban.sql.parser.SQLParser;
import com.akiban.sql.parser.SQLParserFeature;
import com.akiban.ais.model.AkibanInformationSchema;
import com.akiban.ais.model.TableName;
import com.akiban.ais.model.View;
import com.akiban.server.error.InvalidParameterValueException;
import com.akiban.server.error.ViewHasBadSubqueryException;
import com.akiban.server.service.functions.FunctionsRegistryImpl;
import java.util.*;
/** An Akiban schema, parser and binder with various client properties.
* Also caches view definitions.
*/
public class AISBinderContext
{
protected Properties properties;
protected AkibanInformationSchema ais;
protected long aisTimestamp = -1;
protected SQLParser parser;
protected String defaultSchemaName;
protected AISBinder binder;
protected TypeComputer typeComputer;
protected Map<View,AISViewDefinition> viewDefinitions;
/** When context is part of a larger object, such as a server session. */
protected AISBinderContext() {
}
/** Standalone context used for loading views in tests and bootstrapping. */
public AISBinderContext(AkibanInformationSchema ais, String defaultSchemaName) {
this.ais = ais;
this.defaultSchemaName = defaultSchemaName;
properties = new Properties();
properties.put("database", defaultSchemaName);
initParser();
setBinderAndTypeComputer(new AISBinder(ais, defaultSchemaName),
new FunctionsTypeComputer(new FunctionsRegistryImpl()));
}
public Properties getProperties() {
return properties;
}
public String getProperty(String key) {
return properties.getProperty(key);
}
public String getProperty(String key, String defval) {
return properties.getProperty(key, defval);
}
public void setProperty(String key, String value) {
if (value == null)
properties.remove(key);
else
properties.setProperty(key, value);
}
protected void setProperties(Properties properties) {
this.properties = properties;
}
public AkibanInformationSchema getAIS() {
return ais;
}
public SQLParser getParser() {
return parser;
}
protected Set<SQLParserFeature> initParser() {
parser = new SQLParser();
parser.getFeatures().remove(SQLParserFeature.GEO_INDEX_DEF_FUNC); // Off by default.
Set<SQLParserFeature> parserFeatures = new HashSet<SQLParserFeature>();
// TODO: Others that are on by defaults; could have override to turn them
// off, but they are pretty harmless.
if (getBooleanProperty("parserInfixBit", false))
parserFeatures.add(SQLParserFeature.INFIX_BIT_OPERATORS);
if (getBooleanProperty("parserInfixLogical", false))
parserFeatures.add(SQLParserFeature.INFIX_LOGICAL_OPERATORS);
if (getBooleanProperty("columnAsFunc", false))
parserFeatures.add(SQLParserFeature.MYSQL_COLUMN_AS_FUNCS);
String prop = getProperty("parserDoubleQuoted", "identifier");
if (prop.equals("string"))
parserFeatures.add(SQLParserFeature.DOUBLE_QUOTED_STRING);
else if (!prop.equals("identifier"))
throw new InvalidParameterValueException("'" + prop
+ "' for parserDoubleQuoted");
if (getBooleanProperty("parserGeospatialIndexes", false))
parserFeatures.add(SQLParserFeature.GEO_INDEX_DEF_FUNC);
parser.getFeatures().addAll(parserFeatures);
defaultSchemaName = getProperty("database");
// TODO: Any way / need to ask AIS if schema exists and report error?
BindingNodeFactory.wrap(parser);
return parserFeatures;
}
public boolean getBooleanProperty(String key, boolean defval) {
String prop = getProperty(key);
if (prop == null) return defval;
if (prop.equalsIgnoreCase("true"))
return true;
else if (prop.equalsIgnoreCase("false"))
return false;
else
throw new InvalidParameterValueException("'" + prop + "' for " + key);
}
/** Get the non-default properties that were used to parse a view
* definition, for example.
* @see #initParser
*/
public Properties getParserProperties(String schemaName) {
Properties properties = new Properties();
if (!defaultSchemaName.equals(schemaName))
properties.put("database", defaultSchemaName);
String prop = getProperty("parserInfixBit", "false");
if (!"false".equals(prop))
properties.put("parserInfixBit", prop);
prop = getProperty("parserInfixLogical", "false");
if (!"false".equals(prop))
properties.put("parserInfixLogical", prop);
prop = getProperty("columnAsFunc", "false");
if (!"false".equals(prop))
properties.put("columnAsFunc", prop);
prop = getProperty("parserDoubleQuoted", "identifier");
if (!"identifier".equals(prop))
properties.put("parserDoubleQuoted", prop);
return properties;
}
public String getDefaultSchemaName() {
return defaultSchemaName;
}
public void setDefaultSchemaName(String defaultSchemaName) {
this.defaultSchemaName = defaultSchemaName;
if (binder != null)
binder.setDefaultSchemaName(defaultSchemaName);
}
public AISBinder getBinder() {
return binder;
}
public void setBinderAndTypeComputer(AISBinder binder, TypeComputer typeComputer) {
this.binder = binder;
binder.setContext(this);
this.typeComputer = typeComputer;
this.viewDefinitions = new HashMap<View,AISViewDefinition>();
}
protected void initBinder() {
assert (binder == null);
setBinderAndTypeComputer(new AISBinder(ais, defaultSchemaName), null);
}
/** Get view definition given the AIS view. */
public AISViewDefinition getViewDefinition(View view) {
AISViewDefinition viewdef = viewDefinitions.get(view);
if (viewdef == null) {
viewdef = new ViewReloader(view, this).getViewDefinition(view.getDefinition());
viewDefinitions.put(view, viewdef);
}
return viewdef;
}
/** When reloading a view from AIS, we need to parse the
* definition text again in the same parser environment as it was
* originally defined. Also the present binder is in the middle of
* something so we need a separate one.
*/
protected static class ViewReloader extends AISBinderContext {
public ViewReloader(View view, AISBinderContext parent) {
ais = view.getAIS();
properties = view.getDefinitionProperties();
initParser();
if (defaultSchemaName == null)
defaultSchemaName = view.getName().getSchemaName();
setBinderAndTypeComputer(new AISBinder(ais, defaultSchemaName),
parent.typeComputer);
}
}
/** Get view definition given the user's DDL. */
public AISViewDefinition getViewDefinition(CreateViewNode ddl) {
try {
AISViewDefinition view = new AISViewDefinition(ddl, parser);
// Just want the definition for result columns and table references.
// If the view uses another view, the inner one is treated
// like a table for those purposes.
binder.bind(view.getSubquery(), false);
if (typeComputer != null)
view.getSubquery().accept(typeComputer);
return view;
}
catch (StandardException ex) {
throw new ViewHasBadSubqueryException(ddl.getObjectName().toString(),
ex.getMessage());
}
}
/** Get view definition using stored copy of original DDL. */
public AISViewDefinition getViewDefinition(String ddl) {
AISViewDefinition view = null;
try {
view = new AISViewDefinition(ddl, parser);
// Want a subquery that can be spliced in.
// If the view uses another view, it gets expanded, too.
binder.bind(view.getSubquery(), true);
if (typeComputer != null)
view.getSubquery().accept(typeComputer);
}
catch (StandardException ex) {
String name = ddl;
if (view != null)
name = view.getName().toString();
throw new ViewHasBadSubqueryException(name, ex.getMessage());
}
return view;
}
} |
package org.mockito.stubbing.answers;
import java.util.Collection;
import java.util.LinkedList;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
/**
* Returns elements of the collection. Keeps returning the last element forever.
* Might be useful on occasion when you have a collection of elements to return.
* <p>
* <pre class="code"><code class="java">
* //this:
* when(mock.foo()).thenReturn(1, 2, 3);
* //is equivalent to:
* when(mock.foo()).thenReturn(new ReturnsElementsOf(Arrays.asList(1, 2, 3)));
* </code></pre>
*/
public class ReturnsElementsOf implements Answer<Object> {
private final LinkedList<Object> elements;
public ReturnsElementsOf(Collection<?> elements) {
if (elements == null) {
throw new MockitoException("ReturnsElementsOf does not accept null as constructor argument.\n" +
"Please pass a collection instance");
}
this.elements = new LinkedList<Object>(elements);
}
public Object answer(InvocationOnMock invocation) throws Throwable {
if (elements.size() == 1)
return elements.get(0);
else
return elements.poll();
}
} |
package com.jetbrains.ther.parsing;
import com.intellij.lang.PsiBuilder;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.tree.IElementType;
import com.jetbrains.ther.lexer.TheRTokenTypes;
import org.jetbrains.annotations.NotNull;
public class TheRExpressionParsing extends Parsing {
private static final Logger LOG = Logger.getInstance(TheRExpressionParsing.class.getName());
public TheRExpressionParsing(@NotNull final TheRParsingContext context) {
super(context);
}
public void parseExpressionStatement() {
skipNewLines();
final IElementType firstToken = myBuilder.getTokenType();
if (firstToken == null) return;
if (firstToken == TheRTokenTypes.IF_KEYWORD) {
parseIfExpression();
}
else if (firstToken == TheRTokenTypes.WHILE_KEYWORD) {
parseWhileExpression();
}
else if (firstToken == TheRTokenTypes.FOR_KEYWORD) {
parseForExpression();
}
else if (firstToken == TheRTokenTypes.REPEAT_KEYWORD) {
parseRepeatExpression();
}
else if (firstToken == TheRTokenTypes.BREAK_KEYWORD) {
parseBreakExpression();
}
else if (firstToken == TheRTokenTypes.NEXT_KEYWORD) {
parseNextExpression();
}
else if (firstToken == TheRTokenTypes.LBRACE) {
parseBlockExpression();
}
else if (firstToken == TheRTokenTypes.FUNCTION_KEYWORD) {
getFunctionParser().parseFunctionDeclaration();
}
else if (myBuilder.getTokenType() == TheRTokenTypes.HELP) {
parseHelpExpression();
}
else {
parseAssignmentExpression();
}
}
private void parseIfExpression() {
final PsiBuilder.Marker ifExpression = myBuilder.mark();
parseConditionExpression();
parseExpressionStatement();
skipNewLines();
if (myBuilder.getTokenType() == TheRTokenTypes.ELSE_KEYWORD) {
myBuilder.advanceLexer();
parseExpressionStatement();
}
checkSemicolon();
ifExpression.done(TheRElementTypes.IF_STATEMENT);
}
private void parseWhileExpression() {
final PsiBuilder.Marker whileExpression = myBuilder.mark();
parseConditionExpression();
parseExpressionStatement();
checkSemicolon();
whileExpression.done(TheRElementTypes.WHILE_STATEMENT);
}
private void parseConditionExpression() {
advanceAndSkipNewLines();
checkMatches(TheRTokenTypes.LPAR, "( expected");
parseExpressionStatement();
skipNewLines();
checkMatches(TheRTokenTypes.RPAR, ") expected");
skipNewLines();
}
private void parseForExpression() {
final PsiBuilder.Marker forExpression = myBuilder.mark();
advanceAndSkipNewLines();
checkMatches(TheRTokenTypes.LPAR, "( expected");
parseExpressionStatement();
skipNewLines();
if (checkMatches(TheRTokenTypes.IN_KEYWORD, "'in' expected")) {
parseExpressionStatement();
}
skipNewLines();
checkMatches(TheRTokenTypes.RPAR, ") expected");
parseExpressionStatement();
checkSemicolon();
forExpression.done(TheRElementTypes.FOR_STATEMENT);
}
private void parseRepeatExpression() {
final PsiBuilder.Marker repeatExpression = myBuilder.mark();
advanceAndSkipNewLines();
parseExpressionStatement();
checkSemicolon();
repeatExpression.done(TheRElementTypes.REPEAT_STATEMENT);
}
private void parseBreakExpression() {
final PsiBuilder.Marker breakExpression = myBuilder.mark();
myBuilder.advanceLexer();
parseNextBreakInnerExpression();
checkSemicolon();
breakExpression.done(TheRElementTypes.BREAK_STATEMENT);
}
private void parseNextExpression() {
final PsiBuilder.Marker statement = myBuilder.mark();
myBuilder.advanceLexer();
parseNextBreakInnerExpression();
skipNewLines();
statement.done(TheRElementTypes.NEXT_STATEMENT);
}
private void parseNextBreakInnerExpression() {
if (myBuilder.getTokenType() == TheRTokenTypes.LPAR) {
advanceAndSkipNewLines();
if (atToken(TheRTokenTypes.RPAR)) {
myBuilder.advanceLexer();
return;
}
parseExpressionStatement();
skipNewLines();
checkMatches(TheRTokenTypes.RPAR, ") expected");
}
}
public void parseBlockExpression() {
final PsiBuilder.Marker blockExpression = myBuilder.mark();
advanceAndSkipNewLines();
while (myBuilder.getTokenType() != TheRTokenTypes.RBRACE) {
if (myBuilder.eof()) {
myBuilder.error("missing }");
blockExpression.done(TheRElementTypes.BLOCK);
return;
}
parseExpressionStatement();
}
myBuilder.advanceLexer();
checkSemicolon();
blockExpression.done(TheRElementTypes.BLOCK);
}
public void parseHelpExpression() {
final PsiBuilder.Marker mark = myBuilder.mark();
advanceAndSkipNewLines();
if (myBuilder.getTokenType() == TheRTokenTypes.HELP) {
advanceAndSkipNewLines();
}
if (TheRTokenTypes.KEYWORDS.contains(myBuilder.getTokenType())) {
myBuilder.advanceLexer();
mark.done(TheRElementTypes.HELP_EXPRESSION);
}
else if (parseFormulaeExpression()) { // should we parse expression statement instead?
mark.done(TheRElementTypes.HELP_EXPRESSION);
}
else {
myBuilder.error(EXPRESSION_EXPECTED);
mark.drop();
}
}
protected void parseAssignmentExpression() {
final PsiBuilder.Marker assignmentExpression = myBuilder.mark();
final boolean successfull = parseFormulaeExpression();
if (successfull) {
if (TheRTokenTypes.ASSIGNMENTS.contains(myBuilder.getTokenType())) {
advanceAndSkipNewLines();
parseExpressionStatement();
checkSemicolon();
assignmentExpression.done(TheRElementTypes.ASSIGNMENT_STATEMENT);
}
else {
checkSemicolon();
assignmentExpression.drop();
}
return;
}
else
assignmentExpression.drop();
myBuilder.advanceLexer();
myBuilder.error(EXPRESSION_EXPECTED);
}
public boolean parseFormulaeExpression() {
PsiBuilder.Marker expr = myBuilder.mark();
if (!parseOrExpression()) {
expr.drop();
return false;
}
while (TheRTokenTypes.TILDE == myBuilder.getTokenType()) {
advanceAndSkipNewLines();
if (!parseOrExpression()) {
myBuilder.error(EXPRESSION_EXPECTED);
}
expr.done(TheRElementTypes.BINARY_EXPRESSION);
expr = expr.precede();
}
expr.drop();
return true;
}
public boolean parseOrExpression() {
PsiBuilder.Marker expr = myBuilder.mark();
if (!parseANDExpression()) {
expr.drop();
return false;
}
skipNewLines();
while (TheRTokenTypes.OR_OPERATIONS.contains(myBuilder.getTokenType())) {
advanceAndSkipNewLines();
if (!parseANDExpression()) {
myBuilder.error(EXPRESSION_EXPECTED);
}
expr.done(TheRElementTypes.BINARY_EXPRESSION);
expr = expr.precede();
}
expr.drop();
return true;
}
private boolean parseANDExpression() {
PsiBuilder.Marker expr = myBuilder.mark();
if (!parseNOTExpression()) {
expr.drop();
return false;
}
skipNewLines();
while (TheRTokenTypes.AND_OPERATIONS.contains(myBuilder.getTokenType())) {
advanceAndSkipNewLines();
if (!parseNOTExpression()) {
myBuilder.error(EXPRESSION_EXPECTED);
}
expr.done(TheRElementTypes.BINARY_EXPRESSION);
expr = expr.precede();
}
expr.drop();
return true;
}
private boolean parseNOTExpression() {
if (myBuilder.getTokenType() == TheRTokenTypes.NOT) {
final PsiBuilder.Marker expr = myBuilder.mark();
myBuilder.advanceLexer();
if (!parseNOTExpression()) {
myBuilder.error(EXPRESSION_EXPECTED);
}
expr.done(TheRElementTypes.PREFIX_EXPRESSION);
return true;
}
else {
return parseComparisonExpression();
}
}
private boolean parseComparisonExpression() {
PsiBuilder.Marker expr = myBuilder.mark();
if (!parseAdditiveExpression()) {
myBuilder.error(EXPRESSION_EXPECTED);
expr.drop();
return false;
}
while (TheRTokenTypes.COMPARISON_OPERATIONS.contains(myBuilder.getTokenType())) {
advanceAndSkipNewLines();
if (!parseAdditiveExpression()) {
myBuilder.error(EXPRESSION_EXPECTED);
}
expr.done(TheRElementTypes.BINARY_EXPRESSION);
expr = expr.precede();
}
expr.drop();
return true;
}
private boolean parseAdditiveExpression() {
PsiBuilder.Marker expr = myBuilder.mark();
if (!parseMultiplicativeExpression()) {
expr.drop();
return false;
}
while (TheRTokenTypes.ADDITIVE_OPERATIONS.contains(myBuilder.getTokenType())) {
advanceAndSkipNewLines();
if (!parseMultiplicativeExpression()) {
myBuilder.error(EXPRESSION_EXPECTED);
}
expr.done(TheRElementTypes.BINARY_EXPRESSION);
expr = expr.precede();
}
expr.drop();
return true;
}
private boolean parseMultiplicativeExpression() {
PsiBuilder.Marker expr = myBuilder.mark();
if (!parseUserDefinedExpression()) {
expr.drop();
return false;
}
while (TheRTokenTypes.MULTIPLICATIVE_OPERATIONS.contains(myBuilder.getTokenType())) {
advanceAndSkipNewLines();
if (!parseUserDefinedExpression()) {
myBuilder.error(EXPRESSION_EXPECTED);
}
expr.done(TheRElementTypes.BINARY_EXPRESSION);
expr = expr.precede();
}
expr.drop();
return true;
}
private boolean parseUserDefinedExpression() {
PsiBuilder.Marker expr = myBuilder.mark();
if (!parseSliceExpression()) {
expr.drop();
return false;
}
while (TheRTokenTypes.INFIX_OP == myBuilder.getTokenType()) {
advanceAndSkipNewLines();
if (!parseSliceExpression()) {
myBuilder.error(EXPRESSION_EXPECTED);
}
expr.done(TheRElementTypes.BINARY_EXPRESSION);
expr = expr.precede();
}
expr.drop();
return true;
}
protected boolean parseSliceExpression() {
PsiBuilder.Marker expr = myBuilder.mark();
if (!parseUnaryExpression()) {
expr.drop();
return false;
}
while (TheRTokenTypes.COLON == myBuilder.getTokenType()) {
advanceAndSkipNewLines();
if (!parseUnaryExpression()) {
myBuilder.error(EXPRESSION_EXPECTED);
}
expr.done(TheRElementTypes.SLICE_EXPRESSION);
expr = expr.precede();
}
expr.drop();
return true;
}
protected boolean parseUnaryExpression() {
final IElementType tokenType = myBuilder.getTokenType();
if (TheRTokenTypes.UNARY_OPERATIONS.contains(tokenType)) {
final PsiBuilder.Marker expr = myBuilder.mark();
myBuilder.advanceLexer();
if (!parseUnaryExpression()) {
myBuilder.error(EXPRESSION_EXPECTED);
}
expr.done(TheRElementTypes.PREFIX_EXPRESSION);
return true;
}
else {
return parsePowerExpression();
}
}
private boolean parsePowerExpression() {
PsiBuilder.Marker expr = myBuilder.mark();
if (!parseMemberExpression()) {
expr.drop();
return false;
}
if (TheRTokenTypes.POWER_OPERATIONS.contains(myBuilder.getTokenType())) {
myBuilder.advanceLexer();
if (!parseUnaryExpression()) {
myBuilder.error(EXPRESSION_EXPECTED);
}
expr.done(TheRElementTypes.BINARY_EXPRESSION);
}
else {
expr.drop();
}
return true;
}
public boolean parseMemberExpression() {
PsiBuilder.Marker expr = myBuilder.mark();
if (!parsePrimaryExpression()) {
expr.drop();
return false;
}
while (true) {
final IElementType tokenType = myBuilder.getTokenType();
if (tokenType == TheRTokenTypes.LIST_SUBSET) {
myBuilder.advanceLexer();
if (!parseStringOrIdentifier()) {
myBuilder.error("Expected string or identifier");
}
expr.done(TheRElementTypes.REFERENCE_EXPRESSION);
expr = expr.precede();
}
else if (tokenType == TheRTokenTypes.LPAR) {
skipNewLines();
parseArgumentList();
expr.done(TheRElementTypes.CALL_EXPRESSION);
expr = expr.precede();
}
else if (TheRTokenTypes.NAMESPACE_ACCESS.contains(tokenType)) {
myBuilder.advanceLexer();
parseFormulaeExpression();
expr.done(TheRElementTypes.REFERENCE_EXPRESSION);
expr = expr.precede();
}
else if (TheRTokenTypes.OPEN_BRACKETS.contains(tokenType)) {
advanceAndSkipNewLines();
if (myBuilder.getTokenType() == TheRTokenTypes.COMMA) {
PsiBuilder.Marker marker = myBuilder.mark();
marker.done(TheRElementTypes.EMPTY_EXPRESSION);
advanceAndSkipNewLines();
}
final IElementType CLOSE_BRACKET = TheRTokenTypes.BRACKER_PAIRS.get(tokenType);
while (myBuilder.getTokenType() != CLOSE_BRACKET && !myBuilder.eof()) {
parseExpressionStatement();
if (myBuilder.getTokenType() == TheRTokenTypes.COMMA) {
advanceAndSkipNewLines();
}
}
checkMatches(CLOSE_BRACKET, "Closing ] or ]] expected");
expr.done(TheRElementTypes.SUBSCRIPTION_EXPRESSION);
expr = expr.precede();
}
else {
expr.drop();
break;
}
}
return true;
}
private boolean parseStringOrIdentifier() {
if (myBuilder.getTokenType() == TheRTokenTypes.STRING_LITERAL) {
buildTokenElement(TheRElementTypes.STRING_LITERAL_EXPRESSION, myBuilder);
return true;
}
else if (myBuilder.getTokenType() == TheRTokenTypes.IDENTIFIER) {
buildTokenElement(TheRElementTypes.REFERENCE_EXPRESSION, myBuilder);
return true;
}
return false;
}
public void parseArgumentList() {
LOG.assertTrue(myBuilder.getTokenType() == TheRTokenTypes.LPAR);
final PsiBuilder.Marker arglist = myBuilder.mark();
myBuilder.advanceLexer();
int argNumber = 0;
skipNewLines();
while (myBuilder.getTokenType() != TheRTokenTypes.RPAR) {
argNumber++;
if (argNumber > 1) {
if (matchToken(TheRTokenTypes.COMMA)) {
skipNewLines();
if (atToken(TheRTokenTypes.RPAR)) {
break;
}
}
else {
myBuilder.error("',' or ')' expected");
break;
}
}
if (myBuilder.getTokenType() == TheRTokenTypes.IDENTIFIER || myBuilder.getTokenType() == TheRTokenTypes.STRING_LITERAL) {
final PsiBuilder.Marker keywordArgMarker = myBuilder.mark();
parseFormulaeExpression();
skipNewLines();
if (TheRTokenTypes.ASSIGNMENTS.contains(myBuilder.getTokenType())) {
advanceAndSkipNewLines();
if (myBuilder.getTokenType() == TheRTokenTypes.FUNCTION_KEYWORD) {
getFunctionParser().parseFunctionDeclaration();
keywordArgMarker.done(TheRElementTypes.KEYWORD_ARGUMENT_EXPRESSION);
continue;
}
final PsiBuilder.Marker keywordValue = myBuilder.mark();
if (!parseFormulaeExpression()) {
myBuilder.error(EXPRESSION_EXPECTED);
keywordValue.rollbackTo();
}
else {
keywordValue.drop();
}
keywordArgMarker.done(TheRElementTypes.KEYWORD_ARGUMENT_EXPRESSION);
continue;
}
keywordArgMarker.rollbackTo();
}
if (myBuilder.getTokenType() == TheRTokenTypes.LBRACE) {
parseBlockExpression();
continue;
}
if (myBuilder.getTokenType() == TheRTokenTypes.TRIPLE_DOTS) {
myBuilder.advanceLexer();
continue;
}
if (myBuilder.getTokenType() == TheRTokenTypes.FUNCTION_KEYWORD) {
getFunctionParser().parseFunctionDeclaration();
continue;
}
if (!parseFormulaeExpression()) {
myBuilder.error(EXPRESSION_EXPECTED);
break;
}
skipNewLines();
}
skipNewLines();
checkMatches(TheRTokenTypes.RPAR, "')' expected");
arglist.done(TheRElementTypes.ARGUMENT_LIST);
}
private void parseReprExpression() {
LOG.assertTrue(myBuilder.getTokenType() == TheRTokenTypes.TICK);
final PsiBuilder.Marker expr = myBuilder.mark();
myBuilder.advanceLexer();
while (!atToken(TheRTokenTypes.TICK) && !myBuilder.eof()) {
myBuilder.advanceLexer();
}
checkMatches(TheRTokenTypes.TICK, "'`' (backtick) expected");
expr.done(TheRElementTypes.REPR_EXPRESSION);
}
private void parseParenthesizedExpression() {
final PsiBuilder.Marker expr = myBuilder.mark();
myBuilder.advanceLexer();
parseExpressionStatement();
checkMatches(TheRTokenTypes.RPAR, ") expected");
expr.done(TheRElementTypes.PARENTHESIZED_EXPRESSION);
}
public boolean parsePrimaryExpression() {
final IElementType firstToken = myBuilder.getTokenType();
if (firstToken == TheRTokenTypes.NUMERIC_LITERAL) {
buildTokenElement(TheRElementTypes.INTEGER_LITERAL_EXPRESSION, myBuilder);
return true;
}
else if (firstToken == TheRTokenTypes.INTEGER_LITERAL) {
buildTokenElement(TheRElementTypes.INTEGER_LITERAL_EXPRESSION, myBuilder);
return true;
}
else if (firstToken == TheRTokenTypes.COMPLEX_LITERAL) {
buildTokenElement(TheRElementTypes.IMAGINARY_LITERAL_EXPRESSION, myBuilder);
return true;
}
else if (firstToken == TheRTokenTypes.STRING_LITERAL) {
buildTokenElement(TheRElementTypes.STRING_LITERAL_EXPRESSION, myBuilder);
return true;
}
else if (firstToken == TheRTokenTypes.IDENTIFIER) {
buildTokenElement(TheRElementTypes.REFERENCE_EXPRESSION, myBuilder);
return true;
}
else if (TheRTokenTypes.NA_KEYWORDS.contains(firstToken)) {
buildTokenElement(TheRElementTypes.REFERENCE_EXPRESSION, myBuilder);
return true;
}
else if (TheRTokenTypes.SPECIAL_CONSTANTS.contains(firstToken)) {
buildTokenElement(TheRElementTypes.REFERENCE_EXPRESSION, myBuilder);
return true;
}
else if (firstToken == TheRTokenTypes.INFIX_OP) {
buildTokenElement(TheRElementTypes.OPERATOR_EXPRESSION, myBuilder);
return true;
}
else if (firstToken == TheRTokenTypes.TICK) {
parseReprExpression();
return true;
}
else if (firstToken == TheRTokenTypes.LPAR) {
parseParenthesizedExpression();
return true;
}
else if (firstToken == TheRTokenTypes.LBRACE) {
parseBlockExpression();
return true;
}
else {
myBuilder.advanceLexer();
}
return false;
}
} |
package org.pentaho.di.job.entries.unzip;
import static org.pentaho.di.job.entry.validator.AbstractFileValidator.putVariableSpace;
import static org.pentaho.di.job.entry.validator.AndValidator.putValidators;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.andValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.fileDoesNotExistValidator;
import static org.pentaho.di.job.entry.validator.JobEntryValidatorUtils.notBlankValidator;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.vfs.AllFileSelector;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSelectInfo;
import org.apache.commons.vfs.FileSystemException;
import org.apache.commons.vfs.FileType;
import org.apache.commons.vfs.VFS;
import org.pentaho.di.cluster.SlaveServer;
import org.pentaho.di.core.CheckResultInterface;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.Result;
import org.pentaho.di.core.ResultFile;
import org.pentaho.di.core.RowMetaAndData;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleDatabaseException;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.logging.LogWriter;
import org.pentaho.di.core.util.StringUtil;
import org.pentaho.di.core.vfs.KettleVFS;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entry.JobEntryBase;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.job.entry.validator.ValidatorContext;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.repository.ObjectId;
import org.w3c.dom.Node;
/**
* This defines a 'unzip' job entry. Its main use would be to
* unzip files in a directory
*
* @author Samatar Hassan
* @since 25-09-2007
*
*/
public class JobEntryUnZip extends JobEntryBase implements Cloneable, JobEntryInterface
{
private static Class<?> PKG = JobEntryUnZip.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private String zipFilename;
public int afterunzip;
private String wildcard;
private String wildcardexclude;
private String targetdirectory;
private String movetodirectory;
private boolean addfiletoresult;
private boolean isfromprevious;
private boolean adddate;
private boolean addtime;
private boolean SpecifyFormat;
private String date_time_format;
private boolean rootzip;
private boolean createfolder;
private String nr_limit;
private String wildcardSource;
private int iffileexist;
private boolean createMoveToDirectory;
public String SUCCESS_IF_AT_LEAST_X_FILES_UN_ZIPPED="success_when_at_least";
public String SUCCESS_IF_ERRORS_LESS="success_if_errors_less";
public String SUCCESS_IF_NO_ERRORS="success_if_no_errors";
private String success_condition;
public static final int IF_FILE_EXISTS_SKIP = 0;
public static final int IF_FILE_EXISTS_OVERWRITE = 1;
public static final int IF_FILE_EXISTS_UNIQ = 2;
public static final int IF_FILE_EXISTS_FAIL = 3;
public static final int IF_FILE_EXISTS_OVERWRITE_DIFF_SIZE = 4;
public static final int IF_FILE_EXISTS_OVERWRITE_EQUAL_SIZE = 5;
public static final int IF_FILE_EXISTS_OVERWRITE_ZIP_BIG = 6;
public static final int IF_FILE_EXISTS_OVERWRITE_ZIP_BIG_EQUAL = 7;
public static final int IF_FILE_EXISTS_OVERWRITE_ZIP_SMALL = 8;
public static final int IF_FILE_EXISTS_OVERWRITE_ZIP_SMALL_EQUAL = 9;
public static final String typeIfFileExistsCode[] = /* WARNING: DO NOT TRANSLATE THIS. */
{
"SKIP", "OVERWRITE", "UNIQ", "FAIL", "OVERWRITE_DIFF_SIZE",
"OVERWRITE_EQUAL_SIZE", "OVERWRITE_ZIP_BIG", "OVERWRITE_ZIP_BIG_EQUAL", "OVERWRITE_ZIP_BIG_SMALL",
"OVERWRITE_ZIP_BIG_SMALL_EQUAL",
};
public static final String typeIfFileExistsDesc[] =
{
BaseMessages.getString(PKG, "JobUnZip.Skip.Label"),
BaseMessages.getString(PKG, "JobUnZip.Overwrite.Label"),
BaseMessages.getString(PKG, "JobUnZip.Give_Unique_Name.Label"),
BaseMessages.getString(PKG, "JobUnZip.Fail.Label"),
BaseMessages.getString(PKG, "JobUnZip.OverwriteIfSizeDifferent.Label"),
BaseMessages.getString(PKG, "JobUnZip.OverwriteIfSizeEquals.Label"),
BaseMessages.getString(PKG, "JobUnZip.OverwriteIfZipBigger.Label"),
BaseMessages.getString(PKG, "JobUnZip.OverwriteIfZipBiggerOrEqual.Label"),
BaseMessages.getString(PKG, "JobUnZip.OverwriteIfZipSmaller.Label"),
BaseMessages.getString(PKG, "JobUnZip.OverwriteIfZipSmallerOrEqual.Label"),
};
private int NrErrors=0;
private int NrSuccess=0;
boolean successConditionBroken=false;
boolean successConditionBrokenExit=false;
int limitFiles=0;
public JobEntryUnZip(String n)
{
super(n, "");
zipFilename=null;
afterunzip=0;
wildcard=null;
wildcardexclude=null;
targetdirectory=null;
movetodirectory=null;
addfiletoresult = false;
isfromprevious = false;
adddate=false;
addtime=false;
SpecifyFormat=false;
rootzip=false;
createfolder=false;
nr_limit="10";
wildcardSource=null;
iffileexist=IF_FILE_EXISTS_SKIP;
success_condition=SUCCESS_IF_NO_ERRORS;
createMoveToDirectory=false;
setID(-1L);
}
public JobEntryUnZip()
{
this("");
}
public Object clone()
{
JobEntryUnZip je = (JobEntryUnZip) super.clone();
return je;
}
public String getXML()
{
StringBuffer retval = new StringBuffer(50);
retval.append(super.getXML());
retval.append(" ").append(XMLHandler.addTagValue("zipfilename", zipFilename));
retval.append(" ").append(XMLHandler.addTagValue("wildcard", wildcard));
retval.append(" ").append(XMLHandler.addTagValue("wildcardexclude", wildcardexclude));
retval.append(" ").append(XMLHandler.addTagValue("targetdirectory", targetdirectory));
retval.append(" ").append(XMLHandler.addTagValue("movetodirectory", movetodirectory));
retval.append(" ").append(XMLHandler.addTagValue("afterunzip", afterunzip));
retval.append(" ").append(XMLHandler.addTagValue("addfiletoresult", addfiletoresult));
retval.append(" ").append(XMLHandler.addTagValue("isfromprevious", isfromprevious));
retval.append(" ").append(XMLHandler.addTagValue("adddate", adddate));
retval.append(" ").append(XMLHandler.addTagValue("addtime", addtime));
retval.append(" ").append(XMLHandler.addTagValue("SpecifyFormat", SpecifyFormat));
retval.append(" ").append(XMLHandler.addTagValue("date_time_format", date_time_format));
retval.append(" ").append(XMLHandler.addTagValue("rootzip", rootzip));
retval.append(" ").append(XMLHandler.addTagValue("createfolder", createfolder));
retval.append(" ").append(XMLHandler.addTagValue("nr_limit", nr_limit));
retval.append(" ").append(XMLHandler.addTagValue("wildcardSource", wildcardSource));
retval.append(" ").append(XMLHandler.addTagValue("success_condition", success_condition));
retval.append(" ").append(XMLHandler.addTagValue("iffileexists", getIfFileExistsCode(iffileexist)));
retval.append(" ").append(XMLHandler.addTagValue("create_move_to_directory", createMoveToDirectory));
return retval.toString();
}
public void loadXML(Node entrynode, List<DatabaseMeta> databases, List<SlaveServer> slaveServers, Repository rep)
throws KettleXMLException
{
try
{
super.loadXML(entrynode, databases, slaveServers);
zipFilename = XMLHandler.getTagValue(entrynode, "zipfilename");
afterunzip = Const.toInt(XMLHandler.getTagValue(entrynode, "afterunzip"), -1);
wildcard = XMLHandler.getTagValue(entrynode, "wildcard");
wildcardexclude = XMLHandler.getTagValue(entrynode, "wildcardexclude");
targetdirectory = XMLHandler.getTagValue(entrynode, "targetdirectory");
movetodirectory = XMLHandler.getTagValue(entrynode, "movetodirectory");
addfiletoresult = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "addfiletoresult"));
isfromprevious = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "isfromprevious"));
adddate = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "adddate"));
addtime = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "addtime"));
SpecifyFormat = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "SpecifyFormat"));
date_time_format = XMLHandler.getTagValue(entrynode, "date_time_format");
rootzip = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "rootzip"));
createfolder = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "createfolder"));
nr_limit = XMLHandler.getTagValue(entrynode, "nr_limit");
wildcardSource = XMLHandler.getTagValue(entrynode, "wildcardSource");
success_condition = XMLHandler.getTagValue(entrynode, "success_condition");
if(Const.isEmpty(success_condition)) success_condition=SUCCESS_IF_NO_ERRORS;
iffileexist = getIfFileExistsInt(XMLHandler.getTagValue(entrynode, "iffileexists"));
createMoveToDirectory = "Y".equalsIgnoreCase(XMLHandler.getTagValue(entrynode, "create_move_to_directory"));
}
catch(KettleXMLException xe)
{
throw new KettleXMLException("Unable to load job entry of type 'unzip' from XML node", xe);
}
}
public void loadRep(Repository rep, ObjectId id_jobentry, List<DatabaseMeta> databases, List<SlaveServer> slaveServers) throws KettleException
{
try
{
zipFilename = rep.getJobEntryAttributeString(id_jobentry, "zipfilename");
afterunzip=(int) rep.getJobEntryAttributeInteger(id_jobentry, "afterunzip");
wildcard = rep.getJobEntryAttributeString(id_jobentry, "wildcard");
wildcardexclude = rep.getJobEntryAttributeString(id_jobentry, "wildcardexclude");
targetdirectory = rep.getJobEntryAttributeString(id_jobentry, "targetdirectory");
movetodirectory = rep.getJobEntryAttributeString(id_jobentry, "movetodirectory");
addfiletoresult=rep.getJobEntryAttributeBoolean(id_jobentry, "addfiletoresult");
isfromprevious=rep.getJobEntryAttributeBoolean(id_jobentry, "isfromprevious");
adddate=rep.getJobEntryAttributeBoolean(id_jobentry, "adddate");
addtime=rep.getJobEntryAttributeBoolean(id_jobentry, "adddate");
SpecifyFormat=rep.getJobEntryAttributeBoolean(id_jobentry, "SpecifyFormat");
date_time_format = rep.getJobEntryAttributeString(id_jobentry, "date_time_format");
rootzip=rep.getJobEntryAttributeBoolean(id_jobentry, "rootzip");
createfolder=rep.getJobEntryAttributeBoolean(id_jobentry, "createfolder");
nr_limit=rep.getJobEntryAttributeString(id_jobentry, "nr_limit");
wildcardSource=rep.getJobEntryAttributeString(id_jobentry, "wildcardSource");
success_condition = rep.getJobEntryAttributeString(id_jobentry, "success_condition");
if(Const.isEmpty(success_condition)) success_condition=SUCCESS_IF_NO_ERRORS;
iffileexist = getIfFileExistsInt(rep.getJobEntryAttributeString(id_jobentry,"iffileexists") );
createMoveToDirectory=rep.getJobEntryAttributeBoolean(id_jobentry, "create_move_to_directory");
}
catch(KettleException dbe)
{
throw new KettleException("Unable to load job entry of type 'unzip' from the repository for id_jobentry="+id_jobentry, dbe);
}
}
public void saveRep(Repository rep, ObjectId id_job)
throws KettleException
{
try
{
rep.saveJobEntryAttribute(id_job, getObjectId(), "zipfilename", zipFilename);
rep.saveJobEntryAttribute(id_job, getObjectId(), "afterunzip", afterunzip);
rep.saveJobEntryAttribute(id_job, getObjectId(), "wildcard", wildcard);
rep.saveJobEntryAttribute(id_job, getObjectId(), "wildcardexclude", wildcardexclude);
rep.saveJobEntryAttribute(id_job, getObjectId(), "targetdirectory", targetdirectory);
rep.saveJobEntryAttribute(id_job, getObjectId(), "movetodirectory", movetodirectory);
rep.saveJobEntryAttribute(id_job, getObjectId(), "addfiletoresult", addfiletoresult);
rep.saveJobEntryAttribute(id_job, getObjectId(), "isfromprevious", isfromprevious);
rep.saveJobEntryAttribute(id_job, getObjectId(), "addtime", addtime);
rep.saveJobEntryAttribute(id_job, getObjectId(), "adddate", adddate);
rep.saveJobEntryAttribute(id_job, getObjectId(), "SpecifyFormat", SpecifyFormat);
rep.saveJobEntryAttribute(id_job, getObjectId(), "date_time_format", date_time_format);
rep.saveJobEntryAttribute(id_job, getObjectId(), "rootzip", rootzip);
rep.saveJobEntryAttribute(id_job, getObjectId(), "createfolder", createfolder);
rep.saveJobEntryAttribute(id_job, getObjectId(), "nr_limit", nr_limit);
rep.saveJobEntryAttribute(id_job, getObjectId(), "wildcardSource", wildcardSource);
rep.saveJobEntryAttribute(id_job, getObjectId(), "success_condition", success_condition);
rep.saveJobEntryAttribute(id_job, getObjectId(), "iffileexists", getIfFileExistsCode(iffileexist));
rep.saveJobEntryAttribute(id_job, getObjectId(), "create_move_to_directory", createMoveToDirectory);
}
catch(KettleDatabaseException dbe)
{
throw new KettleException("Unable to save job entry of type 'unzip' to the repository for id_job="+id_job, dbe);
}
}
public Result execute(Result previousResult, int nr, Repository rep, Job parentJob)
{
LogWriter log = LogWriter.getInstance();
Result result = previousResult;
result.setResult( false );
result.setEntryNr(1);
List<RowMetaAndData> rows = result.getRows();
RowMetaAndData resultRow = null;
String realFilenameSource = environmentSubstitute(zipFilename);
String realWildcardSource = environmentSubstitute(wildcardSource);
String realWildcard = environmentSubstitute(wildcard);
String realWildcardExclude = environmentSubstitute(wildcardexclude);
String realTargetdirectory = environmentSubstitute(targetdirectory);
String realMovetodirectory = environmentSubstitute(movetodirectory);
limitFiles=Const.toInt(environmentSubstitute(getLimit()),10);
NrErrors=0;
NrSuccess=0;
successConditionBroken=false;
successConditionBrokenExit=false;
if(isfromprevious)
{
if(log.isDetailed())
log.logDetailed(toString(), BaseMessages.getString(PKG, "JobUnZip.Log.ArgFromPrevious.Found",(rows!=null?rows.size():0)+ ""));
if(rows.size()==0) return result;
}else
{
if(Const.isEmpty(zipFilename))
{
// Zip file/folder is missing
log.logError(toString(), BaseMessages.getString(PKG, "JobUnZip.No_ZipFile_Defined.Label"));
return result;
}
}
FileObject fileObject = null;
FileObject targetdir=null;
FileObject movetodir=null;
try
{
// Let's make some checks here, before running job entry ...
boolean exitjobentry=false;
// Target folder
targetdir = KettleVFS.getFileObject(realTargetdirectory);
if (!targetdir.exists())
{
if(createfolder)
{
targetdir.createFolder();
if(log.isDetailed()) log.logDetailed(toString(),BaseMessages.getString(PKG, "JobUnZip.Log.TargetFolderCreated",realTargetdirectory));
}else
{
log.logError(BaseMessages.getString(PKG, "JobUnZip.Error.Label"), BaseMessages.getString(PKG, "JobUnZip.TargetFolderNotFound.Label"));
exitjobentry=true;
}
}else{
if (!(targetdir.getType() == FileType.FOLDER))
{
log.logError(BaseMessages.getString(PKG, "JobUnZip.Error.Label"), BaseMessages.getString(PKG, "JobUnZip.TargetFolderNotFolder.Label",realTargetdirectory));
exitjobentry=true;
}else
{
if (log.isDetailed()) log.logDetailed(toString(),BaseMessages.getString(PKG, "JobUnZip.TargetFolderExists.Label",realTargetdirectory));
}
}
// If user want to move zip files after process
// movetodirectory must be provided
if(afterunzip==2)
{
if(Const.isEmpty(movetodirectory))
{
log.logError(BaseMessages.getString(PKG, "JobUnZip.Error.Label"), BaseMessages.getString(PKG, "JobUnZip.MoveToDirectoryEmpty.Label"));
exitjobentry=true;
}else
{
movetodir = KettleVFS.getFileObject(realMovetodirectory);
if (!(movetodir.exists()) || !(movetodir.getType() == FileType.FOLDER))
{
if(createMoveToDirectory)
{
movetodir.createFolder();
if(log.isDetailed()) log.logDetailed(toString(),BaseMessages.getString(PKG, "JobUnZip.Log.MoveToFolderCreated",realMovetodirectory));
}else
{
log.logError(BaseMessages.getString(PKG, "JobUnZip.Error.Label"), BaseMessages.getString(PKG, "JobUnZip.MoveToDirectoryNotExists.Label"));
exitjobentry=true;
}
}
}
}
// We found errors...now exit
if(exitjobentry) return result;
if(isfromprevious)
{
if (rows!=null) // Copy the input row to the (command line) arguments
{
for (int iteration=0;iteration<rows.size() && !parentJob.isStopped();iteration++)
{
if(successConditionBroken){
if(!successConditionBrokenExit){
log.logError(toString(), BaseMessages.getString(PKG, "JobUnZip.Error.SuccessConditionbroken",""+NrErrors));
successConditionBrokenExit=true;
}
result.setEntryNr(NrErrors);
return result;
}
resultRow = rows.get(iteration);
// Get sourcefile/folder and wildcard
realFilenameSource = resultRow.getString(0,null);
realWildcardSource = resultRow.getString(1,null);
fileObject = KettleVFS.getFileObject(realFilenameSource);
if(fileObject.exists())
{
processOneFile(log, result,parentJob,
fileObject,realTargetdirectory,
realWildcard,realWildcardExclude, movetodir,realMovetodirectory,
realWildcardSource);
}else
{
updateErrors();
log.logError(toString(), BaseMessages.getString(PKG, "JobUnZip.Error.CanNotFindFile", realFilenameSource));
}
}
}
}else{
fileObject = KettleVFS.getFileObject(realFilenameSource);
if (!fileObject.exists())
{
log.logError(BaseMessages.getString(PKG, "JobUnZip.Error.Label"), BaseMessages.getString(PKG, "JobUnZip.ZipFile.NotExists.Label",realFilenameSource));
return result;
}
if (log.isDetailed()) log.logDetailed(toString(),BaseMessages.getString(PKG, "JobUnZip.Zip_FileExists.Label",realFilenameSource));
if(Const.isEmpty(targetdirectory))
{
log.logError(BaseMessages.getString(PKG, "JobUnZip.Error.Label"), BaseMessages.getString(PKG, "JobUnZip.TargetFolderNotFound.Label"));
return result;
}
processOneFile(log, result,parentJob,
fileObject,realTargetdirectory,
realWildcard,realWildcardExclude, movetodir,realMovetodirectory,
realWildcardSource);
}
}
catch (Exception e)
{
log.logError(BaseMessages.getString(PKG, "JobUnZip.Error.Label"), BaseMessages.getString(PKG, "JobUnZip.ErrorUnzip.Label",realFilenameSource,e.getMessage()));
updateErrors();
}
finally
{
if ( fileObject != null ){
try{
fileObject.close();
}catch ( IOException ex ) {};
}
if ( targetdir != null ){
try{
targetdir.close();
}catch ( IOException ex ) {};
}
if ( movetodir != null ){
try{
movetodir.close();
}catch ( IOException ex ) {};
}
}
result.setNrErrors(NrErrors);
result.setNrLinesWritten(NrSuccess);
if(getSuccessStatus()) result.setResult(true);
displayResults(log);
return result;
}
private void displayResults(LogWriter log)
{
if(log.isDetailed()){
log.logDetailed(toString(), "=======================================");
log.logDetailed(toString(), BaseMessages.getString(PKG, "JobUnZip.Log.Info.FilesInError","" + NrErrors));
log.logDetailed(toString(), BaseMessages.getString(PKG, "JobUnZip.Log.Info.FilesInSuccess","" + NrSuccess));
log.logDetailed(toString(), "=======================================");
}
}
private boolean processOneFile(LogWriter log, Result result,Job parentJob,
FileObject fileObject,String realTargetdirectory,
String realWildcard,String realWildcardExclude, FileObject movetodir,String realMovetodirectory,
String realWildcardSource)
{
boolean retval=false;
try{
if(fileObject.getType().equals(FileType.FILE))
{
// We have to unzip one zip file
if(!unzipFile(log, fileObject, realTargetdirectory,realWildcard,
realWildcardExclude,result, parentJob, fileObject, movetodir,realMovetodirectory))
updateErrors();
else
updateSuccess();
}else
{
// Folder..let's see wildcard
FileObject[] children = fileObject.getChildren();
for (int i=0; i<children.length && !parentJob.isStopped(); i++)
{
if(successConditionBroken){
if(!successConditionBrokenExit){
log.logError(toString(), BaseMessages.getString(PKG, "JobUnZip.Error.SuccessConditionbroken",""+NrErrors));
successConditionBrokenExit=true;
}
return false;
}
// Get only file!
if (!children[i].getType().equals(FileType.FOLDER))
{
boolean unzip=true;
String filename=children[i].getName().getPath();
Pattern patternSource = null;
if (!Const.isEmpty(realWildcardSource))
patternSource = Pattern.compile(realWildcardSource);
// First see if the file matches the regular expression!
if (patternSource!=null)
{
Matcher matcher = patternSource.matcher(filename);
unzip = matcher.matches();
}
if(unzip)
{
if(!unzipFile(log,children[i],realTargetdirectory,realWildcard,
realWildcardExclude,result, parentJob, fileObject,movetodir,
realMovetodirectory))
updateErrors();
else
updateSuccess();
}
}
}
}
}catch(Exception e)
{
updateErrors();
log.logError(toString(), BaseMessages.getString(PKG, "JobUnZip.Error.Label",e.getMessage()));
}finally
{
if ( fileObject != null )
{
try {
fileObject.close();
}catch ( IOException ex ) {};
}
}
return retval;
}
private boolean unzipFile(LogWriter log, FileObject sourceFileObject, String realTargetdirectory, String realWildcard,
String realWildcardExclude, Result result, Job parentJob, FileObject fileObject, FileObject movetodir,
String realMovetodirectory)
{
boolean retval=false;
String unzipToFolder=realTargetdirectory;
try {
if(log.isDetailed()) log.logDetailed(toString(), BaseMessages.getString(PKG, "JobUnZip.Log.ProcessingFile",sourceFileObject.toString()));
// Do you create a root folder?
if(rootzip)
{
String shortSourceFilename = sourceFileObject.getName().getBaseName();
int lenstring=shortSourceFilename.length();
int lastindexOfDot=shortSourceFilename.lastIndexOf('.');
if(lastindexOfDot==-1) lastindexOfDot=lenstring;
String foldername=realTargetdirectory + "/" + shortSourceFilename.substring(0, lastindexOfDot);
FileObject rootfolder=KettleVFS.getFileObject(foldername);
if(!rootfolder.exists())
{
try {
rootfolder.createFolder();
if(log.isDetailed()) log.logDetailed(toString(), BaseMessages.getString(PKG, "JobUnZip.Log.RootFolderCreated",foldername));
} catch(Exception e) {
throw new Exception(BaseMessages.getString(PKG, "JobUnZip.Error.CanNotCreateRootFolder",foldername), e);
}
}
unzipToFolder=foldername;
}
// Try to read the entries from the VFS object...
String zipFilename = "zip:"+sourceFileObject.getName().getFriendlyURI();
FileObject zipFile = KettleVFS.getFileObject(zipFilename);
FileObject[] items = zipFile.findFiles(
new AllFileSelector()
{
public boolean traverseDescendents(FileSelectInfo info)
{
return true;
}
public boolean includeFile(FileSelectInfo info)
{
// Never return the parent directory of a file list.
if (info.getDepth() == 0) {
return false;
}
FileObject fileObject = info.getFile();
return fileObject!=null;
}
}
);
Pattern pattern = null;
if (!Const.isEmpty(realWildcard))
{
pattern = Pattern.compile(realWildcard);
}
Pattern patternexclude = null;
if (!Const.isEmpty(realWildcardExclude))
{
patternexclude = Pattern.compile(realWildcardExclude);
}
for (FileObject item : items) {
if(successConditionBroken){
if(!successConditionBrokenExit){
log.logError(toString(), BaseMessages.getString(PKG, "JobUnZip.Error.SuccessConditionbroken",""+NrErrors));
successConditionBrokenExit=true;
}
return false;
}
FileObject newFileObject=null;
try{
if(log.isDetailed()) log.logDetailed(toString(), BaseMessages.getString(PKG, "JobUnZip.Log.ProcessingZipEntry",item.getName().getURI(), sourceFileObject.toString()));
// get real destination filename
String newFileName = unzipToFolder + Const.FILE_SEPARATOR + getTargetFilename(item.getName().getPath());
newFileObject = KettleVFS.getFileObject(newFileName);
if( item.getType().equals(FileType.FOLDER))
{
// Directory
if(log.isDetailed()) log.logDetailed(toString(),BaseMessages.getString(PKG, "JobUnZip.CreatingDirectory.Label",newFileName));
// Create Directory if necessary ...
if(!newFileObject.exists()) newFileObject.createFolder();
}
else
{
// File
boolean getIt = true;
boolean getItexclude = false;
// First see if the file matches the regular expression!
if (pattern!=null)
{
Matcher matcher = pattern.matcher(item.getName().getURI());
getIt = matcher.matches();
}
if (patternexclude!=null)
{
Matcher matcherexclude = patternexclude.matcher(item.getName().getURI());
getItexclude = matcherexclude.matches();
}
boolean take=takeThisFile(log, item, newFileName);
if (getIt && !getItexclude && take)
{
if(log.isDetailed()) log.logDetailed(toString(),BaseMessages.getString(PKG, "JobUnZip.ExtractingEntry.Label",item.getName().getURI(),newFileName));
if(iffileexist==IF_FILE_EXISTS_UNIQ)
{
// Create file with unique name
int lenstring=newFileName.length();
int lastindexOfDot=newFileName.lastIndexOf('.');
if(lastindexOfDot==-1) lastindexOfDot=lenstring;
newFileName=newFileName.substring(0, lastindexOfDot)
+ StringUtil.getFormattedDateTimeNow(true)
+ newFileName.substring(lastindexOfDot, lenstring);
if(log.isDebug()) log.logDebug(toString(), BaseMessages.getString(PKG, "JobUnZip.Log.CreatingUniqFile",newFileName));
}
// See if the folder to the target file exists...
if (!newFileObject.getParent().exists()) {
newFileObject.getParent().createFolder(); // creates the whole path.
}
InputStream is = null;
OutputStream os = null;
try {
is = KettleVFS.getInputStream(item);
os = KettleVFS.getOutputStream(newFileObject, false);
if(is!=null)
{
byte[] buff=new byte[2048];
int len;
while((len=is.read(buff))>0)
{
os.write(buff,0,len);
}
// Add filename to result filenames
addFilenameToResultFilenames(result, parentJob, newFileName);
}
} finally {
if(is!=null) is.close();
if(os!=null) os.close();
}
}// end if take
}
} catch(Exception e)
{
updateErrors();
log.logError(toString(), BaseMessages.getString(PKG, "JobUnZip.Error.CanNotProcessZipEntry",item.getName().getURI(), sourceFileObject.toString()), e);
}
finally {
if(newFileObject!=null) {
try {
newFileObject.close(); }catch(Exception e){};// ignore this
}
// Close file object
// close() does not release resources!
VFS.getManager().closeFileSystem(item.getFileSystem());
if(items!=null) items=null;
}
}// End for
// Here gc() is explicitly called if e.g. createfile is used in the same
// job for the same file. The problem is that after creating the file the
// file object is not properly garbaged collected and thus the file cannot
// be deleted anymore. This is a known problem in the JVM.
//System.gc();
// Unzip done...
if (afterunzip==1)
{
// delete zip file
boolean deleted = fileObject.delete();
if ( ! deleted )
{
updateErrors();
log.logError(toString(), BaseMessages.getString(PKG, "JobUnZip.Cant_Delete_File.Label", sourceFileObject.toString()));
}
// File deleted
if(log.isDebug()) log.logDebug(toString(), BaseMessages.getString(PKG, "JobUnZip.File_Deleted.Label", sourceFileObject.toString()));
}
else if(afterunzip == 2)
{
FileObject destFile=null;
// Move File
try
{
String destinationFilename=movetodir+Const.FILE_SEPARATOR+ fileObject.getName().getBaseName();
destFile=KettleVFS.getFileObject(destinationFilename);
fileObject.moveTo(destFile);
// File moved
if(log.isDetailed()) log.logDetailed(toString(), BaseMessages.getString(PKG, "JobUnZip.Log.FileMovedTo",sourceFileObject.toString(),realMovetodirectory));
}
catch (Exception e)
{
updateErrors();
log.logError(toString(), BaseMessages.getString(PKG, "JobUnZip.Cant_Move_File.Label",sourceFileObject.toString(),realMovetodirectory,e.getMessage()));
}finally
{
if ( destFile != null ){
try{
destFile.close();
}catch ( IOException ex ) {};
}
}
}
retval=true;
}
catch (Exception e)
{
updateErrors();
log.logError(BaseMessages.getString(PKG, "JobUnZip.Error.Label"), BaseMessages.getString(PKG, "JobUnZip.ErrorUnzip.Label",sourceFileObject.toString(),e.getMessage()), e);
}
return retval;
}
private void addFilenameToResultFilenames(Result result, Job parentJob, String newfile) throws Exception
{
if (addfiletoresult)
{
// Add file to result files name
ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL , KettleVFS.getFileObject(newfile), parentJob.getJobname(), toString());
result.getResultFiles().put(resultFile.getFile().toString(), resultFile);
}
}
private void updateErrors()
{
NrErrors++;
if(checkIfSuccessConditionBroken())
{
// Success condition was broken
successConditionBroken=true;
}
}
private void updateSuccess()
{
NrSuccess++;
}
private boolean checkIfSuccessConditionBroken()
{
boolean retval=false;
if ((NrErrors>0 && getSuccessCondition().equals(SUCCESS_IF_NO_ERRORS))
|| (NrErrors>=limitFiles && getSuccessCondition().equals(SUCCESS_IF_ERRORS_LESS)))
{
retval=true;
}
return retval;
}
private boolean getSuccessStatus()
{
boolean retval=false;
if ((NrErrors==0 && getSuccessCondition().equals(SUCCESS_IF_NO_ERRORS))
|| (NrSuccess>=limitFiles && getSuccessCondition().equals(SUCCESS_IF_AT_LEAST_X_FILES_UN_ZIPPED))
|| (NrErrors<=limitFiles && getSuccessCondition().equals(SUCCESS_IF_ERRORS_LESS)))
{
retval=true;
}
return retval;
}
private boolean takeThisFile(LogWriter log, FileObject sourceFile, String destinationFile) throws FileSystemException
{
boolean retval=false;
File destination= new File(destinationFile);
if(!destination.exists())
{
if(log.isDebug()) log.logDebug(toString(), BaseMessages.getString(PKG, "JobUnZip.Log.CanNotFindFile",destinationFile));
return true;
}
if(log.isDebug()) log.logDebug(toString(), BaseMessages.getString(PKG, "JobUnZip.Log.FileExists",destinationFile));
if(iffileexist==IF_FILE_EXISTS_SKIP)
{
if(log.isDebug()) log.logDebug(toString(), BaseMessages.getString(PKG, "JobUnZip.Log.FileSkip",destinationFile));
return false;
}
if(iffileexist==IF_FILE_EXISTS_FAIL)
{
updateErrors();
log.logError(toString(), BaseMessages.getString(PKG, "JobUnZip.Log.FileError",destinationFile,""+NrErrors));
return false;
}
if(iffileexist==IF_FILE_EXISTS_OVERWRITE)
{
if(log.isDebug()) log.logDebug(toString(), BaseMessages.getString(PKG, "JobUnZip.Log.FileOverwrite",destinationFile));
return true;
}
Long entrySize=sourceFile.getContent().getSize();
Long destinationSize=destination.length();
if(iffileexist==IF_FILE_EXISTS_OVERWRITE_DIFF_SIZE)
{
if(entrySize!=destinationSize)
{
if(log.isDebug()) log.logDebug(toString(), BaseMessages.getString(PKG, "JobUnZip.Log.FileDiffSize.Diff",
sourceFile.getName().getURI(),""+entrySize,destinationFile,""+destinationSize));
return true;
}
else
{
if(log.isDebug()) log.logDebug(toString(), BaseMessages.getString(PKG, "JobUnZip.Log.FileDiffSize.Same",
sourceFile.getName().getURI(),""+entrySize,destinationFile,""+destinationSize));
return false;
}
}
if(iffileexist==IF_FILE_EXISTS_OVERWRITE_EQUAL_SIZE)
{
if(entrySize==destinationSize)
{
if(log.isDebug()) log.logDebug(toString(), BaseMessages.getString(PKG, "JobUnZip.Log.FileEqualSize.Same",
sourceFile.getName().getURI(),""+entrySize,destinationFile,""+destinationSize));
return true;
}
else
{
if(log.isDebug()) log.logDebug(toString(), BaseMessages.getString(PKG, "JobUnZip.Log.FileEqualSize.Diff",
sourceFile.getName().getURI(),""+entrySize,destinationFile,""+destinationSize));
return false;
}
}
if(iffileexist==IF_FILE_EXISTS_OVERWRITE_ZIP_BIG)
{
if(entrySize>destinationSize)
{
if(log.isDebug()) log.logDebug(toString(), BaseMessages.getString(PKG, "JobUnZip.Log.FileBigSize.Big",
sourceFile.getName().getURI(),""+entrySize,destinationFile,""+destinationSize));
return true;
}
else
{
if(log.isDebug()) log.logDebug(toString(), BaseMessages.getString(PKG, "JobUnZip.Log.FileBigSize.Small",
sourceFile.getName().getURI(),""+entrySize,destinationFile,""+destinationSize));
return false;
}
}
if(iffileexist==IF_FILE_EXISTS_OVERWRITE_ZIP_BIG_EQUAL)
{
if(entrySize>=destinationSize)
{
if(log.isDebug()) log.logDebug(toString(),
BaseMessages.getString(PKG, "JobUnZip.Log.FileBigEqualSize.Big",
sourceFile.getName().getURI(),""+entrySize,destinationFile,""+destinationSize));
return true;
}
else
{
if(log.isDebug()) log.logDebug(toString(),
BaseMessages.getString(PKG, "JobUnZip.Log.FileBigEqualSize.Small",
sourceFile.getName().getURI(),""+entrySize,destinationFile,""+destinationSize));
return false;
}
}
if(iffileexist==IF_FILE_EXISTS_OVERWRITE_ZIP_SMALL)
{
if(entrySize<destinationSize)
{
if(log.isDebug()) log.logDebug(toString(),
BaseMessages.getString(PKG, "JobUnZip.Log.FileSmallSize.Small",
sourceFile.getName().getURI(),""+entrySize,destinationFile,""+destinationSize));
return true;
}
else
{
if(log.isDebug()) log.logDebug(toString(),
BaseMessages.getString(PKG, "JobUnZip.Log.FileSmallSize.Big",
sourceFile.getName().getURI(),""+entrySize,destinationFile,""+destinationSize));
return false;
}
}
if(iffileexist==IF_FILE_EXISTS_OVERWRITE_ZIP_SMALL_EQUAL)
{
if(entrySize<=destinationSize)
{
if(log.isDebug()) log.logDebug(toString(),
BaseMessages.getString(PKG, "JobUnZip.Log.FileSmallEqualSize.Small",
sourceFile.getName().getURI(),""+entrySize,destinationFile,""+destinationSize));
return true;
}
else
{
if(log.isDebug()) log.logDebug(toString(),
BaseMessages.getString(PKG, "JobUnZip.Log.FileSmallEqualSize.Big",
sourceFile.getName().getURI(),""+entrySize,destinationFile,""+destinationSize));
return false;
}
}
if(iffileexist==IF_FILE_EXISTS_UNIQ)
{
// Create file with unique name
return true;
}
return retval;
}
public boolean evaluates()
{
return true;
}
public static final int getIfFileExistsInt(String desc)
{
for (int i=0;i<typeIfFileExistsCode.length;i++)
{
if (typeIfFileExistsCode[i].equalsIgnoreCase(desc)) return i;
}
return 0;
}
public static final String getIfFileExistsCode(int i)
{
if (i<0 || i>=typeIfFileExistsCode.length) return null;
return typeIfFileExistsCode[i];
}
/**
* @return Returns the iffileexist.
*/
public int getIfFileExist()
{
return iffileexist;
}
/**
* @param setIfFileExist The iffileexist to set.
*/
public void setIfFileExists(int iffileexist)
{
this.iffileexist = iffileexist;
}
public boolean isCreateMoveToDirectory()
{
return createMoveToDirectory;
}
public void setCreateMoveToDirectory(boolean createMoveToDirectory)
{
this.createMoveToDirectory=createMoveToDirectory;
}
public void setZipFilename(String zipFilename)
{
this.zipFilename = zipFilename;
}
public void setWildcard(String wildcard)
{
this.wildcard = wildcard;
}
public void setWildcardExclude(String wildcardexclude)
{
this.wildcardexclude = wildcardexclude;
}
public void setSourceDirectory(String targetdirectoryin)
{
this.targetdirectory = targetdirectoryin;
}
public void setMoveToDirectory(String movetodirectory)
{
this.movetodirectory = movetodirectory;
}
public String getSourceDirectory()
{
return targetdirectory;
}
public String getMoveToDirectory()
{
return movetodirectory;
}
public String getZipFilename()
{
return zipFilename;
}
public String getWildcardSource()
{
return wildcardSource;
}
public void setWildcardSource(String wildcardSource)
{
this.wildcardSource=wildcardSource;
}
public String getWildcard()
{
return wildcard;
}
public String getWildcardExclude()
{
return wildcardexclude;
}
public void setAddFileToResult(boolean addfiletoresultin)
{
this.addfiletoresult = addfiletoresultin;
}
public boolean isAddFileToResult()
{
return addfiletoresult;
}
public void setDateInFilename(boolean adddate)
{
this.adddate= adddate;
}
public boolean isDateInFilename()
{
return adddate;
}
public void setTimeInFilename(boolean addtime)
{
this.addtime= addtime;
}
public boolean isTimeInFilename()
{
return addtime;
}
public boolean isSpecifyFormat()
{
return SpecifyFormat;
}
public void setSpecifyFormat(boolean SpecifyFormat)
{
this.SpecifyFormat=SpecifyFormat;
}
public String getDateTimeFormat()
{
return date_time_format;
}
public void setDateTimeFormat(String date_time_format)
{
this.date_time_format=date_time_format;
}
public void setDatafromprevious(boolean isfromprevious)
{
this.isfromprevious = isfromprevious;
}
public boolean getDatafromprevious()
{
return isfromprevious;
}
public void setCreateRootFolder(boolean rootzip)
{
this.rootzip=rootzip;
}
public boolean isCreateRootFolder()
{
return rootzip;
}
public void setCreateFolder(boolean createfolder)
{
this.createfolder=createfolder;
}
public boolean isCreateFolder()
{
return createfolder;
}
public void setLimit(String nr_limitin)
{
this.nr_limit=nr_limitin;
}
public String getLimit()
{
return nr_limit;
}
public void setSuccessCondition(String success_condition)
{
this.success_condition=success_condition;
}
public String getSuccessCondition()
{
return success_condition;
}
/**
* @param string the filename from the FTP server
*
* @return the calculated target filename
*/
protected String getTargetFilename(String filename)
{
String retval="";
// Replace possible environment variables...
if(filename!=null) retval=filename;
int lenstring=retval.length();
int lastindexOfDot=retval.lastIndexOf('.');
if(lastindexOfDot==-1) lastindexOfDot=lenstring;
retval=retval.substring(0, lastindexOfDot);
SimpleDateFormat daf = new SimpleDateFormat();
Date now = new Date();
if(SpecifyFormat && !Const.isEmpty(date_time_format))
{
daf.applyPattern(date_time_format);
String dt = daf.format(now);
retval+=dt;
}else
{
if (adddate)
{
daf.applyPattern("yyyyMMdd");
String d = daf.format(now);
retval+="_"+d;
}
if (addtime)
{
daf.applyPattern("HHmmssSSS");
String t = daf.format(now);
retval+="_"+t;
}
}
retval+=filename.substring(lastindexOfDot, lenstring);
return retval;
}
@Override
public void check(List<CheckResultInterface> remarks, JobMeta jobMeta)
{
ValidatorContext ctx1 = new ValidatorContext();
putVariableSpace(ctx1, getVariables());
putValidators(ctx1, notBlankValidator(), fileDoesNotExistValidator());
andValidator().validate(this, "zipFilename", remarks, ctx1);//$NON-NLS-1$
if (2 == afterunzip) {
// setting says to move
andValidator().validate(this, "moveToDirectory", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$
}
andValidator().validate(this, "sourceDirectory", remarks, putValidators(notBlankValidator())); //$NON-NLS-1$
}
} |
package com.lassedissing.gamenight.messages;
import com.jme3.network.AbstractMessage;
import com.jme3.network.serializing.Serializable;
import com.lassedissing.gamenight.world.Chunk;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
@Serializable
public class ChunkMessage extends AbstractMessage {
private byte[] compressedData;
private int x;
private int z;
public ChunkMessage() {
}
public ChunkMessage(Chunk chunk) {
compressedData = compress(chunk.getRawArray());
x = chunk.getX();
z = chunk.getZ();
}
public Chunk getChunk() {
return new Chunk(x, z, decompress(compressedData));
}
private byte[] compress(int[] data) {
ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(16384);
DeflaterOutputStream deflater = new DeflaterOutputStream(byteOutputStream);
DataOutputStream out = new DataOutputStream(deflater);
int count = 0;
try {
for (int integer : data) {
out.writeInt(integer);
count++;
}
out.flush();
deflater.finish();
out.close();
deflater.close();
} catch (IOException e) {
e.printStackTrace();
}
return byteOutputStream.toByteArray();
}
private int[] decompress(byte[] data) {
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(data);
InflaterInputStream inflater = new InflaterInputStream(byteInputStream);
DataInputStream in = new DataInputStream(inflater);
int[] result = new int[Chunk.CHUNK_VOLUME];
int count = 0;
try {
for (int i = 0; i < Chunk.CHUNK_VOLUME; i++) {
result[i] = in.readInt();
count++;
}
in.close();
inflater.close();
} catch (IOException e) {
e.printStackTrace();
System.out.println("Partial chunk message!");
}
return result;
}
} |
package com.beolnix.marvin.im.plugin;
import com.beolnix.marvin.im.api.IMSessionManager;
import com.beolnix.marvin.im.api.model.IMIncomingMessage;
import com.beolnix.marvin.im.api.model.IMOutgoingMessage;
import com.beolnix.marvin.im.api.model.IMOutgoingMessageBuilder;
import com.beolnix.marvin.plugins.api.IMPlugin;
import com.beolnix.marvin.plugins.api.IMPluginState;
import org.apache.log4j.Logger;
import org.osgi.framework.BundleContext;
import java.util.Collections;
import java.util.List;
import java.util.Set;
public class EchoIMPlugin implements IMPlugin {
private Logger logger;
private IMSessionManager imSessionManager;
private IMPluginState state = IMPluginState.NOT_INITIALIZED;
private String errMsg = null;
public EchoIMPlugin(BundleContext bundleContext) {
logger = new PluginUtils().getLogger(bundleContext, getPluginName());
}
@Override
public String getPluginName() {
if (logger != null) {
logger.trace("getPluginName invoked");
}
return "echoPlugin";
}
@Override
public List<String> getCommandsList() {
return Collections.emptyList();
}
@Override
public boolean isCommandSupported(String s) {
return true;
}
@Override
public IMPluginState getPluginState() {
return state;
}
@Override
public boolean isProcessAll() {
return true;
}
@Override
public void process(IMIncomingMessage msg) {
IMOutgoingMessage outMsg = new IMOutgoingMessageBuilder(msg)
.withRecipient(msg.getAuthor())
.withRawMessageBody("pong for: " + msg.getRawMessageBody())
.withFromPlugin(getPluginName())
.build();
imSessionManager.sendMessage(outMsg);
}
@Override
public void setIMSessionManager(IMSessionManager imSessionManagerFacade) {
this.imSessionManager = imSessionManagerFacade;
this.state = IMPluginState.INITIALIZED;
}
@Override
public String getErrorDescription() {
return errMsg;
}
@Override
public Set<String> getSupportedProtocols() {
return Collections.emptySet();
}
@Override
public boolean isProtocolSupported(String protocol) {
return true;
}
@Override
public boolean isAllProtocolsSupported() {
return true;
}
} |
package org.jasig.cas.adaptors.x509.authentication.principal;
import java.security.cert.X509Certificate;
import org.jasig.cas.adaptors.x509.authentication.principal.X509CertificateCredentials;
import org.jasig.cas.adaptors.x509.authentication.principal.X509CertificateCredentialsToDistinguishedNamePrincipalResolver;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
public class X509CertificateCredentialsToDistinguishedNamePrincipalResolverTests
extends AbstractX509CertificateTests {
private X509CertificateCredentialsToDistinguishedNamePrincipalResolver resolver = new X509CertificateCredentialsToDistinguishedNamePrincipalResolver();
public void testResolvePrincipalInternal() {
final X509CertificateCredentials c = new X509CertificateCredentials(new X509Certificate[] {VALID_CERTIFICATE});
c.setCertificate(VALID_CERTIFICATE);
assertEquals(VALID_CERTIFICATE.getSubjectDN().getName(), this.resolver.resolvePrincipal(c).getId());
}
public void testSupport() {
final X509CertificateCredentials c = new X509CertificateCredentials(new X509Certificate[] {VALID_CERTIFICATE});
assertTrue(this.resolver.supports(c));
}
public void testSupportFalse() {
assertFalse(this.resolver.supports(new UsernamePasswordCredentials()));
}
} |
package com.mararok.epiccore.command;
import java.util.ArrayList;
import java.util.Collection;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.plugin.java.JavaPlugin;
public abstract class ParentPluginCommand<P extends JavaPlugin> extends ChildPluginCommand<P> {
private Collection<ChildPluginCommand<P>> children;
public ParentPluginCommand(P plugin) {
super(plugin);
children = new ArrayList<ChildPluginCommand<P>>();
}
protected void addCommand(ChildPluginCommand<P> command) {
command.setParent(this, children.size());
children.add(command);
}
@Override
protected boolean onCommand(CommandSender sender, CommandArguments<P> arguments) throws Exception {
if (arguments.isExists(0)) {
return execSubCommand(sender, arguments);
}
sendDescription(sender);
return true;
}
private boolean execSubCommand(CommandSender sender, CommandArguments<P> arguments) throws Exception {
String subCommandName = arguments.get(0).toLowerCase();
ChildPluginCommand<P> childCommand = getCommandByName(subCommandName);
if (childCommand != null) {
return childCommand.onCommand(sender, arguments.getArgumentsForChild(childCommand));
}
sender.sendMessage("Command: " + subCommandName + " not exists or not implemented yet");
return false;
}
protected ChildPluginCommand<P> getCommandByName(String name) {
for (ChildPluginCommand<P> child : children) {
if (child.getName() == name) {
return child;
}
}
return null;
}
@Override
protected void sendDescription(CommandSender sender) {
String[] subCommandsInfo = new String[children.size() + 1];
subCommandsInfo[0] = ChatColor.YELLOW + "" + ChatColor.BOLD + getDescription();
int i = 1;
for (PluginCommand<P> sub : children) {
subCommandsInfo[i] = sub.getName() + ChatColor.RESET + " - " + sub.getDescription();
++i;
}
sender.sendMessage(subCommandsInfo);
}
} |
package com.boulderalf.markdown2mm;
import generated.Html;
import generated.Map;
import generated.Richcontent;
import org.pegdown.ast.*;
import org.pegdown.ast.Node;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.parboiled.common.Preconditions.checkArgNotNull;
public class ToMmSerializer implements Visitor {
protected Stack<MmNodeWrapper> stack = new Stack<MmNodeWrapper>();
protected Map map = new Map();
protected StringBuilder currentStringBuilder = null;
protected StringBuilder mainStringBuilder = null;
protected Stack<Integer> currentNumberOfTableColumns = new Stack<Integer>();
public ToMmSerializer() {
map.setVersion("freeplane 1.3.0");
generated.Node node = createNode(0);
node.setTEXT("");
map.setNode(node);
}
public Map toMm(RootNode astRoot) {
currentStringBuilder = mainStringBuilder = new StringBuilder();
checkArgNotNull(astRoot, "astRoot");
astRoot.accept(this);
flushStringBuilderToCurrentNode();
return map;
}
@Override
public void visit(AbbreviationNode abbreviationNode) {
visitChildren(abbreviationNode);
}
@Override
public void visit(AutoLinkNode autoLinkNode) {
currentStringBuilder.append(autoLinkNode.getText());
}
@Override
public void visit(BlockQuoteNode blockQuoteNode) {
visitChildren(blockQuoteNode);
}
@Override
public void visit(BulletListNode bulletListNode) {
visitChildren(bulletListNode);
}
@Override
public void visit(CodeNode codeNode) {
currentStringBuilder.append("`");
currentStringBuilder.append(codeNode.getText());
currentStringBuilder.append("`");
}
@Override
public void visit(DefinitionListNode definitionListNode) {
visitChildren(definitionListNode);
}
@Override
public void visit(DefinitionNode definitionNode) {
visitChildren(definitionNode);
}
@Override
public void visit(DefinitionTermNode definitionTermNode) {
visitChildren(definitionTermNode);
}
@Override
public void visit(ExpImageNode expImageNode) {
visitChildren(expImageNode);
}
@Override
public void visit(ExpLinkNode expLinkNode) {
visitChildren(expLinkNode);
}
@Override
public void visit(HeaderNode headerNode) {
StringBuilder sb = new StringBuilder();
currentStringBuilder = sb;
visitChildren(headerNode);
currentStringBuilder = mainStringBuilder;
generated.Node node = createNode(headerNode.getLevel());
// strip off any existing leading heading numbers because we want to use Freeplane
// to number them correctly
String headingText = sb.toString();
Pattern r = Pattern.compile("([0-9\\.]* *(.*))");
Matcher m = r.matcher(headingText);
if (m.find()) {
headingText = m.group(2);
}
node.setTEXT(headingText);
}
@Override
public void visit(HtmlBlockNode htmlBlockNode) {
currentStringBuilder.append(htmlBlockNode.getText());
}
@Override
public void visit(InlineHtmlNode inlineHtmlNode) {
currentStringBuilder.append(inlineHtmlNode.getText());
}
@Override
public void visit(ListItemNode listItemNode) {
currentStringBuilder.append("* ");
visitChildren(listItemNode);
currentStringBuilder.append("\n");
}
@Override
public void visit(MailLinkNode mailLinkNode) {
currentStringBuilder.append(mailLinkNode.getText());
}
@Override
public void visit(OrderedListNode orderedListNode) {
visitChildren(orderedListNode);
}
@Override
public void visit(ParaNode paraNode) {
visitChildren(paraNode);
currentStringBuilder.append("\n\n");
}
@Override
public void visit(QuotedNode quotedNode) {
switch (quotedNode.getType()) {
case DoubleAngle:
case Double:
currentStringBuilder.append("\"");
visitChildren(quotedNode);
currentStringBuilder.append("\"");
break;
case Single:
currentStringBuilder.append("'");
visitChildren(quotedNode);
currentStringBuilder.append("'");
break;
}
}
@Override
public void visit(ReferenceNode referenceNode) {
visitChildren(referenceNode);
}
@Override
public void visit(RefImageNode refImageNode) {
visitChildren(refImageNode);
}
@Override
public void visit(RefLinkNode refLinkNode) {
visitChildren(refLinkNode);
}
@Override
public void visit(RootNode rootNode) {
visitChildren(rootNode);
}
@Override
public void visit(SimpleNode simpleNode) {
switch (simpleNode.getType()) {
case Apostrophe:
currentStringBuilder.append("'");
break;
case Ellipsis:
currentStringBuilder.append("...");
break;
case Emdash:
currentStringBuilder.append("-");
break;
case Endash:
currentStringBuilder.append("-");
break;
case HRule:
currentStringBuilder.append("
break;
case Linebreak:
currentStringBuilder.append("\n");
break;
case Nbsp:
currentStringBuilder.append(" ");
break;
default:
throw new IllegalStateException();
}
}
@Override
public void visit(SpecialTextNode specialTextNode) {
currentStringBuilder.append(specialTextNode.getText());
}
@Override
public void visit(StrikeNode strikeNode) {
visitChildren(strikeNode);
}
@Override
public void visit(StrongEmphSuperNode strongEmphSuperNode) {
if(strongEmphSuperNode.isClosed()){
if(strongEmphSuperNode.isStrong()) {
currentStringBuilder.append("**");
visitChildren(strongEmphSuperNode);
currentStringBuilder.append("**");
}
else {
currentStringBuilder.append("*");
visitChildren(strongEmphSuperNode);
currentStringBuilder.append("*");
}
} else {
//sequence was not closed, treat open chars as ordinary chars
currentStringBuilder.append(strongEmphSuperNode.getChars());
visitChildren(strongEmphSuperNode);
}
}
@Override
public void visit(TableBodyNode tableBodyNode) {
for (Node node : tableBodyNode.getChildren()) {
visit((TableRowNode)node);
}
}
@Override
public void visit(TableCaptionNode tableCaptionNode) {
visitChildren(tableCaptionNode);
}
@Override
public void visit(TableCellNode tableCellNode) {
visitChildren(tableCellNode);
}
@Override
public void visit(TableColumnNode tableColumnNode) {
}
@Override
public void visit(TableHeaderNode tableHeaderNode) {
TableRowNode trn = (TableRowNode)tableHeaderNode.getChildren().get(0);
visit(trn);
// create the header divider
boolean first = true;
for (Node col : trn.getChildren()) {
if (first) {
first = false;
}
else {
currentStringBuilder.append("|");
}
currentStringBuilder.append("
}
currentStringBuilder.append("\n");
}
@Override
public void visit(TableNode tableNode) {
currentNumberOfTableColumns.push(tableNode.getColumns().size());
visitChildren(tableNode);
currentNumberOfTableColumns.pop();
currentStringBuilder.append(" \n");
}
@Override
public void visit(TableRowNode tableRowNode) {
// create the header row
boolean first = true;
int columnCount = 0;
for (Node node : tableRowNode.getChildren()) {
columnCount += 1;
TableCellNode tcn = (TableCellNode) node;
if (first) {
first = false;
}
else {
currentStringBuilder.append("|");
}
visit(tcn);
}
// it is possible that not all table cells for this row have been populated. In that case
// we need to make sure we put extra separator characters at the end.
for (int i = columnCount; i < currentNumberOfTableColumns.peek(); i++) {
currentStringBuilder.append(" |");
}
currentStringBuilder.append("\n");
}
@Override
public void visit(VerbatimNode verbatimNode) {
currentStringBuilder.append(String.format("~~~%s\n",verbatimNode.getType()));
String text = verbatimNode.getText();
if (verbatimNode.getType().equalsIgnoreCase("xml")) {
text = prettyFormatXml(text,2);
text = text.replace("><", ">\n<");
}
currentStringBuilder.append(text);
currentStringBuilder.append("~~~\n\n");
}
@Override
public void visit(WikiLinkNode wikiLinkNode) {
currentStringBuilder.append(wikiLinkNode.getText());
}
@Override
public void visit(TextNode textNode) {
currentStringBuilder.append(textNode.getText());
}
@Override
public void visit(SuperNode superNode) {
visitChildren(superNode);
}
@Override
public void visit(Node node) {
}
// helpers
protected void visitChildren(SuperNode node) {
for (Node child : node.getChildren()) {
child.accept(this);
}
}
private void visitChildren(SimpleNode node) {
for (Node child : node.getChildren()) {
child.accept(this);
}
}
private generated.Node getCurrentNode() {
return stack.peek().getNode();
}
/**
* Creates a new node at level (level=0 is the root)
* @param level
* @return
*/
private generated.Node createNode(int level) {
// every time we encounter a header we also need to flush the contents of
// currentStringBuilder into a richContent
if (level > 0) {
flushStringBuilderToCurrentNode();
}
// first, adjust the stack so we get a suitable parent node
while (!stack.isEmpty() && (level <= stack.peek().getLevel())) {
stack.pop();
}
// then create a new node and make it a child of the currentNode()...
generated.Node newNode = new generated.Node();
if (level > 0) {
getCurrentNode().getArrowlinkOrCloudOrEdge().add(newNode);
}
// finally push the newNode onto the stack.
stack.push(new MmNodeWrapper(newNode, level));
return newNode;
}
/**
* flushes the contents of currentStringBuilder into currentNode()
*/
private void flushStringBuilderToCurrentNode() {
Html html = new Html();
html.getAny().add(buildHtmlForNode(currentStringBuilder.toString()));
mainStringBuilder = currentStringBuilder = new StringBuilder();
Richcontent richcontent = new Richcontent();
richcontent.setHtml(html);
richcontent.setTYPE("DETAILS");
richcontent.setHIDDEN("true");
getCurrentNode().getArrowlinkOrCloudOrEdge().add(richcontent);
}
/**
* builds an Element that contains text as a paragraph element
* @param text
*/
private Element buildHtmlForNode(String text) {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
Element body = null;
try {
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.newDocument();
// Create from whole cloth
body = (Element) document.createElement("body");
document.appendChild(body);
for (String line : text.split("\n")) {
Element p = (Element) body.appendChild(document.createElement("p") );
p.appendChild(document.createTextNode(line));
}
} catch (ParserConfigurationException pce) {
// Parser with specified options can't be built
pce.printStackTrace();
}
return body;
}
public void addEntityReferences(org.w3c.dom.Node node) {
int type = node.getNodeType();
if (type == org.w3c.dom.Node.TEXT_NODE) {
// the only type with attributes
Text text = (Text) node;
String s = text.getNodeValue();
int nbsp = s.indexOf('\u00A0'); // finds the first A0
if (nbsp != -1) {
Text middle = text.splitText(nbsp);
Text end = middle.splitText(1);
org.w3c.dom.Node parent = text.getParentNode();
Document factory = text.getOwnerDocument();
EntityReference ref = factory.createEntityReference("nbsp");
parent.replaceChild(ref, middle);
addEntityReferences(end); // finds any subsequent A0s
// System.out.println("Added");
}
} // end if
else if (node.hasChildNodes()) {
NodeList children = node.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
org.w3c.dom.Node child = children.item(i);
addEntityReferences(child);
} // end for
} // end if
} // end addEntityReferences()
public String prettyFormatXml(String input, int indent) {
try {
Source xmlInput = new StreamSource(new StringReader(input));
StringWriter stringWriter = new StringWriter();
StreamResult xmlOutput = new StreamResult(stringWriter);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
transformerFactory.setAttribute("indent-number", indent);
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.transform(xmlInput, xmlOutput);
return xmlOutput.getWriter().toString();
} catch (Exception e) {
throw new RuntimeException(e); // simple exception handling, please review it
}
}
} |
package se.jiderhamn.classloader.leak.prevention.cleanup;
import java.lang.management.ManagementFactory;
import java.lang.management.PlatformManagedObject;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Set;
import javax.management.*;
import se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor;
import se.jiderhamn.classloader.leak.prevention.ClassLoaderPreMortemCleanUp;
/**
* Unregister MBeans, MXBean {@link NotificationListener}s/{@link NotificationFilter}s/handbacks loaded by the
* protected class loader
* @author Mattias Jiderhamn
*/
public class MXBeanNotificationListenersCleanUp implements ClassLoaderPreMortemCleanUp {
@Override
public void cleanUp(ClassLoaderLeakPreventor preventor) {
final Class<?> notificationEmitterSupportClass = preventor.findClass("sun.management.NotificationEmitterSupport");
final Field listenerListField = preventor.findField(notificationEmitterSupportClass, "listenerList");
final Class<?> listenerInfoClass = preventor.findClass("sun.management.NotificationEmitterSupport$ListenerInfo");
final Field listenerField = preventor.findField(listenerInfoClass, "listener");
final Field filterField = preventor.findField(listenerInfoClass, "filter");
final Field handbackField = preventor.findField(listenerInfoClass, "handback");
final Class<?> listenerWrapperClass = preventor.findClass("com.sun.jmx.interceptor.DefaultMBeanServerInterceptor$ListenerWrapper");
final boolean canProcessNotificationEmitterSupport = listenerListField != null && listenerInfoClass != null && listenerField != null && filterField != null && handbackField != null;
if (!canProcessNotificationEmitterSupport) {
preventor.warn("Unable to unregister NotificationEmitterSupport listeners, because details could not be found using reflection");
}
final Set<Class<? extends PlatformManagedObject>> platformInterfaces = ManagementFactory.getPlatformManagementInterfaces();
if (platformInterfaces != null) {
for (Class<? extends PlatformManagedObject> platformInterface : platformInterfaces) {
for (Object mxBean : ManagementFactory.getPlatformMXBeans(platformInterface)) {
if (mxBean instanceof NotificationEmitter) { // The MXBean may have NotificationListeners
if (canProcessNotificationEmitterSupport && notificationEmitterSupportClass.isAssignableFrom(mxBean.getClass())) {
final List<? /* NotificationEmitterSupport.ListenerInfo */> listenerList = preventor.getFieldValue(listenerListField, mxBean);
if (listenerList != null) {
for (Object listenerInfo : listenerList) { // Loop all listeners
final NotificationListener listener = preventor.getFieldValue(listenerField, listenerInfo);
final NotificationListener rawListener = unwrap(preventor, listenerWrapperClass, listener);
final NotificationFilter filter = preventor.getFieldValue(filterField, listenerInfo);
final Object handback = preventor.getFieldValue(handbackField, listenerInfo);
if (preventor.isLoadedInClassLoader(rawListener) || preventor.isLoadedInClassLoader(filter) || preventor.isLoadedInClassLoader(handback)) {
preventor.warn(((listener == rawListener) ? "Listener '" : "Wrapped listener '") + listener +
"' (or its filter or handback) of MXBean " + mxBean +
" of PlatformManagedObject " + platformInterface + " was loaded in protected ClassLoader; removing");
// This is safe, as the implementation (as of this writing) works with a copy,
// not altering the original
try {
((NotificationEmitter) mxBean).removeNotificationListener(listener, filter, handback);
}
catch (ListenerNotFoundException e) { // Should never happen
preventor.error(e);
}
}
}
}
}
else if(mxBean instanceof NotificationBroadcasterSupport) { // Unlikely case
unregisterNotificationListeners(preventor, (NotificationBroadcasterSupport) mxBean, listenerWrapperClass);
}
}
}
}
}
}
/**
* Unregister {@link NotificationListener}s from subclass of {@link NotificationBroadcasterSupport}, if listener,
* filter or handback is loaded by the protected ClassLoader.
*/
protected void unregisterNotificationListeners(ClassLoaderLeakPreventor preventor, NotificationBroadcasterSupport mBean,
final Class<?> listenerWrapperClass) {
final Field listenerListField = preventor.findField(NotificationBroadcasterSupport.class, "listenerList");
if(listenerListField != null) {
final Class<?> listenerInfoClass = preventor.findClass("javax.management.NotificationBroadcasterSupport$ListenerInfo");
final List<? /*javax.management.NotificationBroadcasterSupport.ListenerInfo*/> listenerList =
preventor.getFieldValue(listenerListField, mBean);
if(listenerList != null) {
final Field listenerField = preventor.findField(listenerInfoClass, "listener");
final Field filterField = preventor.findField(listenerInfoClass, "filter");
final Field handbackField = preventor.findField(listenerInfoClass, "handback");
for(Object listenerInfo : listenerList) {
final NotificationListener listener = preventor.getFieldValue(listenerField, listenerInfo);
final NotificationListener rawListener = unwrap(preventor, listenerWrapperClass, listener);
final NotificationFilter filter = preventor.getFieldValue(filterField, listenerInfo);
final Object handback = preventor.getFieldValue(handbackField, listenerInfo);
if(preventor.isLoadedInClassLoader(rawListener) || preventor.isLoadedInClassLoader(filter) || preventor.isLoadedInClassLoader(handback)) {
preventor.warn(((listener == rawListener) ? "Listener '" : "Wrapped listener '") + listener +
"' (or its filter or handback) of MBean " + mBean +
" was loaded in protected ClassLoader; removing");
// This is safe, as the implementation works with a copy, not altering the original
try {
mBean.removeNotificationListener(listener, filter, handback);
}
catch (ListenerNotFoundException e) { // Should never happen
preventor.error(e);
}
}
}
}
}
}
/** Unwrap {@link NotificationListener} wrapped by {@link com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.ListenerWrapper} */
private NotificationListener unwrap(ClassLoaderLeakPreventor preventor, Class<?> listenerWrapperClass, NotificationListener listener) {
if(listenerWrapperClass != null && listenerWrapperClass.isInstance(listener)) {
return preventor.getFieldValue(listener, "listener"); // Unwrap
}
else
return listener;
}
} |
package som.interpreter.actors;
import java.util.ArrayList;
import som.vm.NotYetImplementedException;
import som.vm.Symbols;
import som.vmobjects.SAbstractObject;
import som.vmobjects.SBlock;
import som.vmobjects.SClass;
import som.vmobjects.SObjectWithoutFields;
import som.vmobjects.SSymbol;
import com.oracle.truffle.api.CompilerAsserts;
import com.oracle.truffle.api.CompilerDirectives.CompilationFinal;
import com.sun.istack.internal.NotNull;
public final class SPromise extends SObjectWithoutFields {
@CompilationFinal private static SClass promiseClass;
// THREAD-SAFETY: these fields are subject to race conditions and should only
// be accessed when under the SPromise(this) lock
// currently, we minimize locking by first setting the result
// value and resolved flag, and then release the lock again
// this makes sure that the promise owner directly schedules
// call backs, and does not block the resolver to schedule
// call backs here either. After resolving the future,
// whenResolved and whenBroken should only be accessed by the
// resolver actor
private ArrayList<Object> whenResolved;
private ArrayList<SResolver> whenResolvedResolvers;
private ArrayList<SBlock> onError;
private ArrayList<SResolver> onErrorResolvers;
private ArrayList<SClass> onException;
private ArrayList<SBlock> onExceptionCallbacks;
private ArrayList<SResolver> onExceptionResolvers;
private ArrayList<SPromise> chainedPromises;
private Object value;
private boolean resolved;
private boolean errored;
private boolean chained;
// the owner of this promise, on which all call backs are scheduled
private final Actor owner;
public SPromise(@NotNull final Actor owner) {
super(promiseClass);
assert owner != null;
this.owner = owner;
resolved = false;
assert promiseClass != null;
}
@Override
public boolean isValue() {
return false;
}
public static void setSOMClass(final SClass cls) {
assert promiseClass == null || cls == null;
promiseClass = cls;
}
public SPromise whenResolved(final SBlock block) {
assert block.getMethod().getNumberOfArguments() == 2;
SPromise promise = new SPromise(EventualMessage.getActorCurrentMessageIsExecutionOn());
SResolver resolver = new SResolver(promise);
registerWhenResolved(block, resolver);
return promise;
}
public SPromise whenResolved(final SSymbol selector, final Object[] args) {
SPromise promise = new SPromise(EventualMessage.getActorCurrentMessageIsExecutionOn());
SResolver resolver = new SResolver(promise);
assert owner == EventualMessage.getActorCurrentMessageIsExecutionOn() : "think this should be true because the promise is an Object and owned by this specific actor";
EventualMessage msg = new EventualMessage(owner, selector, args, resolver);
registerWhenResolved(msg, resolver);
return promise;
}
public SPromise onError(final SBlock block) {
assert block.getMethod().getNumberOfArguments() == 2;
SPromise promise = new SPromise(EventualMessage.getActorCurrentMessageIsExecutionOn());
SResolver resolver = new SResolver(promise);
registerOnError(block, resolver);
return promise;
}
public SPromise whenResolvedOrError(final SBlock resolved, final SBlock error) {
assert resolved.getMethod().getNumberOfArguments() == 2;
assert error.getMethod().getNumberOfArguments() == 2;
SPromise promise = new SPromise(EventualMessage.getActorCurrentMessageIsExecutionOn());
SResolver resolver = new SResolver(promise);
synchronized (this) {
registerWhenResolved(resolved, resolver);
registerOnError(error, resolver);
}
return promise;
}
private synchronized void registerWhenResolved(final Object callbackOrMsg,
final SResolver resolver) {
if (resolved) {
scheduleCallback(value, callbackOrMsg, resolver);
} else {
if (errored) { // short cut, this promise will never be resolved
return;
}
if (whenResolved == null) {
whenResolved = new ArrayList<>(2);
whenResolvedResolvers = new ArrayList<>(2);
}
whenResolved.add(callbackOrMsg);
whenResolvedResolvers.add(resolver);
}
}
private synchronized void registerOnError(final SBlock block,
final SResolver resolver) {
if (errored) {
scheduleCallback(value, block, resolver);
} else {
if (resolved) { // short cut, this promise will never error, so, just return promise
return;
}
if (onError == null) {
onError = new ArrayList<>(1);
onErrorResolvers = new ArrayList<>(1);
}
onError.add(block);
onErrorResolvers.add(resolver);
}
}
public SPromise onException(final SClass exceptionClass, final SBlock block) {
assert block.getMethod().getNumberOfArguments() == 2;
SPromise promise = new SPromise(EventualMessage.getActorCurrentMessageIsExecutionOn());
SResolver resolver = new SResolver(promise);
synchronized (this) {
if (errored) {
if (value instanceof SAbstractObject) {
if (((SAbstractObject) value).getSOMClass() == exceptionClass) {
scheduleCallback(value, block, resolver);
}
}
} else {
if (resolved) { // short cut, this promise will never error, so, just return promise
return promise;
}
if (onException == null) {
onException = new ArrayList<>(1);
onExceptionResolvers = new ArrayList<>(1);
onExceptionCallbacks = new ArrayList<>(1);
}
onException.add(exceptionClass);
onExceptionCallbacks.add(block);
onExceptionResolvers.add(resolver);
}
}
return promise;
}
protected void scheduleCallback(final Object result,
final Object callbackOrMsg, final SResolver resolver) {
assert owner != null;
EventualMessage msg;
Actor target;
if (callbackOrMsg instanceof SBlock) {
SBlock callback = (SBlock) callbackOrMsg;
msg = new EventualMessage(owner, SResolver.valueSelector,
new Object[] {callback, result}, resolver);
target = owner;
} else {
assert callbackOrMsg instanceof EventualMessage;
msg = (EventualMessage) callbackOrMsg;
Actor sendingActor = msg.getTarget();
assert sendingActor != null;
if (result instanceof SFarReference) {
target = ((SFarReference) result).getActor();
} else {
target = EventualMessage.getActorCurrentMessageIsExecutionOn();
}
msg.setReceiverForEventualPromiseSend(result, target, sendingActor);
}
target.enqueueMessage(msg);
}
public synchronized void addChainedPromise(@NotNull final SPromise promise) {
assert promise != null;
if (chainedPromises == null) {
chainedPromises = new ArrayList<>(1);
}
chainedPromises.add(promise);
}
public static final class SResolver extends SObjectWithoutFields {
@CompilationFinal private static SClass resolverClass;
private final SPromise promise;
private static final SSymbol valueSelector = Symbols.symbolFor("value:");
public SResolver(final SPromise promise) {
super(resolverClass);
this.promise = promise;
assert resolverClass != null;
}
@Override
public boolean isValue() {
return true;
}
public static void setSOMClass(final SClass cls) {
assert resolverClass == null || cls == null;
resolverClass = cls;
}
public void onError() {
throw new NotYetImplementedException(); // TODO: implement
}
public void resolve(Object result) {
CompilerAsserts.neverPartOfCompilation("This has so many possible cases, we definitely want to optimize this");
assert promise.value == null;
assert !promise.resolved;
assert !promise.errored;
assert !promise.chained;
if (result == promise) {
// TODO: figure out whether this case is relevant
return; // this might happen at least in AmbientTalk, but doesn't do anything
}
// actors should have always direct access to their own objects and
// thus, far references need to be unwrapped if they are returned back
// to the owner
// if a reference is delivered to another actor, it needs to be wrapped
// in a far reference
result = promise.owner.wrapForUse(result, EventualMessage.getActorCurrentMessageIsExecutionOn());
if (result instanceof SPromise) {
synchronized (promise) {
promise.chained = true;
((SPromise) result).addChainedPromise(promise);
}
return;
}
assert !(result instanceof SFarReference);
assert !(result instanceof SPromise);
synchronized (promise) {
promise.value = result;
promise.resolved = true;
scheduleAll(promise, result);
resolveChainedPromises(promise, result);
}
}
protected static void resolveChainedPromises(final SPromise promise,
final Object result) {
// TODO: we should change the implementation of chained promises to
// always move all the handlers to the other promise, then we
// don't need to worry about traversing the chain, which can
// lead to a stack overflow.
// TODO: restore 10000 as parameter in testAsyncDeeplyChainedResolution
if (promise.chainedPromises != null) {
for (SPromise p : promise.chainedPromises) {
scheduleAll(p, result);
resolveChainedPromises(p, result);
}
}
}
protected static void scheduleAll(final SPromise promise, final Object result) {
if (promise.whenResolved != null) {
for (int i = 0; i < promise.whenResolved.size(); i++) {
Object callbackOrMsg = promise.whenResolved.get(i);
SResolver resolver = promise.whenResolvedResolvers.get(i);
promise.scheduleCallback(result, callbackOrMsg, resolver);
}
}
}
}
@CompilationFinal public static SClass pairClass;
public static void setPairClass(final SClass cls) {
assert pairClass == null || cls == null;
pairClass = cls;
}
} |
package com.jme3.terrain.geomipmap;
import com.jme3.export.JmeExporter;
import com.jme3.export.JmeImporter;
import com.jme3.math.FastMath;
import com.jme3.math.Triangle;
import com.jme3.math.Vector2f;
import com.jme3.math.Vector3f;
import com.jme3.scene.Mesh;
import com.jme3.scene.Mesh.Mode;
import com.jme3.scene.VertexBuffer.Type;
import com.jme3.terrain.GeoMap;
import com.jme3.util.BufferUtils;
import com.jme3.util.TempVars;
import java.io.IOException;
import java.nio.BufferOverflowException;
import java.nio.BufferUnderflowException;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
/**
* Produces the mesh for the TerrainPatch.
* This LOD algorithm generates a single triangle strip by first building the center of the
* mesh, minus one outer edge around it. Then it builds the edges in counter-clockwise order,
* starting at the bottom right and working up, then left across the top, then down across the
* left, then right across the bottom.
* It needs to know what its neighbour's LOD's are so it can stitch the edges.
* It creates degenerate polygons in order to keep the winding order of the polygons and to move
* the strip to a new position while still maintaining the continuity of the overall mesh. These
* degenerates are removed quickly by the video card.
*
* @author Brent Owens
*/
public class LODGeomap extends GeoMap {
public LODGeomap() {
}
@Deprecated
public LODGeomap(int size, FloatBuffer heightMap) {
super(heightMap, size, size, 1);
}
public LODGeomap(int size, float[] heightMap) {
super(heightMap, size, size, 1);
}
public Mesh createMesh(Vector3f scale, Vector2f tcScale, Vector2f tcOffset, float offsetAmount, int totalSize, boolean center) {
return this.createMesh(scale, tcScale, tcOffset, offsetAmount, totalSize, center, 1, false, false, false, false);
}
public Mesh createMesh(Vector3f scale, Vector2f tcScale, Vector2f tcOffset, float offsetAmount, int totalSize, boolean center, int lod, boolean rightLod, boolean topLod, boolean leftLod, boolean bottomLod) {
FloatBuffer pb = writeVertexArray(null, scale, center);
FloatBuffer texb = writeTexCoordArray(null, tcOffset, tcScale, offsetAmount, totalSize);
FloatBuffer nb = writeNormalArray(null, scale);
IntBuffer ib = writeIndexArrayLodDiff(null, lod, rightLod, topLod, leftLod, bottomLod);
FloatBuffer bb = BufferUtils.createFloatBuffer(getWidth() * getHeight() * 3);
FloatBuffer tanb = BufferUtils.createFloatBuffer(getWidth() * getHeight() * 3);
writeTangentArray(tanb, bb, texb, scale);
Mesh m = new Mesh();
m.setMode(Mode.TriangleStrip);
m.setBuffer(Type.Position, 3, pb);
m.setBuffer(Type.Normal, 3, nb);
m.setBuffer(Type.Tangent, 3, tanb);
m.setBuffer(Type.Binormal, 3, bb);
m.setBuffer(Type.TexCoord, 2, texb);
m.setBuffer(Type.Index, 3, ib);
m.setStatic();
m.updateBound();
return m;
}
public FloatBuffer writeTexCoordArray(FloatBuffer store, Vector2f offset, Vector2f scale, float offsetAmount, int totalSize) {
if (store != null) {
if (store.remaining() < getWidth() * getHeight() * 2) {
throw new BufferUnderflowException();
}
} else {
store = BufferUtils.createFloatBuffer(getWidth() * getHeight() * 2);
}
if (offset == null) {
offset = new Vector2f();
}
Vector2f tcStore = new Vector2f();
// work from bottom of heightmap up, so we don't flip the coords
for (int y = getHeight() - 1; y >= 0; y
for (int x = 0; x < getWidth(); x++) {
getUV(x, y, tcStore, offset, offsetAmount, totalSize);
float tx = tcStore.x * scale.x;
float ty = tcStore.y * scale.y;
store.put(tx);
store.put(ty);
}
}
return store;
}
public Vector2f getUV(int x, int y, Vector2f store, Vector2f offset, float offsetAmount, int totalSize) {
float offsetX = offset.x + (offsetAmount * 1.0f);
float offsetY = -offset.y + (offsetAmount * 1.0f);//note the -, we flip the tex coords
store.set((((float) x) + offsetX) / (float) (totalSize - 1), // calculates percentage of texture here
(((float) y) + offsetY) / (float) (totalSize - 1));
return store;
}
/**
* Create the LOD index array that will seam its edges with its neighbour's LOD.
* This is a scary method!!! It will break your mind.
*
* @param store to store the index buffer
* @param lod level of detail of the mesh
* @param rightLod LOD of the right neighbour
* @param topLod LOD of the top neighbour
* @param leftLod LOD of the left neighbour
* @param bottomLod LOD of the bottom neighbour
* @return the LOD-ified index buffer
*/
public IntBuffer writeIndexArrayLodDiff(IntBuffer store, int lod, boolean rightLod, boolean topLod, boolean leftLod, boolean bottomLod) {
IntBuffer buffer2 = store;
int numIndexes = calculateNumIndexesLodDiff(lod);
if (store == null) {
buffer2 = BufferUtils.createIntBuffer(numIndexes);
}
VerboseIntBuffer buffer = new VerboseIntBuffer(buffer2);
// generate center squares minus the edges
//System.out.println("for (x="+lod+"; x<"+(getWidth()-(2*lod))+"; x+="+lod+")");
//System.out.println(" for (z="+lod+"; z<"+(getWidth()-(1*lod))+"; z+="+lod+")");
for (int r = lod; r < getWidth() - (2 * lod); r += lod) { // row
int rowIdx = r * getWidth();
int nextRowIdx = (r + 1 * lod) * getWidth();
for (int c = lod; c < getWidth() - (1 * lod); c += lod) { // column
int idx = rowIdx + c;
buffer.put(idx);
idx = nextRowIdx + c;
buffer.put(idx);
}
// add degenerate triangles
if (r < getWidth() - (3 * lod)) {
int idx = nextRowIdx + getWidth() - (1 * lod) - 1;
buffer.put(idx);
idx = nextRowIdx + (1 * lod); // inset by 1
buffer.put(idx);
//System.out.println("");
}
}
//System.out.println("\nright:");
//int runningBufferCount = buffer.getCount();
//System.out.println("buffer start: "+runningBufferCount);
// right
int br = getWidth() * (getWidth() - lod) - 1 - lod;
buffer.put(br); // bottom right -1
int corner = getWidth() * getWidth() - 1;
buffer.put(corner); // bottom right corner
if (rightLod) { // if lower LOD
for (int row = getWidth() - lod; row >= 1 + lod; row -= 2 * lod) {
int idx = (row) * getWidth() - 1 - lod;
buffer.put(idx);
idx = (row - lod) * getWidth() - 1;
buffer.put(idx);
if (row > lod + 1) { //if not the last one
idx = (row - lod) * getWidth() - 1 - lod;
buffer.put(idx);
idx = (row - lod) * getWidth() - 1;
buffer.put(idx);
} else {
}
}
} else {
buffer.put(corner);//br+1);//degenerate to flip winding order
for (int row = getWidth() - lod; row > lod; row -= lod) {
int idx = row * getWidth() - 1; // mult to get row
buffer.put(idx);
buffer.put(idx - lod);
}
}
buffer.put(getWidth() - 1);
//System.out.println("\nbuffer right: "+(buffer.getCount()-runningBufferCount));
//runningBufferCount = buffer.getCount();
//System.out.println("\ntop:");
// top (the order gets reversed here so the diagonals line up)
if (topLod) { // if lower LOD
if (rightLod) {
buffer.put(getWidth() - 1);
}
for (int col = getWidth() - 1; col >= lod; col -= 2 * lod) {
int idx = (lod * getWidth()) + col - lod; // next row
buffer.put(idx);
idx = col - 2 * lod;
buffer.put(idx);
if (col > lod * 2) { //if not the last one
idx = (lod * getWidth()) + col - 2 * lod;
buffer.put(idx);
idx = col - 2 * lod;
buffer.put(idx);
} else {
}
}
} else {
if (rightLod) {
buffer.put(getWidth() - 1);
}
for (int col = getWidth() - 1 - lod; col > 0; col -= lod) {
int idx = col + (lod * getWidth());
buffer.put(idx);
idx = col;
buffer.put(idx);
}
buffer.put(0);
}
buffer.put(0);
//System.out.println("\nbuffer top: "+(buffer.getCount()-runningBufferCount));
//runningBufferCount = buffer.getCount();
//System.out.println("\nleft:");
// left
if (leftLod) { // if lower LOD
if (topLod) {
buffer.put(0);
}
for (int row = 0; row < getWidth() - lod; row += 2 * lod) {
int idx = (row + lod) * getWidth() + lod;
buffer.put(idx);
idx = (row + 2 * lod) * getWidth();
buffer.put(idx);
if (row < getWidth() - lod - 2 - 1) { //if not the last one
idx = (row + 2 * lod) * getWidth() + lod;
buffer.put(idx);
idx = (row + 2 * lod) * getWidth();
buffer.put(idx);
} else {
}
}
} else {
if (!topLod) {
buffer.put(0);
}
//buffer.put(getWidth()+1); // degenerate
//buffer.put(0); // degenerate winding-flip
for (int row = lod; row < getWidth() - lod; row += lod) {
int idx = row * getWidth();
buffer.put(idx);
idx = row * getWidth() + lod;
buffer.put(idx);
}
}
buffer.put(getWidth() * (getWidth() - 1));
//System.out.println("\nbuffer left: "+(buffer.getCount()-runningBufferCount));
//runningBufferCount = buffer.getCount();
//if (true) return buffer.delegate;
//System.out.println("\nbottom");
// bottom
if (bottomLod) { // if lower LOD
if (leftLod) {
buffer.put(getWidth() * (getWidth() - 1));
}
// there was a slight bug here when really high LOD near maxLod
// far right has extra index one row up and all the way to the right, need to skip last index entered
// seemed to be fixed by making "getWidth()-1-2-lod" this: "getWidth()-1-2*lod", which seems more correct
for (int col = 0; col < getWidth() - lod; col += 2 * lod) {
int idx = getWidth() * (getWidth() - 1 - lod) + col + lod;
buffer.put(idx);
idx = getWidth() * (getWidth() - 1) + col + 2 * lod;
buffer.put(idx);
if (col < getWidth() - 1 - 2 * lod) { //if not the last one
idx = getWidth() * (getWidth() - 1 - lod) + col + 2 * lod;
buffer.put(idx);
idx = getWidth() * (getWidth() - 1) + col + 2 * lod;
buffer.put(idx);
} else {
}
}
} else {
if (leftLod) {
buffer.put(getWidth() * (getWidth() - 1));
}
for (int col = lod; col < getWidth() - lod; col += lod) {
int idx = getWidth() * (getWidth() - 1 - lod) + col;
buffer.put(idx);
idx = getWidth() * (getWidth() - 1) + col; // down
buffer.put(idx);
}
//buffer.put(getWidth()*getWidth()-1-lod); // <-- THIS caused holes at the end!
}
buffer.put(getWidth() * getWidth() - 1);
//System.out.println("\nbuffer bottom: "+(buffer.getCount()-runningBufferCount));
//runningBufferCount = buffer.getCount();
//System.out.println("\nBuffer size: "+buffer.getCount());
// fill in the rest of the buffer with degenerates, there should only be a couple
for (int i = buffer.getCount(); i < numIndexes; i++) {
buffer.put(getWidth() * getWidth() - 1);
}
return buffer.delegate;
}
public IntBuffer writeIndexArrayLodVariable(IntBuffer store, int lod, int rightLod, int topLod, int leftLod, int bottomLod) {
IntBuffer buffer2 = store;
int numIndexes = calculateNumIndexesLodDiff(lod);
if (store == null) {
buffer2 = BufferUtils.createIntBuffer(numIndexes);
}
VerboseIntBuffer buffer = new VerboseIntBuffer(buffer2);
// generate center squares minus the edges
//System.out.println("for (x="+lod+"; x<"+(getWidth()-(2*lod))+"; x+="+lod+")");
//System.out.println(" for (z="+lod+"; z<"+(getWidth()-(1*lod))+"; z+="+lod+")");
for (int r = lod; r < getWidth() - (2 * lod); r += lod) { // row
int rowIdx = r * getWidth();
int nextRowIdx = (r + 1 * lod) * getWidth();
for (int c = lod; c < getWidth() - (1 * lod); c += lod) { // column
int idx = rowIdx + c;
buffer.put(idx);
idx = nextRowIdx + c;
buffer.put(idx);
}
// add degenerate triangles
if (r < getWidth() - (3 * lod)) {
int idx = nextRowIdx + getWidth() - (1 * lod) - 1;
buffer.put(idx);
idx = nextRowIdx + (1 * lod); // inset by 1
buffer.put(idx);
//System.out.println("");
}
}
//System.out.println("\nright:");
//int runningBufferCount = buffer.getCount();
//System.out.println("buffer start: "+runningBufferCount);
// right
int br = getWidth() * (getWidth() - lod) - 1 - lod;
buffer.put(br); // bottom right -1
int corner = getWidth() * getWidth() - 1;
buffer.put(corner); // bottom right corner
if (rightLod > lod) { // if lower LOD
int idx = corner;
int it = (getWidth() - 1) / rightLod; // iterations
int lodDiff = rightLod / lod;
for (int i = it; i > 0; i--) { // for each lod level of the neighbour
idx = getWidth() * (i * rightLod + 1) - 1;
for (int j = 1; j <= lodDiff; j++) { // for each section in that lod level
int idxB = idx - (getWidth() * (j * lod)) - lod;
if (j == lodDiff && i == 1) {// the last one
buffer.put(getWidth() - 1);
} else if (j == lodDiff) {
buffer.put(idxB);
buffer.put(idxB + lod);
} else {
buffer.put(idxB);
buffer.put(idx);
}
}
}
// reset winding order
buffer.put(getWidth() * (lod + 1) - lod - 1); // top-right +1row
buffer.put(getWidth() - 1);// top-right
} else {
buffer.put(corner);//br+1);//degenerate to flip winding order
for (int row = getWidth() - lod; row > lod; row -= lod) {
int idx = row * getWidth() - 1; // mult to get row
buffer.put(idx);
buffer.put(idx - lod);
}
buffer.put(getWidth() - 1);
}
//System.out.println("\nbuffer right: "+(buffer.getCount()-runningBufferCount));
//runningBufferCount = buffer.getCount();
//System.out.println("\ntop:");
// top (the order gets reversed here so the diagonals line up)
if (topLod > lod) { // if lower LOD
if (rightLod > lod) {
// need to flip winding order
buffer.put(getWidth() - 1);
buffer.put(getWidth() * lod - 1);
buffer.put(getWidth() - 1);
}
int idx = getWidth() - 1;
int it = (getWidth() - 1) / topLod; // iterations
int lodDiff = topLod / lod;
for (int i = it; i > 0; i--) { // for each lod level of the neighbour
idx = (i * topLod);
for (int j = 1; j <= lodDiff; j++) { // for each section in that lod level
int idxB = lod * getWidth() + (i * topLod) - (j * lod);
if (j == lodDiff && i == 1) {// the last one
buffer.put(0);
} else if (j == lodDiff) {
buffer.put(idxB);
buffer.put(idx - topLod);
} else {
buffer.put(idxB);
buffer.put(idx);
}
}
}
} else {
if (rightLod > lod) {
buffer.put(getWidth() - 1);
}
for (int col = getWidth() - 1 - lod; col > 0; col -= lod) {
int idx = col + (lod * getWidth());
buffer.put(idx);
idx = col;
buffer.put(idx);
}
buffer.put(0);
}
buffer.put(0);
//System.out.println("\nbuffer top: "+(buffer.getCount()-runningBufferCount));
//runningBufferCount = buffer.getCount();
//System.out.println("\nleft:");
// left
if (leftLod > lod) { // if lower LOD
int idx = 0;
int it = (getWidth() - 1) / leftLod; // iterations
int lodDiff = leftLod / lod;
for (int i = 0; i < it; i++) { // for each lod level of the neighbour
idx = getWidth() * (i * leftLod);
for (int j = 1; j <= lodDiff; j++) { // for each section in that lod level
int idxB = idx + (getWidth() * (j * lod)) + lod;
if (j == lodDiff && i == it - 1) {// the last one
buffer.put(getWidth() * getWidth() - getWidth());
} else if (j == lodDiff) {
buffer.put(idxB);
buffer.put(idxB - lod);
} else {
buffer.put(idxB);
buffer.put(idx);
}
}
}
} else {
buffer.put(0);
buffer.put(getWidth() * lod + lod);
buffer.put(0);
for (int row = lod; row < getWidth() - lod; row += lod) {
int idx = row * getWidth();
buffer.put(idx);
idx = row * getWidth() + lod;
buffer.put(idx);
}
buffer.put(getWidth() * (getWidth() - 1));
}
//buffer.put(getWidth()*(getWidth()-1));
//System.out.println("\nbuffer left: "+(buffer.getCount()-runningBufferCount));
//runningBufferCount = buffer.getCount();
//if (true) return buffer.delegate;
//System.out.println("\nbottom");
// bottom
if (bottomLod > lod) { // if lower LOD
if (leftLod > lod) {
buffer.put(getWidth() * (getWidth() - 1));
buffer.put(getWidth() * (getWidth() - lod));
buffer.put(getWidth() * (getWidth() - 1));
}
int idx = getWidth() * getWidth() - getWidth();
int it = (getWidth() - 1) / bottomLod; // iterations
int lodDiff = bottomLod / lod;
for (int i = 0; i < it; i++) { // for each lod level of the neighbour
idx = getWidth() * getWidth() - getWidth() + (i * bottomLod);
for (int j = 1; j <= lodDiff; j++) { // for each section in that lod level
int idxB = idx - (getWidth() * lod) + j * lod;
if (j == lodDiff && i == it - 1) {// the last one
buffer.put(getWidth() * getWidth() - 1);
} else if (j == lodDiff) {
buffer.put(idxB);
buffer.put(idx + bottomLod);
} else {
buffer.put(idxB);
buffer.put(idx);
}
}
}
} else {
if (leftLod > lod) {
buffer.put(getWidth() * (getWidth() - 1));
buffer.put(getWidth() * getWidth() - (getWidth() * lod) + lod);
buffer.put(getWidth() * (getWidth() - 1));
}
for (int col = lod; col < getWidth() - lod; col += lod) {
int idx = getWidth() * (getWidth() - 1 - lod) + col;
buffer.put(idx);
idx = getWidth() * (getWidth() - 1) + col; // down
buffer.put(idx);
}
//buffer.put(getWidth()*getWidth()-1-lod); // <-- THIS caused holes at the end!
}
buffer.put(getWidth() * getWidth() - 1);
//System.out.println("\nbuffer bottom: "+(buffer.getCount()-runningBufferCount));
//runningBufferCount = buffer.getCount();
//System.out.println("\nBuffer size: "+buffer.getCount());
// fill in the rest of the buffer with degenerates, there should only be a couple
for (int i = buffer.getCount(); i < numIndexes; i++) {
buffer.put(getWidth() * getWidth() - 1);
}
return buffer.delegate;
}
/*private int calculateNumIndexesNormal(int lod) {
int length = getWidth()-1;
int num = ((length/lod)+1)*((length/lod)+1)*2;
System.out.println("num: "+num);
num -= 2*((length/lod)+1);
System.out.println("num2: "+num);
// now get the degenerate indexes that exist between strip rows
num += 2*(((length/lod)+1)-2); // every row except the first and last
System.out.println("Index buffer size: "+num);
return num;
}*/
/**
* calculate how many indexes there will be.
* This isn't that precise and there might be a couple extra.
*/
private int calculateNumIndexesLodDiff(int lod) {
if (lod == 0) {
lod = 1;
}
int length = getWidth() - 1; // make it even for lod calc
int side = (length / lod) + 1 - (2);
//System.out.println("side: "+side);
int num = side * side * 2;
//System.out.println("num: "+num);
num -= 2 * side; // remove one first row and one last row (they are only hit once each)
//System.out.println("num2: "+num);
// now get the degenerate indexes that exist between strip rows
int degenerates = 2 * (side - (2)); // every row except the first and last
num += degenerates;
//System.out.println("degenerates: "+degenerates);
//System.out.println("center, before edges: "+num);
num += (getWidth() / lod) * 2 * 4;
num++;
num += 10;// TODO remove me: extra
//System.out.println("Index buffer size: "+num);
return num;
}
public FloatBuffer[] writeTangentArray(FloatBuffer tangentStore, FloatBuffer binormalStore, FloatBuffer textureBuffer, Vector3f scale) {
if (!isLoaded()) {
throw new NullPointerException();
}
if (tangentStore != null) {
if (tangentStore.remaining() < getWidth() * getHeight() * 3) {
throw new BufferUnderflowException();
}
} else {
tangentStore = BufferUtils.createFloatBuffer(getWidth() * getHeight() * 3);
}
tangentStore.rewind();
if (binormalStore != null) {
if (binormalStore.remaining() < getWidth() * getHeight() * 3) {
throw new BufferUnderflowException();
}
} else {
binormalStore = BufferUtils.createFloatBuffer(getWidth() * getHeight() * 3);
}
binormalStore.rewind();
Vector3f tangent = new Vector3f();
Vector3f binormal = new Vector3f();
Vector3f v1 = new Vector3f();
Vector3f v2 = new Vector3f();
Vector3f v3 = new Vector3f();
Vector2f t1 = new Vector2f();
Vector2f t2 = new Vector2f();
Vector2f t3 = new Vector2f();
//scale = Vector3f.UNIT_XYZ;
for (int r = 0; r < getHeight(); r++) {
for (int c = 0; c < getWidth(); c++) {
int texIdx = ((getHeight() - 1 - r) * getWidth() + c) * 2; // pull from the end
int texIdxAbove = ((getHeight() - 1 - (r - 1)) * getWidth() + c) * 2; // pull from the end
int texIdxNext = ((getHeight() - 1 - (r + 1)) * getWidth() + c) * 2; // pull from the end
v1.set(c, getValue(c, r), r);
t1.set(textureBuffer.get(texIdx), textureBuffer.get(texIdx + 1));
// below
if (r == getHeight()-1) { // last row
v3.set(c, getValue(c, r), r + 1);
float u = textureBuffer.get(texIdx) - textureBuffer.get(texIdxAbove);
u += textureBuffer.get(texIdx);
float v = textureBuffer.get(texIdx + 1) - textureBuffer.get(texIdxAbove + 1);
v += textureBuffer.get(texIdx + 1);
t3.set(u, v);
} else {
v3.set(c, getValue(c, r + 1), r + 1);
t3.set(textureBuffer.get(texIdxNext), textureBuffer.get(texIdxNext + 1));
}
//right
if (c == getWidth()-1) { // last column
v2.set(c + 1, getValue(c, r), r);
float u = textureBuffer.get(texIdx) - textureBuffer.get(texIdx - 2);
u += textureBuffer.get(texIdx);
float v = textureBuffer.get(texIdx + 1) - textureBuffer.get(texIdx - 1);
v += textureBuffer.get(texIdx - 1);
t2.set(u, v);
} else {
v2.set(c + 1, getValue(c + 1, r), r); // one to the right
t2.set(textureBuffer.get(texIdx + 2), textureBuffer.get(texIdx + 3));
}
calculateTangent(new Vector3f[]{v1.mult(scale), v2.mult(scale), v3.mult(scale)}, new Vector2f[]{t1, t2, t3}, tangent, binormal);
BufferUtils.setInBuffer(tangent, tangentStore, (r * getWidth() + c)); // save the tangent
BufferUtils.setInBuffer(binormal, binormalStore, (r * getWidth() + c)); // save the binormal
}
}
return new FloatBuffer[]{tangentStore, binormalStore};
}
/**
*
* @param v Takes 3 vertices: root, right, bottom
* @param t Takes 3 tex coords: root, right, bottom
* @param tangent that will store the result
* @return the tangent store
*/
public static Vector3f calculateTangent(Vector3f[] v, Vector2f[] t, Vector3f tangent, Vector3f binormal) {
Vector3f edge1 = new Vector3f();
Vector3f edge2 = new Vector3f();
Vector2f edge1uv = new Vector2f();
Vector2f edge2uv = new Vector2f();
t[2].subtract(t[0], edge2uv);
t[1].subtract(t[0], edge1uv);
float det = edge1uv.x * edge2uv.y;// - edge1uv.y*edge2uv.x; = 0
boolean normalize = true;
if (Math.abs(det) < 0.0000001f) {
det = 1;
normalize = true;
}
v[1].subtract(v[0], edge1);
v[2].subtract(v[0], edge2);
tangent.set(edge1);
tangent.normalizeLocal();
binormal.set(edge2);
binormal.normalizeLocal();
float factor = 1 / det;
tangent.x = (edge2uv.y * edge1.x) * factor;
tangent.y = 0;
tangent.z = (edge2uv.y * edge1.z) * factor;
if (normalize) {
tangent.normalizeLocal();
}
binormal.x = 0;
binormal.y = (edge1uv.x * edge2.y) * factor;
binormal.z = (edge1uv.x * edge2.z) * factor;
if (normalize) {
binormal.normalizeLocal();
}
return tangent;
}
@Override
public FloatBuffer writeNormalArray(FloatBuffer store, Vector3f scale) {
if (!isLoaded()) {
throw new NullPointerException();
}
if (store != null) {
if (store.remaining() < getWidth() * getHeight() * 3) {
throw new BufferUnderflowException();
}
} else {
store = BufferUtils.createFloatBuffer(getWidth() * getHeight() * 3);
}
store.rewind();
TempVars vars = TempVars.get();
Vector3f rootPoint = vars.vect1;
Vector3f rightPoint = vars.vect2;
Vector3f leftPoint = vars.vect3;
Vector3f topPoint = vars.vect4;
Vector3f bottomPoint = vars.vect5;
Vector3f tmp1 = vars.vect6;
// calculate normals for each polygon
for (int r = 0; r < getHeight(); r++) {
for (int c = 0; c < getWidth(); c++) {
rootPoint.set(c, getValue(c, r), r);
Vector3f normal = vars.vect8;
if (r == 0) { // first row
if (c == 0) { // first column
rightPoint.set(c + 1, getValue(c + 1, r), r);
bottomPoint.set(c, getValue(c, r + 1), r + 1);
getNormal(bottomPoint, rootPoint, rightPoint, scale, normal);
} else if (c == getWidth() - 1) { // last column
leftPoint.set(c - 1, getValue(c - 1, r), r);
bottomPoint.set(c, getValue(c, r + 1), r + 1);
getNormal(leftPoint, rootPoint, bottomPoint, scale, normal);
} else { // all middle columns
leftPoint.set(c - 1, getValue(c - 1, r), r);
rightPoint.set(c + 1, getValue(c + 1, r), r);
bottomPoint.set(c, getValue(c, r + 1), r + 1);
normal.set( getNormal(leftPoint, rootPoint, bottomPoint, scale, tmp1) );
normal.add( getNormal(bottomPoint, rootPoint, rightPoint, scale, tmp1) );
normal.normalizeLocal();
}
} else if (r == getHeight() - 1) { // last row
if (c == 0) { // first column
topPoint.set(c, getValue(c, r - 1), r - 1);
rightPoint.set(c + 1, getValue(c + 1, r), r);
getNormal(rightPoint, rootPoint, topPoint, scale, normal);
} else if (c == getWidth() - 1) { // last column
topPoint.set(c, getValue(c, r - 1), r - 1);
leftPoint.set(c - 1, getValue(c - 1, r), r);
getNormal(topPoint, rootPoint, leftPoint, scale, normal);
} else { // all middle columns
topPoint.set(c, getValue(c, r - 1), r - 1);
leftPoint.set(c - 1, getValue(c - 1, r), r);
rightPoint.set(c + 1, getValue(c + 1, r), r);
normal.set( getNormal(topPoint, rootPoint, leftPoint, scale, tmp1) );
normal.add( getNormal(rightPoint, rootPoint, topPoint, scale, tmp1) );
normal.normalizeLocal();
}
} else { // all middle rows
if (c == 0) { // first column
topPoint.set(c, getValue(c, r - 1), r - 1);
rightPoint.set(c + 1, getValue(c + 1, r), r);
bottomPoint.set(c, getValue(c, r + 1), r + 1);
normal.set( getNormal(rightPoint, rootPoint, topPoint, scale, tmp1) );
normal.add( getNormal(bottomPoint, rootPoint, rightPoint, scale, tmp1) );
normal.normalizeLocal();
} else if (c == getWidth() - 1) { // last column
topPoint.set(c, getValue(c, r - 1), r - 1);
leftPoint.set(c - 1, getValue(c - 1, r), r);
bottomPoint.set(c, getValue(c, r + 1), r + 1); //XXX wrong
normal.set( getNormal(topPoint, rootPoint, leftPoint, scale, tmp1) );
normal.add( getNormal(leftPoint, rootPoint, bottomPoint, scale, tmp1) );
normal.normalizeLocal();
} else { // all middle columns
topPoint.set(c, getValue(c, r - 1), r - 1);
leftPoint.set(c - 1, getValue(c - 1, r), r);
rightPoint.set(c + 1, getValue(c + 1, r), r);
bottomPoint.set(c, getValue(c, r + 1), r + 1);
normal.set( getNormal(topPoint, rootPoint, leftPoint, scale, tmp1 ) );
normal.add( getNormal(leftPoint, rootPoint, bottomPoint, scale, tmp1) );
normal.add( getNormal(bottomPoint, rootPoint, rightPoint, scale, tmp1) );
normal.add( getNormal(rightPoint, rootPoint, topPoint, scale, tmp1) );
normal.normalizeLocal();
}
}
BufferUtils.setInBuffer(normal, store, (r * getWidth() + c)); // save the normal
}
}
vars.release();
return store;
}
private Vector3f getNormal(Vector3f firstPoint, Vector3f rootPoint, Vector3f secondPoint, Vector3f scale, Vector3f store) {
float x1 = firstPoint.x - rootPoint.x;
float y1 = firstPoint.y - rootPoint.y;
float z1 = firstPoint.z - rootPoint.z;
x1 *= scale.x;
y1 *= scale.y;
z1 *= scale.z;
float x2 = secondPoint.x - rootPoint.x;
float y2 = secondPoint.y - rootPoint.y;
float z2 = secondPoint.z - rootPoint.z;
x2 *= scale.x;
y2 *= scale.y;
z2 *= scale.z;
float x3 = (y1 * z2) - (z1 * y2);
float y3 = (z1 * x2) - (x1 * z2);
float z3 = (x1 * y2) - (y1 * x2);
float inv = 1.0f / FastMath.sqrt(x3 * x3 + y3 * y3 + z3 * z3);
store.x = x3 * inv;
store.y = y3 * inv;
store.z = z3 * inv;
return store;
/*store.set( firstPoint.subtractLocal(rootPoint).multLocal(scale).crossLocal(secondPoint.subtractLocal(rootPoint).multLocal(scale)).normalizeLocal() );
return store;*/
}
/**
* Keeps a count of the number of indexes, good for debugging
*/
public class VerboseIntBuffer {
private IntBuffer delegate;
int count = 0;
public VerboseIntBuffer(IntBuffer d) {
delegate = d;
}
public void put(int value) {
try {
delegate.put(value);
count++;
} catch (BufferOverflowException e) {
//System.out.println("err buffer size: "+delegate.capacity());
}
}
public int getCount() {
return count;
}
}
/**
* Get a representation of the underlying triangle at the given point,
* translated to world coordinates.
*
* @param x local x coordinate
* @param z local z coordinate
* @return a triangle in world space not local space
*/
protected Triangle getTriangleAtPoint(float x, float z, Vector3f scale, Vector3f translation) {
Triangle tri = getTriangleAtPoint(x, z);
if (tri != null) {
tri.get1().multLocal(scale).addLocal(translation);
tri.get2().multLocal(scale).addLocal(translation);
tri.get3().multLocal(scale).addLocal(translation);
}
return tri;
}
/**
* Get the two triangles that make up the grid section at the specified point,
* translated to world coordinates.
*
* @param x local x coordinate
* @param z local z coordinate
* @param scale
* @param translation
* @return two triangles in world space not local space
*/
protected Triangle[] getGridTrianglesAtPoint(float x, float z, Vector3f scale, Vector3f translation) {
Triangle[] tris = getGridTrianglesAtPoint(x, z);
if (tris != null) {
tris[0].get1().multLocal(scale).addLocal(translation);
tris[0].get2().multLocal(scale).addLocal(translation);
tris[0].get3().multLocal(scale).addLocal(translation);
tris[1].get1().multLocal(scale).addLocal(translation);
tris[1].get2().multLocal(scale).addLocal(translation);
tris[1].get3().multLocal(scale).addLocal(translation);
}
return tris;
}
protected Triangle[] getGridTrianglesAtPoint(float x, float z) {
int gridX = (int) x;
int gridY = (int) z;
int index = findClosestHeightIndex(gridX, gridY);
if (index < 0) {
return null;
}
Triangle t = new Triangle(new Vector3f(), new Vector3f(), new Vector3f());
Triangle t2 = new Triangle(new Vector3f(), new Vector3f(), new Vector3f());
float h1 = hdata[index]; // top left
float h2 = hdata[index + 1]; // top right
float h3 = hdata[index + width]; // bottom left
float h4 = hdata[index + width + 1]; // bottom right
if ((gridX == 0 && gridY == 0) || (gridX == width - 1 && gridY == width - 1)) {
// top left or bottom right grid point
t.get(0).x = (gridX);
t.get(0).y = (h1);
t.get(0).z = (gridY);
t.get(1).x = (gridX);
t.get(1).y = (h3);
t.get(1).z = (gridY + 1);
t.get(2).x = (gridX + 1);
t.get(2).y = (h4);
t.get(2).z = (gridY + 1);
t2.get(0).x = (gridX);
t2.get(0).y = (h1);
t2.get(0).z = (gridY);
t2.get(1).x = (gridX + 1);
t2.get(1).y = (h4);
t2.get(1).z = (gridY + 1);
t2.get(2).x = (gridX + 1);
t2.get(2).y = (h2);
t2.get(2).z = (gridY);
} else {
// all other grid points
t.get(0).x = (gridX);
t.get(0).y = (h1);
t.get(0).z = (gridY);
t.get(1).x = (gridX);
t.get(1).y = (h3);
t.get(1).z = (gridY + 1);
t.get(2).x = (gridX + 1);
t.get(2).y = (h2);
t.get(2).z = (gridY);
t2.get(0).x = (gridX + 1);
t2.get(0).y = (h2);
t2.get(0).z = (gridY);
t2.get(1).x = (gridX);
t2.get(1).y = (h3);
t2.get(1).z = (gridY + 1);
t2.get(2).x = (gridX + 1);
t2.get(2).y = (h4);
t2.get(2).z = (gridY + 1);
}
return new Triangle[]{t, t2};
}
/**
* Get the triangle that the point is on.
*
* @param x coordinate in local space to the geomap
* @param z coordinate in local space to the geomap
* @return triangle in local space to the geomap
*/
protected Triangle getTriangleAtPoint(float x, float z) {
Triangle[] triangles = getGridTrianglesAtPoint(x, z);
if (triangles == null) {
//System.out.println("x,z: " + x + "," + z);
return null;
}
Vector2f point = new Vector2f(x, z);
Vector2f t1 = new Vector2f(triangles[0].get1().x, triangles[0].get1().z);
Vector2f t2 = new Vector2f(triangles[0].get2().x, triangles[0].get2().z);
Vector2f t3 = new Vector2f(triangles[0].get3().x, triangles[0].get3().z);
if (0 != FastMath.pointInsideTriangle(t1, t2, t3, point)) {
return triangles[0];
}
t1.set(triangles[1].get1().x, triangles[1].get1().z);
t1.set(triangles[1].get2().x, triangles[1].get2().z);
t1.set(triangles[1].get3().x, triangles[1].get3().z);
if (0 != FastMath.pointInsideTriangle(t1, t2, t3, point)) {
return triangles[1];
}
return null;
}
protected int findClosestHeightIndex(int x, int z) {
if (x < 0 || x >= width - 1) {
return -1;
}
if (z < 0 || z >= width - 1) {
return -1;
}
return z * width + x;
}
@Override
public void write(JmeExporter ex) throws IOException {
super.write(ex);
}
@Override
public void read(JmeImporter im) throws IOException {
super.read(im);
}
} |
package com.mick88.dittimetable.screens;
import java.io.IOException;
import java.util.Locale;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.mick88.dittimetable.AppSettings;
import com.mick88.dittimetable.R;
import com.mick88.dittimetable.TimetableApp;
import com.mick88.dittimetable.timetable.Timetable;
import com.mick88.dittimetable.utils.FontApplicator;
public class SettingsActivity extends ActionBarActivity
{
/**
* TODO: Roboto font in Spinners
* TODO: Don't allow back if data is incorrect
* TODO: Clear error when semester is seleceted
*/
FontApplicator fontApplicator;
Spinner yearSelector,
semesterSelector;
CheckBox weekCheckBox;
EditText editWeeks,
editCourse,
editPassword,
editUsername;
AppSettings appSettings;
final int SEM_1_ID=0,
SEM_2_ID=1,
CUSTOM_ID=4;
int currentWeek = Timetable.getCurrentWeek();
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
this.fontApplicator = new FontApplicator(getAssets(), "Roboto-Light.ttf");
fontApplicator.applyFont(getWindow().getDecorView());
appSettings = ((TimetableApp)getApplication()).getSettings();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
yearSelector = (Spinner) findViewById(R.id.spinner_year_selector);
semesterSelector = (Spinner) findViewById(R.id.spinner_semester_selector);
editWeeks = (EditText) findViewById(R.id.edit_weeks);
editCourse = (EditText) findViewById(R.id.editCourseCode);
editCourse.setRawInputType(Configuration.KEYBOARD_QWERTY);
editUsername = (EditText) findViewById(R.id.editUsername);
editPassword = (EditText) findViewById(R.id.editPassword);
weekCheckBox = (CheckBox) findViewById(R.id.checkBoxSetCurrentWeekOnly);
TextView tvInfo = (TextView) findViewById(R.id.textDatasetInfo);
findViewById(R.id.btn_get_password).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http:
startActivity(intent);
}
});
tvInfo.setText(String.format(Locale.ENGLISH, "Dataset: %s, week %d", Timetable.getDataset(), currentWeek));
loadSettings();
semesterSelector.setOnItemSelectedListener(new OnItemSelectedListener()
{
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3)
{
switch ((int)arg3)
{
case SEM_1_ID:
editWeeks.setText(Timetable.SEMESTER_1);
editWeeks.setError(null);
break;
case SEM_2_ID:
editWeeks.setText(Timetable.SEMESTER_2);
editWeeks.setError(null);
break;
case 2:
editWeeks.setText(Timetable.ALL_WEEKS);
editWeeks.setError(null);
break;
case 3:
editWeeks.setText(String.valueOf(currentWeek));
editWeeks.setError(null);
break;
case 4:
editWeeks.requestFocus();
editWeeks.selectAll();
break;
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0)
{
}
});
}
boolean saveSettings()
{
String [] settings = new String[] {
editCourse.getText().toString(),
String.valueOf(yearSelector.getSelectedItemId()+1),
editWeeks.getText().toString(),
editUsername.getText().toString().trim(),
editPassword.getText().toString().trim()
};
appSettings.setUsername(editUsername.getText().toString().trim());
appSettings.setPassword(editPassword.getText().toString().trim());
appSettings.setCourse(editCourse.getText().toString().toUpperCase());
appSettings.setWeeks(editWeeks.getText().toString());
appSettings.setYear((int) (yearSelector.getSelectedItemId()+1));
appSettings.setOnlyCurrentWeek(weekCheckBox.isChecked());
appSettings.saveSettings();
try
{
Timetable.writeSettings(getApplicationContext(), settings);
return true;
} catch (IOException e)
{
Toast.makeText(getApplicationContext(), "Settings could not be saved", Toast.LENGTH_LONG).show();
}
return false;
}
void loadSettings()
{
String courseCode="",
weeks=Timetable.getSemester()==1?Timetable.SEMESTER_1:Timetable.SEMESTER_2,
username="",
password="";
int year=1;
courseCode = appSettings.getCourse();
weeks = appSettings.getWeeks();
year = appSettings.getYear();
username = appSettings.getUsername();
password = appSettings.getPassword();
if (TextUtils.isEmpty(weeks)) weeks = Timetable.getSemester()==1?Timetable.SEMESTER_1:Timetable.SEMESTER_2;
if (weeks.equals(Timetable.SEMESTER_1)) semesterSelector.setSelection(SEM_1_ID);
else if (weeks.equals(Timetable.SEMESTER_2)) semesterSelector.setSelection(SEM_2_ID);
else semesterSelector.setSelection(CUSTOM_ID);
editCourse.setText(courseCode);
editWeeks.setText(weeks);
yearSelector.setSelection(year-1);
editUsername.setText(username);
editPassword.setText(password);
weekCheckBox.setChecked(appSettings.getOnlyCurrentWeek());
}
@Override
public boolean onOptionsItemSelected(
MenuItem item)
{
switch(item.getItemId())
{
case android.R.id.home:
onBackPressed();
break;
case R.id.settings_save:
saveAndQuit();
break;
case R.id.settings_cancel:
cancelAndQuit();
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_settings, menu);
return super.onCreateOptionsMenu(menu);
}
private boolean validate()
{
boolean valid = true;
if (TextUtils.isEmpty(editPassword.getText()))
{
editPassword.requestFocus();
editPassword.setError("Password cannot be empty");
valid = false;
}
if (TextUtils.isEmpty(editUsername.getText()))
{
editUsername.requestFocus();
editUsername.setError("Username cannot be empty");
valid = false;
}
if (editWeeks.getText().toString().matches("[0-9-,]+") == false) //any digit, space or ,. One or more times
{
editWeeks.requestFocus();
editWeeks.setError("Incorrect week range");
valid = false;
}
if (editCourse.getText().toString().toUpperCase().matches("DT[0-9]{3}") == false)
{
if (editCourse.getText().toString().matches("[0-9]{3}") == true)
{
// autocorrect
CharSequence text = editCourse.getText();
editCourse.setText(new StringBuilder("DT").append(text));
}
else
{
editCourse.requestFocus();
editCourse.setError("Invalid course code");
valid = false;
}
}
return valid;
}
void saveAndQuit()
{
if (validate())
{
saveSettings();
this.setResult(RESULT_OK);
finish();
}
}
void cancelAndQuit()
{
this.setResult(RESULT_CANCELED);
this.finish();
}
@Override
public void onBackPressed()
{
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle(R.string.app_name)
.setMessage("Would you like to save changes?")
.setPositiveButton("Yes", new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
saveAndQuit();
}
})
.setNegativeButton("No", new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
cancelAndQuit();
}
})
.setCancelable(false)
.setIcon(R.drawable.ic_launcher)
.create();
dialog.show();
}
} |
package org.xwiki.extension.distribution.internal.job;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.commons.lang3.ObjectUtils;
import org.xwiki.component.annotation.Component;
import org.xwiki.extension.ExtensionId;
import org.xwiki.extension.InstalledExtension;
import org.xwiki.extension.distribution.internal.DistributionManager;
import org.xwiki.extension.distribution.internal.job.DistributionStepStatus.UpdateState;
import org.xwiki.extension.repository.InstalledExtensionRepository;
import org.xwiki.job.AbstractJob;
import org.xwiki.job.internal.AbstractJobStatus;
/**
* @version $Id$
* @since 4.2M3
*/
@Component
@Named("distribution")
public class DistributionJob extends AbstractJob<DistributionRequest>
{
/**
* The component used to get information about the current distribution.
*/
@Inject
private DistributionManager distributionManager;
@Inject
private InstalledExtensionRepository installedRepository;
@Override
public String getType()
{
return "distribution";
}
@Override
protected AbstractJobStatus<DistributionRequest> createNewStatus(DistributionRequest request)
{
// TODO: make steps components automatically discovered so that any module can add custom steps
List<DistributionStepStatus> steps = new ArrayList<DistributionStepStatus>(3);
ExtensionId extensionUI = this.distributionManager.getUIExtensionId();
// Step 1: Install/upgrade main wiki UI
DistributionStepStatus step1 = new DistributionStepStatus("extension.mainui");
steps.add(step1);
// Only if the UI is not already installed
if (this.installedRepository.getInstalledExtension(extensionUI) != null) {
step1.setUpdateState(UpdateState.COMPLETED);
}
// Step 2: Upgrade outdated extensions
DistributionStepStatus step2 = new DistributionStepStatus("extension.outdatedextensions");
steps.add(step2);
step1.setUpdateState(UpdateState.COMPLETED);
// Upgrade outdated extensions only when there is outdated extensions
for (InstalledExtension extension : this.installedRepository.getInstalledExtensions()) {
Collection<String> namespaces = extension.getNamespaces();
if (namespaces == null) {
if (!extension.isValid(null)) {
step2.setUpdateState(null);
break;
}
} else {
for (String namespace : namespaces) {
if (!extension.isValid(namespace)) {
step2.setUpdateState(null);
break;
}
}
}
}
// Step 0: A welcome message. Only if there is actually something to do
for (DistributionStepStatus step : steps) {
if (step.getUpdateState() == null) {
steps.add(0, new DistributionStepStatus("welcome"));
break;
}
}
// Create status
DistributionJobStatus status =
new DistributionJobStatus(request, this.observationManager, this.loggerManager, steps);
if (this.distributionManager.getDistributionExtension() != null) {
DistributionJobStatus previousStatus = this.distributionManager.getPreviousJobStatus();
if (previousStatus != null
&& previousStatus.getDistributionExtension() != null
&& !ObjectUtils.equals(previousStatus.getDistributionExtension(),
this.distributionManager.getDistributionExtension())) {
status.setDistributionExtension(previousStatus.getDistributionExtension());
status.setDistributionExtensionUi(previousStatus.getDistributionExtensionUi());
}
status.setDistributionExtension(this.distributionManager.getDistributionExtension().getId());
status.setDistributionExtensionUi(extensionUI);
}
return status;
}
/**
* @return the distribution job status
*/
protected DistributionJobStatus getDistributionJobStatus()
{
return (DistributionJobStatus) getStatus();
}
@Override
protected void start() throws Exception
{
List<DistributionStepStatus> steps = getDistributionJobStatus().getSteps();
notifyPushLevelProgress(steps.size());
try {
for (int index = 0; index < steps.size(); ++index) {
getDistributionJobStatus().setCurrentStateIndex(index);
DistributionStepStatus step = steps.get(index);
if (step.getUpdateState() == null) {
DistributionQuestion question = new DistributionQuestion(step.getStepId());
// Waiting to start
getStatus().ask(question);
if (question.isSave()) {
switch (question.getAction()) {
case CANCEL_STEP:
step.setUpdateState(UpdateState.CANCELED);
break;
case COMPLETE_STEP:
step.setUpdateState(UpdateState.COMPLETED);
break;
case CANCEL:
for (; index < steps.size(); ++index) {
steps.get(index).setUpdateState(UpdateState.CANCELED);
}
case SKIP:
index = steps.size() - 1;
break;
default:
break;
}
}
}
notifyStepPropress();
}
} finally {
notifyPopLevelProgress();
}
}
} |
package com.couchbase.lite.replicator;
import com.couchbase.lite.AsyncTask;
import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.Database;
import com.couchbase.lite.Manager;
import com.couchbase.lite.Misc;
import com.couchbase.lite.NetworkReachabilityListener;
import com.couchbase.lite.RevisionList;
import com.couchbase.lite.Status;
import com.couchbase.lite.auth.Authenticator;
import com.couchbase.lite.auth.AuthenticatorImpl;
import com.couchbase.lite.auth.Authorizer;
import com.couchbase.lite.auth.FacebookAuthorizer;
import com.couchbase.lite.auth.PersonaAuthorizer;
import com.couchbase.lite.internal.InterfaceAudience;
import com.couchbase.lite.internal.RevisionInternal;
import com.couchbase.lite.support.BatchProcessor;
import com.couchbase.lite.support.Batcher;
import com.couchbase.lite.support.CouchbaseLiteHttpClientFactory;
import com.couchbase.lite.support.HttpClientFactory;
import com.couchbase.lite.support.PersistentCookieStore;
import com.couchbase.lite.support.RemoteMultipartDownloaderRequest;
import com.couchbase.lite.support.RemoteMultipartRequest;
import com.couchbase.lite.support.RemoteRequest;
import com.couchbase.lite.support.RemoteRequestCompletionBlock;
import com.couchbase.lite.util.CollectionUtils;
import com.couchbase.lite.util.Log;
import com.couchbase.lite.util.TextUtils;
import com.couchbase.lite.util.URIUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpResponseException;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.impl.cookie.BasicClientCookie2;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* A Couchbase Lite pull or push Replication between a local and a remote Database.
*/
public abstract class Replication implements NetworkReachabilityListener {
private static int lastSessionID = 0;
protected boolean continuous;
protected String filterName;
protected ScheduledExecutorService workExecutor;
protected Database db;
protected URL remote;
protected String lastSequence;
protected boolean lastSequenceChanged;
protected Map<String, Object> remoteCheckpoint;
protected boolean savingCheckpoint;
protected boolean overdueForSave;
protected boolean running;
protected boolean active;
protected Throwable error;
protected String sessionID;
protected Batcher<RevisionInternal> batcher;
protected int asyncTaskCount;
protected AtomicInteger completedChangesCount;
private AtomicInteger changesCount;
protected boolean online;
protected HttpClientFactory clientFactory;
private final List<ChangeListener> changeListeners;
protected List<String> documentIDs;
protected Map<String, Object> filterParams;
protected ExecutorService remoteRequestExecutor;
protected Authenticator authenticator;
private ReplicationStatus status = ReplicationStatus.REPLICATION_STOPPED;
protected Map<String, Object> requestHeaders;
private int revisionsFailed;
private ScheduledFuture retryIfReadyFuture;
private final Map<RemoteRequest, Future> requests;
private String serverType;
private String remoteCheckpointDocID;
private CollectionUtils.Functor<Map<String,Object>,Map<String,Object>> propertiesTransformationBlock;
protected CollectionUtils.Functor<RevisionInternal,RevisionInternal> revisionBodyTransformationBlock;
protected static final int PROCESSOR_DELAY = 500;
protected static final int INBOX_CAPACITY = 100;
protected static final int RETRY_DELAY = 60;
protected static final int EXECUTOR_THREAD_POOL_SIZE = 5;
/**
* @exclude
*/
public static final String BY_CHANNEL_FILTER_NAME = "sync_gateway/bychannel";
/**
* @exclude
*/
public static final String CHANNELS_QUERY_PARAM = "channels";
/**
* @exclude
*/
public static final String REPLICATOR_DATABASE_NAME = "_replicator";
/**
* Options for what metadata to include in document bodies
*/
public enum ReplicationStatus {
/** The replication is finished or hit a fatal error. */
REPLICATION_STOPPED,
/** The remote host is currently unreachable. */
REPLICATION_OFFLINE,
/** Continuous replication is caught up and waiting for more changes.*/
REPLICATION_IDLE,
/** The replication is actively transferring data. */
REPLICATION_ACTIVE
}
/**
* Private Constructor
* @exclude
*/
@InterfaceAudience.Private
/* package */ Replication(Database db, URL remote, boolean continuous, ScheduledExecutorService workExecutor) {
this(db, remote, continuous, null, workExecutor);
}
/**
* Private Constructor
* @exclude
*/
@InterfaceAudience.Private
/* package */ Replication(Database db, URL remote, boolean continuous, HttpClientFactory clientFactory, ScheduledExecutorService workExecutor) {
this.db = db;
this.continuous = continuous;
this.workExecutor = workExecutor;
this.remote = remote;
this.remoteRequestExecutor = Executors.newFixedThreadPool(EXECUTOR_THREAD_POOL_SIZE);
this.changeListeners = new CopyOnWriteArrayList<ChangeListener>();
this.online = true;
this.requestHeaders = new HashMap<String, Object>();
this.requests = new ConcurrentHashMap<RemoteRequest, Future>();
this.completedChangesCount = new AtomicInteger(0);
this.changesCount = new AtomicInteger(0);
if (remote.getQuery() != null && !remote.getQuery().isEmpty()) {
URI uri = URI.create(remote.toExternalForm());
String personaAssertion = URIUtils.getQueryParameter(uri, PersonaAuthorizer.QUERY_PARAMETER);
if (personaAssertion != null && !personaAssertion.isEmpty()) {
String email = PersonaAuthorizer.registerAssertion(personaAssertion);
PersonaAuthorizer authorizer = new PersonaAuthorizer(email);
setAuthenticator(authorizer);
}
String facebookAccessToken = URIUtils.getQueryParameter(uri, FacebookAuthorizer.QUERY_PARAMETER);
if (facebookAccessToken != null && !facebookAccessToken.isEmpty()) {
String email = URIUtils.getQueryParameter(uri, FacebookAuthorizer.QUERY_PARAMETER_EMAIL);
FacebookAuthorizer authorizer = new FacebookAuthorizer(email);
URL remoteWithQueryRemoved = null;
try {
remoteWithQueryRemoved = new URL(remote.getProtocol(), remote.getHost(), remote.getPort(), remote.getPath());
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
authorizer.registerAccessToken(facebookAccessToken, email, remoteWithQueryRemoved.toExternalForm());
setAuthenticator(authorizer);
}
// we need to remove the query from the URL, since it will cause problems when
// communicating with sync gw / couchdb
try {
this.remote = new URL(remote.getProtocol(), remote.getHost(), remote.getPort(), remote.getPath());
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
}
batcher = new Batcher<RevisionInternal>(workExecutor, INBOX_CAPACITY, PROCESSOR_DELAY, new BatchProcessor<RevisionInternal>() {
@Override
public void process(List<RevisionInternal> inbox) {
try {
Log.v(Log.TAG_SYNC, "*** %s: BEGIN processInbox (%d sequences)", this, inbox.size());
processInbox(new RevisionList(inbox));
Log.v(Log.TAG_SYNC, "*** %s: END processInbox (lastSequence=%s)", this, lastSequence);
updateActive();
} catch (Exception e) {
Log.e(Log.TAG_SYNC,"ERROR: processInbox failed: ",e);
throw new RuntimeException(e);
}
}
});
setClientFactory(clientFactory);
}
/**
* Set the HTTP client factory if one was passed in, or use the default
* set in the manager if available.
* @param clientFactory
*/
@InterfaceAudience.Private
protected void setClientFactory(HttpClientFactory clientFactory) {
Manager manager = null;
if (this.db != null) {
manager = this.db.getManager();
}
HttpClientFactory managerClientFactory = null;
if (manager != null) {
managerClientFactory = manager.getDefaultHttpClientFactory();
}
if (clientFactory != null) {
this.clientFactory = clientFactory;
} else {
if (managerClientFactory != null) {
this.clientFactory = managerClientFactory;
} else {
PersistentCookieStore cookieStore = db.getPersistentCookieStore();
this.clientFactory = new CouchbaseLiteHttpClientFactory(cookieStore);
}
}
}
/**
* Get the local database which is the source or target of this replication
*/
@InterfaceAudience.Public
public Database getLocalDatabase() {
return db;
}
/**
* Get the remote URL which is the source or target of this replication
*/
@InterfaceAudience.Public
public URL getRemoteUrl() {
return remote;
}
/**
* Is this a pull replication? (Eg, it pulls data from Sync Gateway -> Device running CBL?)
*/
@InterfaceAudience.Public
public abstract boolean isPull();
/**
* Should the target database be created if it doesn't already exist? (Defaults to NO).
*/
@InterfaceAudience.Public
public abstract boolean shouldCreateTarget();
/**
* Set whether the target database be created if it doesn't already exist?
*/
@InterfaceAudience.Public
public abstract void setCreateTarget(boolean createTarget);
/**
* Should the replication operate continuously, copying changes as soon as the
* source database is modified? (Defaults to NO).
*/
@InterfaceAudience.Public
public boolean isContinuous() {
return continuous;
}
/**
* Set whether the replication should operate continuously.
*/
@InterfaceAudience.Public
public void setContinuous(boolean continuous) {
if (!isRunning()) {
this.continuous = continuous;
}
}
/**
* Name of an optional filter function to run on the source server. Only documents for
* which the function returns true are replicated.
*
* For a pull replication, the name looks like "designdocname/filtername".
* For a push replication, use the name under which you registered the filter with the Database.
*/
@InterfaceAudience.Public
public String getFilter() {
return filterName;
}
/**
* Set the filter to be used by this replication
*/
@InterfaceAudience.Public
public void setFilter(String filterName) {
this.filterName = filterName;
}
/**
* Parameters to pass to the filter function. Should map strings to strings.
*/
@InterfaceAudience.Public
public Map<String, Object> getFilterParams() {
return filterParams;
}
/**
* Set parameters to pass to the filter function.
*/
@InterfaceAudience.Public
public void setFilterParams(Map<String, Object> filterParams) {
this.filterParams = filterParams;
}
/**
* List of Sync Gateway channel names to filter by; a nil value means no filtering, i.e. all
* available channels will be synced. Only valid for pull replications whose source database
* is on a Couchbase Sync Gateway server. (This is a convenience that just reads or
* changes the values of .filter and .query_params.)
*/
@InterfaceAudience.Public
public List<String> getChannels() {
if (filterParams == null || filterParams.isEmpty()) {
return new ArrayList<String>();
}
String params = (String) filterParams.get(CHANNELS_QUERY_PARAM);
if (!isPull() || getFilter() == null || !getFilter().equals(BY_CHANNEL_FILTER_NAME) || params == null || params.isEmpty()) {
return new ArrayList<String>();
}
String[] paramsArray = params.split(",");
return new ArrayList<String>(Arrays.asList(paramsArray));
}
/**
* Set the list of Sync Gateway channel names
*/
@InterfaceAudience.Public
public void setChannels(List<String> channels) {
if (channels != null && !channels.isEmpty()) {
if (!isPull()) {
Log.w(Log.TAG_SYNC, "filterChannels can only be set in pull replications");
return;
}
setFilter(BY_CHANNEL_FILTER_NAME);
Map<String, Object> filterParams = new HashMap<String, Object>();
filterParams.put(CHANNELS_QUERY_PARAM, TextUtils.join(",", channels));
setFilterParams(filterParams);
} else if (getFilter().equals(BY_CHANNEL_FILTER_NAME)) {
setFilter(null);
setFilterParams(null);
}
}
/**
* Extra HTTP headers to send in all requests to the remote server.
* Should map strings (header names) to strings.
*/
@InterfaceAudience.Public
public Map<String, Object> getHeaders() {
return requestHeaders;
}
/**
* Set Extra HTTP headers to be sent in all requests to the remote server.
*/
@InterfaceAudience.Public
public void setHeaders(Map<String, Object> requestHeadersParam) {
if (requestHeadersParam != null && !requestHeaders.equals(requestHeadersParam)) {
requestHeaders = requestHeadersParam;
}
}
/**
* Gets the documents to specify as part of the replication.
*/
@InterfaceAudience.Public
public List<String> getDocIds() {
return documentIDs;
}
/**
* Sets the documents to specify as part of the replication.
*/
@InterfaceAudience.Public
public void setDocIds(List<String> docIds) {
documentIDs = docIds;
}
/**
* The replication's current state, one of {stopped, offline, idle, active}.
*/
@InterfaceAudience.Public
public ReplicationStatus getStatus() {
return status;
}
/**
* The number of completed changes processed, if the task is active, else 0 (observable).
*/
@InterfaceAudience.Public
public int getCompletedChangesCount() {
return completedChangesCount.get();
}
/**
* The total number of changes to be processed, if the task is active, else 0 (observable).
*/
@InterfaceAudience.Public
public int getChangesCount() {
return changesCount.get();
}
/**
* True while the replication is running, False if it's stopped.
* Note that a continuous replication never actually stops; it only goes idle waiting for new
* data to appear.
*/
@InterfaceAudience.Public
public boolean isRunning() {
return running;
}
/**
* The error status of the replication, or null if there have not been any errors since
* it started.
*/
@InterfaceAudience.Public
public Throwable getLastError() {
return error;
}
/**
* Starts the replication, asynchronously.
*/
@InterfaceAudience.Public
public void start() {
if (!db.isOpen()) { // Race condition: db closed before replication starts
Log.w(Log.TAG_SYNC, "Not starting replication because db.isOpen() returned false.");
return;
}
if (running) {
return;
}
db.addReplication(this);
db.addActiveReplication(this);
final CollectionUtils.Functor<Map<String,Object>,Map<String,Object>> xformer = propertiesTransformationBlock;
if (xformer != null) {
revisionBodyTransformationBlock = new CollectionUtils.Functor<RevisionInternal, RevisionInternal>() {
@Override
public RevisionInternal invoke(RevisionInternal rev) {
Map<String,Object> properties = rev.getProperties();
Map<String, Object> xformedProperties = xformer.invoke(properties);
if (xformedProperties == null) {
rev = null;
} else if (xformedProperties != properties) {
assert(xformedProperties != null);
assert(xformedProperties.get("_id").equals(properties.get("_id")));
assert(xformedProperties.get("_rev").equals(properties.get("_rev")));
RevisionInternal nuRev = new RevisionInternal(rev.getProperties(), db);
nuRev.setProperties(xformedProperties);
rev = nuRev;
}
return rev;
}
};
}
this.sessionID = String.format("repl%03d", ++lastSessionID);
Log.v(Log.TAG_SYNC, "%s: STARTING ...", this);
running = true;
lastSequence = null;
checkSession();
db.getManager().getContext().getNetworkReachabilityManager().addNetworkReachabilityListener(this);
}
/**
* Stops replication, asynchronously.
*/
@InterfaceAudience.Public
public void stop() {
if (!running) {
return;
}
Log.v(Log.TAG_SYNC, "%s: STOPPING...", this);
batcher.clear(); // no sense processing any pending changes
continuous = false;
stopRemoteRequests();
cancelPendingRetryIfReady();
db.forgetReplication(this);
if (running && asyncTaskCount <= 0) {
Log.v(Log.TAG_SYNC, "%s: calling stopped()", this);
stopped();
} else {
Log.v(Log.TAG_SYNC, "%s: not calling stopped(). running: %s asyncTaskCount: %d", this, running, asyncTaskCount);
}
}
/**
* Restarts a completed or failed replication.
*/
@InterfaceAudience.Public
public void restart() {
// TODO: add the "started" flag and check it here
stop();
start();
}
/**
* Adds a change delegate that will be called whenever the Replication changes.
*/
@InterfaceAudience.Public
public void addChangeListener(ChangeListener changeListener) {
changeListeners.add(changeListener);
}
/**
* Return a string representation of this replication.
*
* The credentials will be masked in order to avoid passwords leaking into logs.
*/
@Override
@InterfaceAudience.Public
public String toString() {
String maskedRemoteWithoutCredentials = (remote != null ? remote.toExternalForm() : "");
maskedRemoteWithoutCredentials = maskedRemoteWithoutCredentials.replaceAll(":
String name = getClass().getSimpleName() + "@" + Integer.toHexString(hashCode()) + "[" + maskedRemoteWithoutCredentials + "]";
return name;
}
/**
* Sets an HTTP cookie for the Replication.
*
* @param name The name of the cookie.
* @param value The value of the cookie.
* @param path The path attribute of the cookie. If null or empty, will use remote.getPath()
* @param maxAge The maxAge, in milliseconds, that this cookie should be valid for.
* @param secure Whether the cookie should only be sent using a secure protocol (e.g. HTTPS).
* @param httpOnly (ignored) Whether the cookie should only be used when transmitting HTTP, or HTTPS, requests thus restricting access from other, non-HTTP APIs.
*/
@InterfaceAudience.Public
public void setCookie(String name, String value, String path, long maxAge, boolean secure, boolean httpOnly) {
Date now = new Date();
Date expirationDate = new Date(now.getTime() + maxAge);
setCookie(name, value, path, expirationDate, secure, httpOnly);
}
/**
* Sets an HTTP cookie for the Replication.
*
* @param name The name of the cookie.
* @param value The value of the cookie.
* @param path The path attribute of the cookie. If null or empty, will use remote.getPath()
* @param expirationDate The expiration date of the cookie.
* @param secure Whether the cookie should only be sent using a secure protocol (e.g. HTTPS).
* @param httpOnly (ignored) Whether the cookie should only be used when transmitting HTTP, or HTTPS, requests thus restricting access from other, non-HTTP APIs.
*/
@InterfaceAudience.Public
public void setCookie(String name, String value, String path, Date expirationDate, boolean secure, boolean httpOnly) {
if (remote == null) {
throw new IllegalStateException("Cannot setCookie since remote == null");
}
BasicClientCookie2 cookie = new BasicClientCookie2(name, value);
cookie.setDomain(remote.getHost());
if (path != null && path.length() > 0) {
cookie.setPath(path);
} else {
cookie.setPath(remote.getPath());
}
cookie.setExpiryDate(expirationDate);
cookie.setSecure(secure);
List<Cookie> cookies = Arrays.asList((Cookie)cookie);
this.clientFactory.addCookies(cookies);
}
/**
* Deletes an HTTP cookie for the Replication.
*
* @param name The name of the cookie.
*/
@InterfaceAudience.Public
public void deleteCookie(String name) {
this.clientFactory.deleteCookie(name);
}
/**
* The type of event raised by a Replication when any of the following
* properties change: mode, running, error, completed, total.
*/
@InterfaceAudience.Public
public static class ChangeEvent {
private Replication source;
public ChangeEvent(Replication source) {
this.source = source;
}
public Replication getSource() {
return source;
}
}
/**
* A delegate that can be used to listen for Replication changes.
*/
@InterfaceAudience.Public
public static interface ChangeListener {
public void changed(ChangeEvent event);
}
/**
* Removes the specified delegate as a listener for the Replication change event.
*/
@InterfaceAudience.Public
public void removeChangeListener(ChangeListener changeListener) {
changeListeners.remove(changeListener);
}
/**
* Set the Authenticator used for authenticating with the Sync Gateway
*/
@InterfaceAudience.Public
public void setAuthenticator(Authenticator authenticator) {
this.authenticator = authenticator;
}
/**
* Get the Authenticator used for authenticating with the Sync Gateway
*/
@InterfaceAudience.Public
public Authenticator getAuthenticator() {
return authenticator;
}
/**
* @exclude
*/
@InterfaceAudience.Private
public void databaseClosing() {
saveLastSequence();
stop();
clearDbRef();
}
/**
* If we're in the middle of saving the checkpoint and waiting for a response, by the time the
* response arrives _db will be nil, so there won't be any way to save the checkpoint locally.
* To avoid that, pre-emptively save the local checkpoint now.
*
* @exclude
*/
private void clearDbRef() {
if (savingCheckpoint && lastSequence != null && db != null) {
if (!db.isOpen()) {
Log.w(Log.TAG_SYNC, "Not attempting to setLastSequence, db is closed");
} else {
db.setLastSequence(lastSequence, remoteCheckpointDocID(), !isPull());
}
db = null;
}
}
/**
* @exclude
*/
@InterfaceAudience.Private
public String getLastSequence() {
return lastSequence;
}
/**
* @exclude
*/
@InterfaceAudience.Private
public void setLastSequence(String lastSequenceIn) {
if (lastSequenceIn != null && !lastSequenceIn.equals(lastSequence)) {
Log.v(Log.TAG_SYNC, "%s: Setting lastSequence to %s from(%s)", this, lastSequenceIn, lastSequence );
lastSequence = lastSequenceIn;
if (!lastSequenceChanged) {
lastSequenceChanged = true;
workExecutor.schedule(new Runnable() {
@Override
public void run() {
saveLastSequence();
}
}, 2 * 1000, TimeUnit.MILLISECONDS);
}
}
}
@InterfaceAudience.Private
/* package */ void addToCompletedChangesCount(int delta) {
int previousVal = this.completedChangesCount.getAndAdd(delta);
Log.v(Log.TAG_SYNC, "%s: Incrementing completedChangesCount count from %s by adding %d -> %d", this, previousVal, delta, completedChangesCount.get());
notifyChangeListeners();
}
@InterfaceAudience.Private
/* package */ void addToChangesCount(int delta) {
int previousVal = this.changesCount.getAndAdd(delta);
if (changesCount.get() < 0) {
Log.w(Log.TAG_SYNC, "Changes count is negative, this could indicate an error");
}
Log.v(Log.TAG_SYNC, "%s: Incrementing changesCount count from %s by adding %d -> %d", this, previousVal, delta, changesCount.get());
notifyChangeListeners();
}
/**
* @exclude
*/
@InterfaceAudience.Private
public String getSessionID() {
return sessionID;
}
@InterfaceAudience.Private
protected void checkSession() {
// REVIEW : This is not in line with the iOS implementation
if (getAuthenticator() != null && ((AuthenticatorImpl)getAuthenticator()).usesCookieBasedLogin()) {
checkSessionAtPath("/_session");
} else {
fetchRemoteCheckpointDoc();
}
}
@InterfaceAudience.Private
protected void checkSessionAtPath(final String sessionPath) {
Log.d(Log.TAG_SYNC,"%s: checkSessionAtPath() calling asyncTaskStarted()", this);
asyncTaskStarted();
sendAsyncRequest("GET", sessionPath, null, new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(Object result, Throwable error) {
try {
if (error != null) {
// If not at /db/_session, try CouchDB location /_session
if (error instanceof HttpResponseException &&
((HttpResponseException) error).getStatusCode() == 404 &&
sessionPath.equalsIgnoreCase("/_session")) {
checkSessionAtPath("_session");
return;
}
Log.e(Log.TAG_SYNC, this + ": Session check failed", error);
setError(error);
} else {
Map<String, Object> response = (Map<String, Object>) result;
Map<String, Object> userCtx = (Map<String, Object>) response.get("userCtx");
String username = (String) userCtx.get("name");
if (username != null && username.length() > 0) {
Log.d(Log.TAG_SYNC, "%s Active session, logged in as %s", this, username);
fetchRemoteCheckpointDoc();
} else {
Log.d(Log.TAG_SYNC, "%s No active session, going to login", this);
login();
}
}
} finally {
asyncTaskFinished(1);
}
}
});
}
/**
* @exclude
*/
@InterfaceAudience.Private
public abstract void beginReplicating();
@InterfaceAudience.Private
protected void stopped() {
Log.v(Log.TAG_SYNC, "%s: STOPPED", this);
running = false;
notifyChangeListeners();
saveLastSequence();
batcher = null;
if (db != null) {
db.getManager().getContext().getNetworkReachabilityManager().removeNetworkReachabilityListener(this);
}
clearDbRef(); // db no longer tracks me so it won't notify me when it closes; clear ref now
}
@InterfaceAudience.Private
private void notifyChangeListeners() {
updateProgress();
for (ChangeListener listener : changeListeners) {
ChangeEvent changeEvent = new ChangeEvent(this);
listener.changed(changeEvent);
}
}
@InterfaceAudience.Private
protected void login() {
Map<String, String> loginParameters = ((AuthenticatorImpl)getAuthenticator()).loginParametersForSite(remote);
if (loginParameters == null) {
Log.d(Log.TAG_SYNC, "%s: %s has no login parameters, so skipping login", this, getAuthenticator());
fetchRemoteCheckpointDoc();
return;
}
final String loginPath = ((AuthenticatorImpl)getAuthenticator()).loginPathForSite(remote);
Log.d(Log.TAG_SYNC, "%s: Doing login with %s at %s", this, getAuthenticator().getClass(), loginPath);
asyncTaskStarted();
sendAsyncRequest("POST", loginPath, loginParameters, new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(Object result, Throwable e) {
try {
if (e != null) {
Log.d(Log.TAG_SYNC, "%s: Login failed for path: %s", this, loginPath);
setError(e);
}
else {
Log.v(Log.TAG_SYNC, "%s: Successfully logged in!", this);
fetchRemoteCheckpointDoc();
}
} finally {
asyncTaskFinished(1);
}
}
});
}
/**
* @exclude
*/
@InterfaceAudience.Private
public synchronized void asyncTaskStarted() {
if (asyncTaskCount++ == 0) {
updateActive();
}
}
/**
* @exclude
*/
@InterfaceAudience.Private
public synchronized void asyncTaskFinished(int numTasks) {
this.asyncTaskCount -= numTasks;
assert(asyncTaskCount >= 0);
if (asyncTaskCount == 0) {
updateActive();
}
}
/**
* @exclude
*/
@InterfaceAudience.Private
public void updateActive() {
try {
int batcherCount = 0;
if (batcher != null) {
batcherCount = batcher.count();
} else {
Log.w(Log.TAG_SYNC, "%s: batcher object is null.", this);
}
boolean newActive = batcherCount > 0 || asyncTaskCount > 0;
if (active != newActive) {
Log.d(Log.TAG_SYNC, "%s: Progress: set active = %s asyncTaskCount: %d batcherCount: ", this, newActive, asyncTaskCount, batcherCount);
active = newActive;
notifyChangeListeners();
if (!active) {
if (!continuous) {
Log.d(Log.TAG_SYNC, "%s since !continuous, calling stopped()", this);
stopped();
} else if (error != null) /*(revisionsFailed > 0)*/ {
Log.d(Log.TAG_SYNC, "%s: Failed to xfer %d revisions, will retry in %d sec",
this,
revisionsFailed,
RETRY_DELAY);
cancelPendingRetryIfReady();
scheduleRetryIfReady();
}
}
}
} catch (Exception e) {
Log.e(Log.TAG_SYNC, "Exception in updateActive()", e);
}
}
/**
* @exclude
*/
@InterfaceAudience.Private
public void addToInbox(RevisionInternal rev) {
batcher.queueObject(rev);
updateActive();
}
@InterfaceAudience.Private
protected void processInbox(RevisionList inbox) {
}
/**
* @exclude
*/
@InterfaceAudience.Private
public void sendAsyncRequest(String method, String relativePath, Object body, RemoteRequestCompletionBlock onCompletion) {
try {
String urlStr = buildRelativeURLString(relativePath);
URL url = new URL(urlStr);
sendAsyncRequest(method, url, body, onCompletion);
} catch (MalformedURLException e) {
Log.e(Log.TAG_SYNC, "Malformed URL for async request", e);
}
}
@InterfaceAudience.Private
/* package */ String buildRelativeURLString(String relativePath) {
// the following code is a band-aid for a system problem in the codebase
// where it is appending "relative paths" that start with a slash, eg:
// which is not compatible with the way the java url concatonation works.
String remoteUrlString = remote.toExternalForm();
if (remoteUrlString.endsWith("/") && relativePath.startsWith("/")) {
remoteUrlString = remoteUrlString.substring(0, remoteUrlString.length() - 1);
}
return remoteUrlString + relativePath;
}
/**
* @exclude
*/
@InterfaceAudience.Private
public void sendAsyncRequest(String method, URL url, Object body, final RemoteRequestCompletionBlock onCompletion) {
final RemoteRequest request = new RemoteRequest(workExecutor, clientFactory, method, url, body, getLocalDatabase(), getHeaders(), onCompletion);
request.setAuthenticator(getAuthenticator());
request.setOnPreCompletion(new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(Object result, Throwable e) {
if (serverType == null && result instanceof HttpResponse) {
HttpResponse response = (HttpResponse) result;
Header serverHeader = response.getFirstHeader("Server");
if (serverHeader != null) {
String serverVersion = serverHeader.getValue();
Log.v(Log.TAG_SYNC, "serverVersion: %s", serverVersion);
serverType = serverVersion;
}
}
}
});
request.setOnPostCompletion(new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(Object result, Throwable e) {
requests.remove(request);
}
});
if (remoteRequestExecutor.isTerminated()) {
String msg = "sendAsyncRequest called, but remoteRequestExecutor has been terminated";
throw new IllegalStateException(msg);
}
Future future = remoteRequestExecutor.submit(request);
requests.put(request, future);
}
/**
* @exclude
*/
@InterfaceAudience.Private
public void sendAsyncMultipartDownloaderRequest(String method, String relativePath, Object body, Database db, RemoteRequestCompletionBlock onCompletion) {
try {
String urlStr = buildRelativeURLString(relativePath);
URL url = new URL(urlStr);
RemoteMultipartDownloaderRequest request = new RemoteMultipartDownloaderRequest(
workExecutor,
clientFactory,
method,
url,
body,
db,
getHeaders(),
onCompletion);
request.setAuthenticator(getAuthenticator());
remoteRequestExecutor.execute(request);
} catch (MalformedURLException e) {
Log.e(Log.TAG_SYNC, "Malformed URL for async request", e);
}
}
/**
* @exclude
*/
@InterfaceAudience.Private
public void sendAsyncMultipartRequest(String method, String relativePath, MultipartEntity multiPartEntity, RemoteRequestCompletionBlock onCompletion) {
URL url = null;
try {
String urlStr = buildRelativeURLString(relativePath);
url = new URL(urlStr);
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
RemoteMultipartRequest request = new RemoteMultipartRequest(
workExecutor,
clientFactory,
method,
url,
multiPartEntity,
getLocalDatabase(),
getHeaders(),
onCompletion);
request.setAuthenticator(getAuthenticator());
remoteRequestExecutor.execute(request);
}
/**
* CHECKPOINT STORAGE: *
*/
@InterfaceAudience.Private
/* package */ void maybeCreateRemoteDB() {
// Pusher overrides this to implement the .createTarget option
}
/**
* This is the _local document ID stored on the remote server to keep track of state.
* Its ID is based on the local database ID (the private one, to make the result unguessable)
* and the remote database's URL.
*
* @exclude
*/
@InterfaceAudience.Private
public String remoteCheckpointDocID() {
if (remoteCheckpointDocID != null) {
return remoteCheckpointDocID;
} else {
// TODO: Needs to be consistent with -hasSameSettingsAs: --
// TODO: If a.remoteCheckpointID == b.remoteCheckpointID then [a hasSameSettingsAs: b]
if (db == null) {
return null;
}
// canonicalization: make sure it produces the same checkpoint id regardless of
// ordering of filterparams / docids
Map<String, Object> filterParamsCanonical = null;
if (getFilterParams() != null) {
filterParamsCanonical = new TreeMap<String, Object>(getFilterParams());
}
List<String> docIdsSorted = null;
if (getDocIds() != null) {
docIdsSorted = new ArrayList<String>(getDocIds());
Collections.sort(docIdsSorted);
}
// use a treemap rather than a dictionary for purposes of canonicalization
Map<String, Object> spec = new TreeMap<String, Object>();
spec.put("localUUID", db.privateUUID());
spec.put("remoteURL", remote.toExternalForm());
spec.put("push", !isPull());
spec.put("continuous", isContinuous());
if (getFilter() != null) {
spec.put("filter", getFilter());
}
if (filterParamsCanonical != null) {
spec.put("filterParams", filterParamsCanonical);
}
if (docIdsSorted != null) {
spec.put("docids", docIdsSorted);
}
byte[] inputBytes = null;
try {
inputBytes = db.getManager().getObjectMapper().writeValueAsBytes(spec);
} catch (IOException e) {
throw new RuntimeException(e);
}
remoteCheckpointDocID = Misc.TDHexSHA1Digest(inputBytes);
return remoteCheckpointDocID;
}
}
@InterfaceAudience.Private
private boolean is404(Throwable e) {
if (e instanceof HttpResponseException) {
return ((HttpResponseException) e).getStatusCode() == 404;
}
return false;
}
/**
* @exclude
*/
@InterfaceAudience.Private
public void fetchRemoteCheckpointDoc() {
lastSequenceChanged = false;
String checkpointId = remoteCheckpointDocID();
final String localLastSequence = db.lastSequenceWithCheckpointId(checkpointId);
asyncTaskStarted();
sendAsyncRequest("GET", "/_local/" + checkpointId, null, new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(Object result, Throwable e) {
try {
if (e != null && !is404(e)) {
Log.w(Log.TAG_SYNC, "%s: error getting remote checkpoint", e, this);
setError(e);
} else {
if (e != null && is404(e)) {
Log.d(Log.TAG_SYNC, "%s: 404 error getting remote checkpoint %s, calling maybeCreateRemoteDB", this, remoteCheckpointDocID());
maybeCreateRemoteDB();
}
Map<String, Object> response = (Map<String, Object>) result;
remoteCheckpoint = response;
String remoteLastSequence = null;
if (response != null) {
remoteLastSequence = (String) response.get("lastSequence");
}
if (remoteLastSequence != null && remoteLastSequence.equals(localLastSequence)) {
lastSequence = localLastSequence;
Log.d(Log.TAG_SYNC, "%s: Replicating from lastSequence=%s", this, lastSequence);
} else {
Log.d(Log.TAG_SYNC, "%s: lastSequence mismatch: I had: %s, remote had: %s", this, localLastSequence, remoteLastSequence);
}
beginReplicating();
}
} finally {
asyncTaskFinished(1);
}
}
});
}
/**
* @exclude
*/
@InterfaceAudience.Private
public void saveLastSequence() {
if (!lastSequenceChanged) {
return;
}
if (savingCheckpoint) {
// If a save is already in progress, don't do anything. (The completion block will trigger
// another save after the first one finishes.)
overdueForSave = true;
return;
}
lastSequenceChanged = false;
overdueForSave = false;
Log.d(Log.TAG_SYNC, "%s: saveLastSequence() called. lastSequence: %s", this, lastSequence);
final Map<String, Object> body = new HashMap<String, Object>();
if (remoteCheckpoint != null) {
body.putAll(remoteCheckpoint);
}
body.put("lastSequence", lastSequence);
String remoteCheckpointDocID = remoteCheckpointDocID();
if (remoteCheckpointDocID == null) {
Log.w(Log.TAG_SYNC, "%s: remoteCheckpointDocID is null, aborting saveLastSequence()", this);
return;
}
savingCheckpoint = true;
final String checkpointID = remoteCheckpointDocID;
Log.d(Log.TAG_SYNC, "%s: put remote _local document. checkpointID: %s", this, checkpointID);
sendAsyncRequest("PUT", "/_local/" + checkpointID, body, new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(Object result, Throwable e) {
savingCheckpoint = false;
if (e != null) {
Log.w(Log.TAG_SYNC, "%s: Unable to save remote checkpoint", e, this);
}
if (db == null) {
Log.w(Log.TAG_SYNC, "%s: Database is null, ignoring remote checkpoint response", this);
return;
}
if (!db.isOpen()) {
Log.w(Log.TAG_SYNC, "%s: Database is closed, ignoring remote checkpoint response", this);
return;
}
if (e != null) {
// Failed to save checkpoint:
switch (getStatusFromError(e)) {
case Status.NOT_FOUND:
remoteCheckpoint = null; // doc deleted or db reset
overdueForSave = true; // try saving again
break;
case Status.CONFLICT:
refreshRemoteCheckpointDoc();
break;
default:
// TODO: On 401 or 403, and this is a pull, remember that remote
// TODo: is read-only & don't attempt to read its checkpoint next time.
break;
}
} else {
// Saved checkpoint:
Map<String, Object> response = (Map<String, Object>) result;
body.put("_rev", response.get("rev"));
remoteCheckpoint = body;
db.setLastSequence(lastSequence, checkpointID, !isPull());
}
if (overdueForSave) {
saveLastSequence();
}
}
});
}
@InterfaceAudience.Public
public boolean goOffline() {
if (!online) {
return false;
}
if (db == null) {
return false;
}
db.runAsync(new AsyncTask() {
@Override
public void run(Database database) {
Log.d(Log.TAG_SYNC, "%s: Going offline", this);
online = false;
stopRemoteRequests();
updateProgress();
notifyChangeListeners();
}
});
return true;
}
@InterfaceAudience.Public
public boolean goOnline() {
if (online) {
return false;
}
if (db == null) {
return false;
}
db.runAsync(new AsyncTask() {
@Override
public void run(Database database) {
Log.d(Log.TAG_SYNC, "%s: Going online", this);
online = true;
if (running) {
lastSequence = null;
setError(null);
}
remoteRequestExecutor = Executors.newCachedThreadPool();
checkSession();
notifyChangeListeners();
}
});
return true;
}
@InterfaceAudience.Private
private void stopRemoteRequests() {
Log.v(Log.TAG_SYNC, "%s: stopRemoteRequests() cancelling: %d requests", this, requests.size());
for (RemoteRequest request : requests.keySet()) {
Future future = requests.get(request);
if (future != null) {
Log.v(Log.TAG_SYNC, "%s: cancelling future %s for request: %s isCancelled: %s isDone: %s", this, future, request, future.isCancelled(), future.isDone());
boolean result = future.cancel(true);
Log.v(Log.TAG_SYNC, "%s: cancelled future, result: %s", this, result);
}
}
}
@InterfaceAudience.Private
/* package */ void updateProgress() {
if (!isRunning()) {
status = ReplicationStatus.REPLICATION_STOPPED;
} else if (!online) {
status = ReplicationStatus.REPLICATION_OFFLINE;
} else {
if (active) {
status = ReplicationStatus.REPLICATION_ACTIVE;
} else {
status = ReplicationStatus.REPLICATION_IDLE;
}
}
}
@InterfaceAudience.Private
protected void setError(Throwable throwable) {
// TODO
/*
if (error.code == NSURLErrorCancelled && $equal(error.domain, NSURLErrorDomain))
return;
*/
if (throwable != error) {
Log.e(Log.TAG_SYNC, "%s: Progress: set error = %s", this, throwable);
error = throwable;
notifyChangeListeners();
}
}
@InterfaceAudience.Private
protected void revisionFailed() {
// Remember that some revisions failed to transfer, so we can later retry.
++revisionsFailed;
}
protected RevisionInternal transformRevision(RevisionInternal rev) {
if(revisionBodyTransformationBlock != null) {
try {
final int generation = rev.getGeneration();
RevisionInternal xformed = revisionBodyTransformationBlock.invoke(rev);
if (xformed == null)
return null;
if (xformed != rev) {
assert(xformed.getDocId().equals(rev.getDocId()));
assert(xformed.getRevId().equals(rev.getRevId()));
assert(xformed.getProperties().get("_revisions").equals(rev.getProperties().get("_revisions")));
if (xformed.getProperties().get("_attachments") != null) {
// Insert 'revpos' properties into any attachments added by the callback:
RevisionInternal mx = new RevisionInternal(xformed.getProperties(), db);
xformed = mx;
mx.mutateAttachments(new CollectionUtils.Functor<Map<String,Object>,Map<String,Object>>() {
public Map<String, Object> invoke(Map<String, Object> info) {
if (info.get("revpos") != null) {
return info;
}
if(info.get("data") == null) {
throw new IllegalStateException("Transformer added attachment without adding data");
}
Map<String,Object> nuInfo = new HashMap<String, Object>(info);
nuInfo.put("revpos",generation);
return nuInfo;
}
});
}
rev = xformed;
}
}catch (Exception e) {
Log.w(Log.TAG_SYNC,"%s: Exception transforming a revision of doc '%s", e, this, rev.getDocId());
}
}
return rev;
}
/**
* Called after a continuous replication has gone idle, but it failed to transfer some revisions
* and so wants to try again in a minute. Should be overridden by subclasses.
*/
@InterfaceAudience.Private
protected void retry() {
setError(null);
}
@InterfaceAudience.Private
protected void retryIfReady() {
if (!running) {
return;
}
if (online) {
Log.d(Log.TAG_SYNC, "%s: RETRYING, to transfer missed revisions", this);
revisionsFailed = 0;
cancelPendingRetryIfReady();
retry();
} else {
scheduleRetryIfReady();
}
}
@InterfaceAudience.Private
protected void cancelPendingRetryIfReady() {
if (retryIfReadyFuture != null && retryIfReadyFuture.isCancelled() == false) {
retryIfReadyFuture.cancel(true);
}
}
@InterfaceAudience.Private
protected void scheduleRetryIfReady() {
retryIfReadyFuture = workExecutor.schedule(new Runnable() {
@Override
public void run() {
retryIfReady();
}
}, RETRY_DELAY, TimeUnit.SECONDS);
}
@InterfaceAudience.Private
private int getStatusFromError(Throwable t) {
if (t instanceof CouchbaseLiteException) {
CouchbaseLiteException couchbaseLiteException = (CouchbaseLiteException) t;
return couchbaseLiteException.getCBLStatus().getCode();
}
return Status.UNKNOWN;
}
/**
* Variant of -fetchRemoveCheckpointDoc that's used while replication is running, to reload the
* checkpoint to get its current revision number, if there was an error saving it.
*/
@InterfaceAudience.Private
private void refreshRemoteCheckpointDoc() {
Log.d(Log.TAG_SYNC, "%s: Refreshing remote checkpoint to get its _rev...", this);
savingCheckpoint = true;
asyncTaskStarted();
sendAsyncRequest("GET", "/_local/" + remoteCheckpointDocID(), null, new RemoteRequestCompletionBlock() {
@Override
public void onCompletion(Object result, Throwable e) {
try {
if (db == null) {
Log.w(Log.TAG_SYNC, "%s: db == null while refreshing remote checkpoint. aborting", this);
return;
}
savingCheckpoint = false;
if (e != null && getStatusFromError(e) != Status.NOT_FOUND) {
Log.e(Log.TAG_SYNC, "%s: Error refreshing remote checkpoint", e, this);
} else {
Log.d(Log.TAG_SYNC, "%s: Refreshed remote checkpoint: %s", this, result);
remoteCheckpoint = (Map<String, Object>) result;
lastSequenceChanged = true;
saveLastSequence(); // try saving again
}
} finally {
asyncTaskFinished(1);
}
}
});
}
@InterfaceAudience.Private
protected Status statusFromBulkDocsResponseItem(Map<String, Object> item) {
try {
if (!item.containsKey("error")) {
return new Status(Status.OK);
}
String errorStr = (String) item.get("error");
if (errorStr == null || errorStr.isEmpty()) {
return new Status(Status.OK);
}
// 'status' property is nonstandard; TouchDB returns it, others don't.
String statusString = (String) item.get("status");
int status = Integer.parseInt(statusString);
if (status >= 400) {
return new Status(status);
}
// If no 'status' present, interpret magic hardcoded CouchDB error strings:
if (errorStr.equalsIgnoreCase("unauthorized")) {
return new Status(Status.UNAUTHORIZED);
} else if (errorStr.equalsIgnoreCase("forbidden")) {
return new Status(Status.FORBIDDEN);
} else if (errorStr.equalsIgnoreCase("conflict")) {
return new Status(Status.CONFLICT);
} else {
return new Status(Status.UPSTREAM_ERROR);
}
} catch (Exception e) {
Log.e(Database.TAG, "Exception getting status from " + item, e);
}
return new Status(Status.OK);
}
@Override
@InterfaceAudience.Private
public void networkReachable() {
goOnline();
}
@Override
@InterfaceAudience.Private
public void networkUnreachable() {
goOffline();
}
@InterfaceAudience.Private
/* package */ boolean serverIsSyncGatewayVersion(String minVersion) {
String prefix = "Couchbase Sync Gateway/";
if (serverType == null) {
return false;
} else {
if (serverType.startsWith(prefix)) {
String versionString = serverType.substring(prefix.length());
return versionString.compareTo(minVersion) >= 0;
}
}
return false;
}
@InterfaceAudience.Private
/* package */ void setServerType(String serverType) {
this.serverType = serverType;
}
@InterfaceAudience.Private
/* package */ HttpClientFactory getClientFactory() {
return clientFactory;
}
} |
package gnu.bytecode;
import java.util.HashMap;
public class Scope
{
/** The enclosing scope. */
Scope parent;
Scope nextSibling;
Scope firstChild, lastChild;
/** If true, don't call freeLocal on our variables (yet). */
boolean preserved;
boolean autoPop;
Label start;
Label end;
Variable vars;
Variable last_var;
public Scope()
{
}
public Scope (Label start, Label end)
{
this.start = start;
this.end = end;
}
// Variable lookup (String name);
public final Variable firstVar () { return vars; }
public VarEnumerator allVars () { return new VarEnumerator (this); }
public Label getStartLabel() { return start; }
public Label getEndLabel() { return end; }
/** Link this scope as the next child of its parent scope. */
public void linkChild (Scope parent)
{
this.parent = parent;
if (parent == null)
return;
if (parent.lastChild == null)
parent.firstChild = this;
else
parent.lastChild.nextSibling = this;
parent.lastChild = this;
}
public Variable addVariable (CodeAttr code, Type type, String name)
{
Variable var = new Variable(name, type);
addVariable (code, var);
return var;
}
public void addVariable (Variable var)
{
if (last_var == null)
vars = var;
else
last_var.next = var;
last_var = var;
var.scope = this;
}
/* Add a new Variable, linking it in after a given Variable, */
public void addVariableAfter (Variable prev, Variable var)
{
if (prev == null)
{ // Put first
var.next = vars;
vars = var;
}
else
{
var.next = prev.next;
prev.next = var;
}
if (last_var == prev)
last_var = var;
if (var.next == var)
throw new Error("cycle");
var.scope = this;
}
public void addVariable (CodeAttr code, Variable var)
{
addVariable (var);
if (var.isSimple() && code != null)
var.allocateLocal(code);
}
/**
* Return a variable the scope, by numerical index.
* @param index the number of the variable
*/
public Variable getVariable(int index) {
Variable var = vars;
while (--index >= 0)
var = var.next;
return var;
}
/** Fix duplicate names.
* This is needed for Android, since otherwise dex complains.
*/
public void fixParamNames(HashMap<String,Variable> map) {
for (Variable var = firstVar(); var != null;
var = var.nextVar()) {
String name = var.getName();
if (name != null) {
String xname = name;
Variable old;
for (int i = 0; (old = map.get(xname)) != null; i++)
xname = name + '$' + i;
if (name != xname)
var.setName(xname);
map.put(xname, var);
}
}
}
static boolean equals (byte[] name1, byte[] name2) {
if (name1.length != name2.length)
return false;
if (name1 == name2)
return true;
for (int i = name1.length; --i >= 0; )
if (name1[i] != name2[i])
return false;
return true;
}
public void setStartPC(CodeAttr code)
{
if (start == null)
start = new Label();
boolean reachable = code.reachableHere();
start.define(code);
code.setReachable(reachable);
}
/** Should be called at the start of a logical function - inlined or not. */
public void noteStartFunction(CodeAttr code)
{
setStartPC(code);
}
/**
* Search by name for a Variable in this Scope (only).
* @param name name to search for
* @return the Variable, or null if not found (in this scope).
*/
public Variable lookup (String name) {
for (Variable var = vars; var != null; var = var.next) {
if (name.equals(var.name))
return var;
}
return null;
}
/** Make local variable slots of this scope available for re-use.
* However, if the 'preserved' flag is set, defer doing so until
* we exit a non-preserved Scope. */
void freeLocals (CodeAttr code)
{
if (preserved)
return;
for (Variable var = vars; var != null; var = var.next)
{
if (var.isSimple () && ! var.dead ())
var.freeLocal(code);
}
for (Scope child = firstChild; child != null; child = child.nextSibling)
{
if (child.preserved)
{
child.preserved = false;
child.freeLocals(code);
}
}
}
/* DEBUG
static int counter; int id=++counter;
public String toString() { return "Scope#"+id; }
*/
} |
package org.xwiki.tool.packager.internal;
import javax.inject.Named;
import javax.inject.Singleton;
import org.xwiki.classloader.xwiki.internal.ThreadClassloaderExecutionContextInitializer;
import org.xwiki.component.annotation.Component;
import org.xwiki.context.ExecutionContext;
import org.xwiki.context.ExecutionContextException;
import org.xwiki.context.ExecutionContextInitializer;
/**
* Cancel {@link ThreadClassloaderExecutionContextInitializer} to not mess with the Maven classloader.
*
* @version $Id$
* @since 9.7RC1
*/
@Component
@Singleton
@Named("threadclassloader")
public class MavenBuildThreadClassloaderExecutionContextInitializer implements ExecutionContextInitializer
{
@Override
public void initialize(ExecutionContext context) throws ExecutionContextException
{
// Cancel
}
} |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.cwoodson.pigaddons.rpig;
import com.cwoodson.pigaddons.rpig.rfunctions.Utils;
import com.cwoodson.pigaddons.rpig.rutils.RConnector;
import com.cwoodson.pigaddons.rpig.rutils.RException;
import com.cwoodson.pigaddons.rpig.rutils.RJriConnector;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import org.apache.pig.FuncSpec;
import org.apache.pig.PigServer;
import org.apache.pig.backend.executionengine.ExecException;
import org.apache.pig.impl.PigContext;
import org.apache.pig.scripting.ScriptEngine;
import org.apache.pig.tools.pigstats.PigStats;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author connor-woodson
*/
public class RScriptEngine extends ScriptEngine
{
private static final Logger log = LoggerFactory.getLogger(RScriptEngine.class);
private static class Interpreter
{
static final RConnector rEngine;
static final Set<String> internalNames = new HashSet<String>();
static final Set<String> registeredFuncs = new HashSet<String>();
static
{
Runtime.getRuntime().addShutdownHook(new RShutdown());
try {
rEngine = RJriConnector.create();
if(rEngine == null)
{
log.error("Rengine failed to be created. Exiting program.");
System.exit(1);
}
rEngine.voidEval("if('rJava' %in% rownames(installed.packages()) == FALSE) { install.packages('rJava', dependencies=TRUE, repos='http://cran.us.r-project.org') }");
rEngine.voidEval("library('rJava')");
rEngine.voidEval(".jinit()");
rEngine.voidEval(".jaddClassPath('" + getJarPath(Utils.class) + "')");
// set up helpful functions
rEngine.voidEval("Utils.logInfo <<- function(info) { .jcall('com/cwoodson/pigaddons/rpig/rfunctions/Utils', 'LogInfo', info) }");
rEngine.voidEval("Utils.logError <<- function(error) { .jcall('com/cwoodson/pigaddons/rpig/rfunctions/Utils', 'LogError', error) }");
rEngine.voidEval("Utils.installPackage <<- function(name) { if(!is.character(name)) { Utils.logError('Utils.installPackage not called on a string'); return(FALSE) }; if(name %in% rownames(installed.packages()) == FALSE) { install.packages(name, dependencies=TRUE, repos='http://cran.us.r-project.org') }; return(TRUE) }");
internalNames.add("Utils.logError");
internalNames.add("Utils.installPackage");
// set up JavaGD
//rEngine.voidEval("Sys.setenv('JAVAGD_USE_RJAVA'=TRUE)");
//rEngine.voidEval("Sys.setenv('JAVAGD_CLASS_NAME'='com.cwoodson.pigaddons.rfunctions.RGraphics')");
//rEngine.voidEval("Utils.installPackage('JavaGD')");
//rEngine.voidEval("library('JavaGD')");
String width_str = System.getProperty("rpig.gfx.width");
Integer width;
try {
width = width_str == null ? 640 : Integer.parseInt(width_str);
} catch(NumberFormatException nfe) {
width = 640;
}
String height_str = System.getProperty("rpig.gfx.height");
Integer height;
try {
height = height_str == null ? 480 : Integer.parseInt(height_str);
} catch(NumberFormatException nfe) {
height = 480;
}
String ps_str = System.getProperty("rpig.gfx.ps");
Integer ps;
try {
ps = ps_str == null ? 12 : Integer.parseInt(ps_str);
} catch(NumberFormatException nfe) {
ps = 12;
}
//rEngine.voidEval("JavaGD('rPig GFX', width=" + width.toString()
// + ", height=" + height.toString() + ", ps=" + ps.toString() + ")");
// set up graphics functions
// save - can save internally by adding to a map<String, Image>
// save to file
// flume?
// email?
// set up Pig functions
// compile/bind
} catch(RException re) {
log.error("RException thrown", re);
throw new RuntimeException("Unable to initialize R", re);
} catch(FileNotFoundException fnfe) {
log.error("FileNotFoundException thrown", fnfe);
throw new RuntimeException("Unable to initialize RScriptEngine", fnfe);
}
}
static void init(String path, PigContext pigContext) throws IOException
{
// rengine execute its stuff
InputStream is = getScriptAsStream(path);
try {
execFile(is, path, pigContext);
} finally {
is.close();
}
}
static void execFile(InputStream script, String path, PigContext pigContext) throws ExecException
{
try {
rEngine.execFile(script, path);
} catch(RException re) {
throw new ExecException(re);
}
}
}
@Override
public void registerFunctions(String path, String namespace, PigContext context) throws IOException {
Interpreter.init(path, context);
namespace = (namespace == null) ? "" : namespace + NAMESPACE_SEPARATOR;
for(String name : Interpreter.rEngine.lsFunctions())
{
if(!Interpreter.internalNames.contains(name))
{
if(Interpreter.registeredFuncs.contains(name)) {
log.warn("R Function " + name + " has already been registered");
continue;
}
FuncSpec funcspec = new FuncSpec(RFunction.class.getCanonicalName() + "('" + name + "')");
context.registerFunction(namespace + name, funcspec);
Interpreter.registeredFuncs.add(name);
log.info("Registered Function: " + namespace + name);
}
}
context.addScriptFile(path);
}
@Override
protected Map<String, List<PigStats>> main(PigContext pigContext, String scriptFile) throws IOException {
PigServer pigServer = new PigServer(pigContext, false);
String thisJarPath = getJarPath(RScriptEngine.class);
if(thisJarPath != null)
{
pigServer.registerJar(thisJarPath);
}
File f = new File(scriptFile);
if(!f.canRead())
{
log.error("Unable to open specified file");
throw new IOException("Can't read file: " + scriptFile);
}
try {
Interpreter.init(scriptFile, pigServer.getPigContext());
} finally {
}
return getPigStatsMap();
}
@Override
protected String getScriptingLang() {
return "rPig";
}
@Override
protected Map<String, Object> getParamsFromVariables() throws IOException {
RConnector rEngine = Interpreter.rEngine;
Map<String, Object> result = new HashMap<String, Object>();
List<String> variables = rEngine.lsVariables();
for(String v : variables)
{
if(!Interpreter.internalNames.contains(v))
{
try {
result.put(v, rEngine.eval(v));
} catch(RException re) {
log.error("Error evaluating variable " + v, re);
throw new IOException("Error evaluating variable " + v, re);
}
}
}
return result;
}
public static RConnector getEngine()
{
return Interpreter.rEngine;
}
private static class RShutdown extends Thread
{
@Override
public void run()
{
try {
if(Interpreter.rEngine != null)
{
Interpreter.rEngine.terminate();
}
} catch(Exception e) {
}
}
}
} |
package org.usfirst.frc.team166.robot.subsystems;
import edu.wpi.first.wpilibj.AnalogGyro;
import edu.wpi.first.wpilibj.CANTalon;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.PIDSourceType;
import edu.wpi.first.wpilibj.RobotDrive;
//import edu.wpi.first.wpilibj.TalonSRX;
import edu.wpi.first.wpilibj.Servo;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.interfaces.Gyro;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import org.usfirst.frc.team166.robot.PIDSpeedController;
import org.usfirst.frc.team166.robot.Robot;
import org.usfirst.frc.team166.robot.RobotMap;
import org.usfirst.frc.team166.robot.commands.drive.DriveWithJoysticks;
public class Drive extends Subsystem {
double distancePerPulse = 12 / 56320.0; // this makes perfect cents // no it doesn't it makes 2.1306818181...
double gyroConstant = -0.3 / 10.0;
double driveSpeedModifierConstant = .7;
double gyroVal = 0;
boolean highGear;
boolean neutral;
boolean isShiftingOK;
double highGearValue = 0.0;
double lowGearValue = 1.0;
// TalonSRX leftTopVictor = new TalonSRX(RobotMap.Pwm.leftTopDrive);
// TalonSRX leftBotVictor = new TalonSRX(RobotMap.Pwm.leftBotDrive);
// TalonSRX rightTopVictor = new TalonSRX(RobotMap.Pwm.rightTopDrive);
// TalonSRX rightBotVictor = new TalonSRX(RobotMap.Pwm.rightBotDrive);
CANTalon leftTopCanTalon = new CANTalon(0); // These values are CAN IDs, they might be different.
CANTalon leftBotCanTalon = new CANTalon(1);
CANTalon rightTopCanTalon = new CANTalon(2);
CANTalon rightBotCanTalon = new CANTalon(3);
Servo leftTransmissionServo = new Servo(RobotMap.Pwm.leftTransmissionServoPort);
Servo rightTransmissionServo = new Servo(RobotMap.Pwm.rightTransmissionServoPort);// dont be dumb by putting double
Encoder leftEncoder = new Encoder(RobotMap.Digital.leftEncoderA, RobotMap.Digital.leftEncoderB);// more
Encoder rightEncoder = new Encoder(RobotMap.Digital.rightEncoderA, RobotMap.Digital.rightEncoderB);
Encoder leftEncoder1 = new Encoder(RobotMap.Digital.leftEncoder1A, RobotMap.Digital.leftEncoder1B); // delete these
// later when we have the real robot
Encoder rightEncoder1 = new Encoder(RobotMap.Digital.rightEncoder1A, RobotMap.Digital.rightEncoder1B);
PIDSpeedController leftTopPID = new PIDSpeedController(leftEncoder, leftTopCanTalon, "Drive", "LeftTopPID"); // specify
PIDSpeedController leftBotPID = new PIDSpeedController(leftEncoder1, leftBotCanTalon, "Drive", "LeftBotPID");
PIDSpeedController rightTopPID = new PIDSpeedController(rightEncoder, rightTopCanTalon, "Drive", "RightTopPID");
PIDSpeedController rightBotPID = new PIDSpeedController(rightEncoder1, rightBotCanTalon, "Drive", "RightBotPID");
// bot
// motors
Gyro gyro = new AnalogGyro(RobotMap.Analog.gyroPort);
RobotDrive tankDrive = new RobotDrive(leftTopPID, leftBotPID, rightTopPID, rightBotPID);
// RobotDrive tankDrive = new RobotDrive(leftTopVictor, leftBotVictor, rightTopVictor, rightBotVictor);
public Drive() {
leftEncoder.setDistancePerPulse(distancePerPulse);
rightEncoder.setDistancePerPulse(distancePerPulse);
leftEncoder.setPIDSourceType(PIDSourceType.kRate);
rightEncoder.setPIDSourceType(PIDSourceType.kRate);
leftEncoder1.setDistancePerPulse(distancePerPulse);
rightEncoder1.setDistancePerPulse(distancePerPulse);
leftEncoder1.setPIDSourceType(PIDSourceType.kRate); // delete these later
rightEncoder1.setPIDSourceType(PIDSourceType.kRate);
}
public double getGyroOffset() {
gyroVal = Robot.drive.getGyro() * gyroConstant;
if (Math.abs(gyroVal) > (1.0 - driveSpeedModifierConstant)) {
gyroVal = (1.0 - driveSpeedModifierConstant) * Math.abs(gyroVal) / gyroVal; // sets gyroVal to either 1 or
}
return gyroVal;
}
public void driveWithGyro() {
double rightPower = Robot.oi.getRightYAxis() * driveSpeedModifierConstant;
double leftPower = Robot.oi.getLeftYAxis() * driveSpeedModifierConstant;
double power = 0;
power = (rightPower + leftPower) / 2;
if (Math.abs(Robot.oi.getRightYAxis()) > .1) {
tankDrive.tankDrive(power + getGyroOffset(), power - getGyroOffset());
}
}
public void highGear() {
if (isShiftingOK == true) {
leftTransmissionServo.set(highGearValue);
rightTransmissionServo.set(highGearValue);
highGear = true;
neutral = false;
leftEncoder.setDistancePerPulse(3 * distancePerPulse);
rightEncoder.setDistancePerPulse(3 * distancePerPulse);
leftEncoder1.setDistancePerPulse(3 * distancePerPulse); // delete this later
rightEncoder1.setDistancePerPulse(3 * distancePerPulse);
}
}
public void lowGear() {
if (isShiftingOK == true) {
leftTransmissionServo.set(lowGearValue);
rightTransmissionServo.set(lowGearValue);
highGear = false;
neutral = false;
leftEncoder.setDistancePerPulse(distancePerPulse);
rightEncoder.setDistancePerPulse(distancePerPulse);
leftEncoder1.setDistancePerPulse(distancePerPulse); // delete this later
rightEncoder1.setDistancePerPulse(distancePerPulse); // delete this later
}
}
public void neutral() {
leftTransmissionServo.set(0.5);
rightTransmissionServo.set(0.5);
neutral = true;
}
public void driveWithJoysticks() {
// integrate gyro into drive. i.e. correct for imperfect forward motion
// with a proportional controller
if ((Math.abs(Robot.oi.getLeftYAxis()) > .1) || (Math.abs(Robot.oi.getRightYAxis()) > .1)) {
isShiftingOK = true;
SmartDashboard.putNumber("Gyro Offset", getGyroOffset());
tankDrive.tankDrive(Robot.oi.getLeftYAxis(), Robot.oi.getRightYAxis()); // if not trying to go straight, //
} else {
isShiftingOK = false;
stop();
}
}
public void driveWithJoysticksBackward() {
// integrate gyro into drive. i.e. correct for imperfect forward motion
// with a proportional controller
double rightPower = -Robot.oi.getRightYAxis() * driveSpeedModifierConstant;
boolean areJoysticksSimilar = false;
if ((Math.abs(Robot.oi.getLeftYAxis()) > .1) || (Math.abs(Robot.oi.getRightYAxis()) > .1)) {
isShiftingOK = true;
SmartDashboard.putNumber("Gyro Offset", getGyroOffset());
SmartDashboard.putNumber("Right Power", rightPower);
SmartDashboard.putBoolean("areJoysticksSimilar", areJoysticksSimilar);
tankDrive.tankDrive(-Robot.oi.getRightYAxis(), -Robot.oi.getLeftYAxis());
} else {
isShiftingOK = false;
stop();
}
}
public void stop() {
tankDrive.tankDrive(0, 0);
}
public void resetGyro() {
gyro.reset();
}
public void resetEncoders() {
leftEncoder.reset();
rightEncoder.reset();
}
public double getLeftEncoder() {
SmartDashboard.putNumber("Left Encoder", leftEncoder.getRate());
return leftEncoder.getRate();
}
public double getRightEncoder() {
SmartDashboard.putNumber("Right Encoder", rightEncoder.getRate());
return rightEncoder.getRate();
}
public double getDistance() {
return (((getLeftEncoder() + getRightEncoder()) / 2.0) / 1024.0) / 31.4;
}
public double getGyro() {
return gyro.getAngle();
}
public void turnAngle(double angle) {
double power = (angle - getGyro()) / angle;
if (getGyro() < angle - 7.0) {
tankDrive.tankDrive(power, -power);
// rightMotor(-power);
// leftMotor(power);
} else if (getGyro() > angle + 7) {
tankDrive.tankDrive(-power, power);
// rightMotor(power);
// leftMotor(-power);
} else if (getGyro() >= angle - 7 && getGyro() <= angle + 7) {
tankDrive.tankDrive(0, 0);
}
}
public void driveDistance(double distance) { // inches
double power = (distance - getDistance()) / distance;
if (getDistance() <= (Math.PI * distance) - 4) {
tankDrive.tankDrive(power, power);
} else {
tankDrive.tankDrive(0, 0);
}
}
public void driveDirection(double angle, double distance) {
turnAngle(angle);
driveDistance(distance);
}
public void setPIDConstants() {
// double p = 1;
// double i = 2;
// double d = 0;
// double f = 1;
double p = 0.000001;
double i = 0.000001;
double d = 0.000001;
double f = 1;
leftTopPID.setConstants(p, i, d, f);
leftBotPID.setConstants(p, i, d, f);
rightTopPID.setConstants(p, i, d, f);
rightBotPID.setConstants(p, i, d, f);
}
@Override
public void initDefaultCommand() {
setDefaultCommand(new DriveWithJoysticks());
}
} |
package hudson.model.queue;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.model.AbstractProject;
import jenkins.model.Jenkins;
import java.util.Collection;
import java.util.Collections;
/**
* Externally contributes {@link SubTask}s to {@link AbstractProject#getSubTasks()}.
*
* <p>
* Put @{@link Extension} on your implementation classes to register them.
*
* @author Kohsuke Kawaguchi
* @since 1.377
*/
public abstract class SubTaskContributor implements ExtensionPoint {
public Collection<? extends SubTask> forProject(AbstractProject<?,?> p) {
return Collections.emptyList();
}
/**
* All registered {@link SubTaskContributor} instances.
*/
public static ExtensionList<SubTaskContributor> all() {
return Jenkins.getInstance().getExtensionList(SubTaskContributor.class);
}
} |
import java.io.ByteArrayInputStream;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.*;
public class StreamTest {
@org.junit.Test
public void isNumber() throws Exception {
ByteArrayInputStream testStream = new ByteArrayInputStream("12".getBytes());
Stream stream = new Stream();
assertThat(stream.isNumber(testStream), is(true));
}
} |
package com.obidea.semantika.cli2.runtime;
import java.util.HashMap;
import java.util.Map;
import com.obidea.semantika.cli2.command.Command;
import com.obidea.semantika.cli2.command.CommandFactory;
import com.obidea.semantika.cli2.command.SelectCommand;
import com.obidea.semantika.cli2.command.SetPrefixCommand;
import com.obidea.semantika.cli2.command.ShowPrefixesCommand;
import com.obidea.semantika.knowledgebase.IPrefixManager;
import com.obidea.semantika.queryanswer.IQueryEngine;
public class ConsoleSession
{
private IQueryEngine mQueryEngine;
private Map<String, String> mPrefixMapper;
public ConsoleSession(IQueryEngine engine, IPrefixManager prefixManager)
{
mQueryEngine = engine;
mPrefixMapper = new HashMap<String, String>(prefixManager.getPrefixMapper());
}
public Object execute(String command) throws Exception
{
Command cmd = CommandFactory.create(command);
if (cmd instanceof SelectCommand) {
return mQueryEngine.evaluate(cmd.arguments().get("string"));
}
else if (cmd instanceof SetPrefixCommand) {
mPrefixMapper.put(cmd.arguments().get("prefix"), cmd.arguments().get("namespace"));
}
else if (cmd instanceof ShowPrefixesCommand) {
return mPrefixMapper;
}
throw new Exception();
}
} |
package org.splevo.jamopp.vpm.analyzer.programdependency.references;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.ComposedSwitch;
import org.emftext.language.java.commons.Commentable;
import org.emftext.language.java.containers.CompilationUnit;
import org.emftext.language.java.expressions.AssignmentExpression;
import org.emftext.language.java.expressions.Expression;
import org.emftext.language.java.expressions.util.ExpressionsSwitch;
import org.emftext.language.java.imports.ClassifierImport;
import org.emftext.language.java.imports.Import;
import org.emftext.language.java.imports.util.ImportsSwitch;
import org.emftext.language.java.instantiations.NewConstructorCall;
import org.emftext.language.java.instantiations.util.InstantiationsSwitch;
import org.emftext.language.java.members.ClassMethod;
import org.emftext.language.java.members.Constructor;
import org.emftext.language.java.members.Method;
import org.emftext.language.java.members.util.MembersSwitch;
import org.emftext.language.java.references.IdentifierReference;
import org.emftext.language.java.references.MethodCall;
import org.emftext.language.java.references.util.ReferencesSwitch;
import org.emftext.language.java.statements.ExpressionStatement;
import org.emftext.language.java.statements.LocalVariableStatement;
import org.emftext.language.java.statements.Return;
import org.emftext.language.java.statements.Statement;
import org.emftext.language.java.statements.util.StatementsSwitch;
import org.emftext.language.java.types.Type;
import org.emftext.language.java.types.TypeReference;
import org.emftext.language.java.types.util.TypesSwitch;
import org.emftext.language.java.variables.LocalVariable;
import org.splevo.vpm.analyzer.VPMAnalyzerUtil;
import com.google.common.collect.Lists;
/**
* Switch to decide about which elements to return as referenced elements for a given JaMoPP
* element.
*/
public class DefaultReferenceSelectorSwitch extends ComposedSwitch<List<Commentable>> {
/** The logger for this class. */
private Logger logger = Logger.getLogger(DefaultReferenceSelectorSwitch.class);
/** Constructor to set up the sub switches. */
public DefaultReferenceSelectorSwitch() {
addSwitch(new StatementsReferencedElementsSwitch(this));
addSwitch(new ExpressionsReferencedElementsSwitch(this));
addSwitch(new MembersReferencedElementsSwitch(this));
addSwitch(new ImportReferencedElementsSwitch());
addSwitch(new ReferencesReferencedElementsSwitch(this));
addSwitch(new InstantiationsReferencedElementsSwitch(this));
addSwitch(new TypesReferencedElementsSwitch());
}
/**
* Wrapper for the super method implementation ensuring that at least an empty list is always
* returned.
*
* {@inheritDoc}
*/
@Override
public List<Commentable> doSwitch(EObject eObject) {
List<Commentable> elements = null;
if (!VPMAnalyzerUtil.isNullOrProxy(eObject)) {
elements = super.doSwitch(eObject);
}
if (elements == null) {
elements = Lists.newArrayList();
}
return elements;
}
/**
* Switch to decide about referenced elements for import elements.
*/
private class ImportReferencedElementsSwitch extends ImportsSwitch<List<Commentable>> {
@Override
public List<Commentable> caseImport(Import object) {
return Lists.newArrayList((Commentable) object);
}
}
/**
* Switch to decide about referenced elements for reference elements.
*/
private class TypesReferencedElementsSwitch extends TypesSwitch<List<Commentable>> {
/**
* For type references, not only the type itself, but also according import statements in
* the same compilation unit are detected as they are part of the reference.
*/
@Override
public List<Commentable> caseTypeReference(TypeReference typeReference) {
Type type = typeReference.getTarget();
ArrayList<Commentable> refElements = Lists.newArrayList((Commentable) type);
CompilationUnit cu = typeReference.getContainingCompilationUnit();
EList<ClassifierImport> imports = cu.getChildrenByType(ClassifierImport.class);
for (ClassifierImport classifierImport : imports) {
if (classifierImport.getClassifier().equals(type)) {
refElements.add(classifierImport);
}
}
return refElements;
}
}
/**
* Switch to decide about referenced elements for reference elements.
*/
private class ReferencesReferencedElementsSwitch extends ReferencesSwitch<List<Commentable>> {
private DefaultReferenceSelectorSwitch parentSwitch;
public ReferencesReferencedElementsSwitch(DefaultReferenceSelectorSwitch parentSwitch) {
this.parentSwitch = parentSwitch;
}
@Override
public List<Commentable> caseMethodCall(MethodCall methodCall) {
ArrayList<Commentable> refElements = Lists.newArrayList();
for (Expression expression : methodCall.getArguments()) {
refElements.addAll(parentSwitch.doSwitch(expression));
}
refElements.addAll(parentSwitch.doSwitch(methodCall.getTarget()));
return refElements;
}
@Override
public List<Commentable> caseIdentifierReference(IdentifierReference reference) {
ArrayList<Commentable> refElements = Lists.newArrayList((Commentable) reference.getTarget());
if (reference.getNext() != null) {
refElements.addAll(parentSwitch.doSwitch(reference.getNext()));
}
return refElements;
}
}
/**
* Switch to decide about referenced elements for statement elements.
*/
private class InstantiationsReferencedElementsSwitch extends InstantiationsSwitch<List<Commentable>> {
private DefaultReferenceSelectorSwitch parentSwitch;
public InstantiationsReferencedElementsSwitch(DefaultReferenceSelectorSwitch parentSwitch) {
this.parentSwitch = parentSwitch;
}
@Override
public List<Commentable> caseNewConstructorCall(NewConstructorCall call) {
ArrayList<Commentable> refElements = Lists.newArrayList();
for (Expression expression : call.getArguments()) {
refElements.addAll(parentSwitch.doSwitch(expression));
}
refElements.addAll(parentSwitch.doSwitch(call.getTypeReference()));
return refElements;
}
}
/**
* Switch to decide about referenced elements for statement elements.
*/
private class StatementsReferencedElementsSwitch extends StatementsSwitch<List<Commentable>> {
private DefaultReferenceSelectorSwitch parentSwitch;
public StatementsReferencedElementsSwitch(DefaultReferenceSelectorSwitch parentSwitch) {
this.parentSwitch = parentSwitch;
}
@Override
public List<Commentable> caseReturn(Return returnStmt) {
ArrayList<Commentable> refElements = Lists.newArrayList((Commentable) returnStmt);
refElements.addAll(parentSwitch.doSwitch(returnStmt.getReturnValue()));
return refElements;
}
@Override
public List<Commentable> caseLocalVariableStatement(LocalVariableStatement lvs) {
ArrayList<Commentable> refElements = Lists.newArrayList();
LocalVariable variable = lvs.getVariable();
if (variable != null) {
refElements.add(lvs.getVariable());
refElements.addAll(parentSwitch.doSwitch(variable.getTypeReference()));
refElements.addAll(parentSwitch.doSwitch(variable.getInitialValue()));
refElements.addAll(variable.getAdditionalLocalVariables());
} else {
logger.warn("VariableStatement without variable: " + lvs);
}
return refElements;
}
@Override
public List<Commentable> caseExpressionStatement(ExpressionStatement stmt) {
return parentSwitch.doSwitch(stmt.getExpression());
}
}
/**
* Switch to decide about referenced elements for statement elements.
*/
private class ExpressionsReferencedElementsSwitch extends ExpressionsSwitch<List<Commentable>> {
private DefaultReferenceSelectorSwitch parentSwitch;
public ExpressionsReferencedElementsSwitch(DefaultReferenceSelectorSwitch parentSwitch) {
this.parentSwitch = parentSwitch;
}
@Override
public List<Commentable> caseAssignmentExpression(AssignmentExpression exp) {
ArrayList<Commentable> refElements = Lists.newArrayList();
refElements.addAll(parentSwitch.doSwitch(exp.getChild()));
refElements.addAll(parentSwitch.doSwitch(exp.getValue()));
return refElements;
}
}
/**
* Switch to decide about referenced elements for member elements.
*/
private class MembersReferencedElementsSwitch extends MembersSwitch<List<Commentable>> {
private DefaultReferenceSelectorSwitch parentSwitch;
public MembersReferencedElementsSwitch(DefaultReferenceSelectorSwitch parentSwitch) {
this.parentSwitch = parentSwitch;
}
/**
* Return the method itself and scan the included statements for additional references.
*/
@Override
public List<Commentable> caseClassMethod(ClassMethod method) {
ArrayList<Commentable> refElements = Lists.newArrayList((Commentable) method);
for (Statement statement : method.getStatements()) {
refElements.addAll(parentSwitch.doSwitch(statement));
}
return refElements;
}
@Override
public List<Commentable> caseConstructor(Constructor constructor) {
ArrayList<Commentable> refElements = Lists.newArrayList((Commentable) constructor);
for (Statement statement : constructor.getStatements()) {
refElements.addAll(parentSwitch.doSwitch(statement));
}
return refElements;
}
@Override
public List<Commentable> caseMethod(Method object) {
return Lists.newArrayList((Commentable) object);
}
}
} |
package com.datazuul.apps.notepad.gui;
import com.datazuul.apps.commons.gui.WindowSizer;
import com.datazuul.apps.notepad.Main;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JViewport;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;
public class AboutDialog extends JDialog {
private static final long serialVersionUID = 1L;
private JButton btnClose = null;
/**
* @param parent
*/
public AboutDialog(JFrame parent) {
super(parent, "About " + Main.PROGRAM_NAME, true);
getContentPane().add(this.buildGUI());
getRootPane().setDefaultButton(this.btnClose);
pack();
new WindowSizer().centerOnScreen(this);
//new WindowSizer(300, 150).centerOnScreen(this);
}
private JPanel buildGUI() {
JPanel panel = new JPanel(new BorderLayout());
panel.add(this.buildAboutPanel(), BorderLayout.CENTER);
panel.add(this.buildButtonPanel(), BorderLayout.SOUTH);
return panel;
}
private JPanel buildAboutPanel() {
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(new EmptyBorder(5, 5, 5, 5));
panel.add(new JViewport(), BorderLayout.WEST);
panel.add(this.buildInfoPanel(), BorderLayout.CENTER);
return panel;
}
private JPanel buildInfoPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
EmptyBorder innerBorder = new EmptyBorder(5, 5, 5, 5);
TitledBorder outerBorder = new TitledBorder(Main.VERSION);
panel.setBorder(new CompoundBorder(outerBorder, innerBorder));
panel.add(new JLabel("Written by Ralf Eichinger"));
panel.add(new JLabel("ralf.eichinger@gmail.com"));
panel.add(new JLabel("http:
return panel;
}
private JPanel buildButtonPanel() {
JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
this.btnClose = new JButton("Close");
this.btnClose.setMnemonic(KeyEvent.VK_C);
this.btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
panel.add(this.btnClose);
return panel;
}
} |
package data.playlists;
import com.google.gson.JsonArray;
import com.google.gson.JsonParser;
import com.wrapper.spotify.SpotifyApi;
import com.wrapper.spotify.exceptions.SpotifyWebApiException;
import com.wrapper.spotify.model_objects.special.SnapshotResult;
import com.wrapper.spotify.requests.data.playlists.RemoveTracksFromPlaylistRequest;
import org.apache.hc.core5.http.ParseException;
import java.io.IOException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class RemoveTracksFromPlaylistExample {
private static final String accessToken = "taHZ2SdB-bPA3FsK3D7ZN5npZS47cMy-IEySVEGttOhXmqaVAIo0ESvTCLjLBifhHOHOIuhFUKPW1WMDP7w6dj3MAZdWT8CLI2MkZaXbYLTeoDvXesf2eeiLYPBGdx8tIwQJKgV8XdnzH_DONk";
private static final String playlistId = "3AGOiaoRXMSjswCLtuNqv5";
private static final JsonArray tracks = JsonParser.parseString("[{\"uri\":\"spotify:track:01iyCAUm8EvOFqVWYJ3dVX\"}]").getAsJsonArray();
private static final SpotifyApi spotifyApi = new SpotifyApi.Builder()
.setAccessToken(accessToken)
.build();
private static final RemoveTracksFromPlaylistRequest removeTracksFromPlaylistRequest = spotifyApi
.removeTracksFromPlaylist(playlistId, tracks)
// .snapshotId("JbtmHBDBAYu3/bt8BOXKjzKx3i0b6LCa/wVjyl6qQ2Yf6nFXkbmzuEa+ZI/U1yF+")
.build();
public static void removeTracksFromPlaylist_Sync() {
try {
final SnapshotResult snapshotResult = removeTracksFromPlaylistRequest.execute();
System.out.println("Snapshot ID: " + snapshotResult.getSnapshotId());
} catch (IOException | SpotifyWebApiException | ParseException e) {
System.out.println("Error: " + e.getMessage());
}
}
public static void removeTracksFromPlaylist_Async() {
try {
final CompletableFuture<SnapshotResult> snapshotResultFuture = removeTracksFromPlaylistRequest.executeAsync();
// Thread free to do other tasks...
// Example Only. Never block in production code.
final SnapshotResult snapshotResult = snapshotResultFuture.join();
System.out.println("Snapshot ID: " + snapshotResult.getSnapshotId());
} catch (CompletionException e) {
System.out.println("Error: " + e.getCause().getMessage());
} catch (CancellationException e) {
System.out.println("Async operation cancelled.");
}
}
} |
package pl.bukkit.team.packets;
import pl.bukkit.team.Main;
import pl.bukkit.team.protocols.Reflection;
import pl.bukkit.team.protocols.TinyProtocol;
public class PacketPlayOutPlayerInfo extends AbstractPacket {
private static final Object handle = Reflection.getConstructor("{nms}.PacketPlayOutPlayerInfo").invoke();
public PacketPlayOutPlayerInfo() { super(handle, Main.getTinyProtocol());}
public PacketPlayOutPlayerInfo(Object packet,TinyProtocol tinyprotocol) { super(packet, tinyprotocol); }
public String getPlayerName() { return (String) Reflection.getMethod(packet.getClass(), "a").invoke(packet); }
public void setPlayerName(String value) { Reflection.getField(packet.getClass(), "a", String.class).set(packet, value); }
public boolean getOnline() { return (boolean) Reflection.getMethod(packet.getClass(), "b").invoke(packet); }
public void setOnline(boolean value) { Reflection.getField(packet.getClass(), "b", boolean.class).set(packet, value); }
public int getPing() { return (int) Reflection.getMethod(packet.getClass(), "c").invoke(packet); }
public void setPing(int value) { Reflection.getField(packet.getClass(), "c", int.class).set(packet, value); }
public void setPacket(String value1, boolean value2, int value3) {setPlayerName(value1); setOnline(value2); setPing(value3);}
} |
package io.subutai.core.environment.impl.workflow.modification;
import io.subutai.common.environment.EnvironmentStatus;
import io.subutai.common.tracker.TrackerOperation;
import io.subutai.core.environment.impl.EnvironmentManagerImpl;
import io.subutai.core.environment.impl.entity.LocalEnvironment;
import io.subutai.core.environment.api.CancellableWorkflow;
import io.subutai.core.environment.impl.workflow.creation.steps.AddSshKeyStep;
public class SshKeyAdditionWorkflow extends CancellableWorkflow<SshKeyAdditionWorkflow.SshKeyAdditionPhase>
{
private LocalEnvironment environment;
private final String sshKey;
private final TrackerOperation operationTracker;
private final EnvironmentManagerImpl environmentManager;
public enum SshKeyAdditionPhase
{
INIT, ADD_KEY, FINALIZE
}
public SshKeyAdditionWorkflow( final LocalEnvironment environment, final String sshKey,
final TrackerOperation operationTracker,
final EnvironmentManagerImpl environmentManager )
{
super( SshKeyAdditionPhase.INIT );
this.environment = environment;
this.sshKey = sshKey;
this.operationTracker = operationTracker;
this.environmentManager = environmentManager;
} |
package org.javarosa.xpath.expr;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.condition.IFunctionHandler;
import org.javarosa.core.model.condition.pivot.UnpivotableExpressionException;
import org.javarosa.core.model.instance.DataInstance;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.core.model.utils.DateUtils;
import org.javarosa.core.util.CacheTable;
import org.javarosa.core.util.MathUtils;
import org.javarosa.core.util.PropertyUtils;
import org.javarosa.core.util.externalizable.DeserializationException;
import org.javarosa.core.util.externalizable.ExtUtil;
import org.javarosa.core.util.externalizable.ExtWrapListPoly;
import org.javarosa.core.util.externalizable.PrototypeFactory;
import org.javarosa.xpath.IExprDataType;
import org.javarosa.xpath.XPathArityException;
import org.javarosa.xpath.XPathException;
import org.javarosa.xpath.XPathNodeset;
import org.javarosa.xpath.XPathTypeMismatchException;
import org.javarosa.xpath.XPathUnhandledException;
import org.javarosa.xpath.XPathUnsupportedException;
import org.javarosa.xpath.parser.XPathSyntaxException;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import me.regexp.RE;
import me.regexp.RESyntaxException;
/**
* Representation of an xpath function expression.
*
* All of the built-in xpath functions are included here, as well as the xpath type conversion logic
*
* Evaluation of functions can delegate out to custom function handlers that must be registered at
* runtime.
*
* @author Drew Roos
*/
public class XPathFuncExpr extends XPathExpression {
public XPathQName id; //name of the function
public XPathExpression[] args; //argument list
private static CacheTable<String, Double> mDoubleParseCache = new CacheTable<String, Double>();
public XPathFuncExpr() {
} //for deserialization
public XPathFuncExpr(XPathQName id, XPathExpression[] args) throws XPathSyntaxException {
if (id.name.equals("if")) {
if (args.length != 3) {
throw new XPathSyntaxException("if() function requires 3 arguments but " + args.length + " are present.");
}
}
this.id = id;
this.args = args;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append("{func-expr:");
sb.append(id.toString());
sb.append(",{");
for (int i = 0; i < args.length; i++) {
sb.append(args[i].toString());
if (i < args.length - 1)
sb.append(",");
}
sb.append("}}");
return sb.toString();
}
@Override
public String toPrettyString() {
StringBuffer sb = new StringBuffer();
sb.append(id.toString() + "(");
for (int i = 0; i < args.length; i++) {
sb.append(args[i].toPrettyString());
if (i < args.length - 1) {
sb.append(", ");
}
}
sb.append(")");
return sb.toString();
}
@Override
public boolean equals(Object o) {
if (o instanceof XPathFuncExpr) {
XPathFuncExpr x = (XPathFuncExpr)o;
//Shortcuts for very easily comprable values
//We also only return "True" for methods we expect to return the same thing. This is not good
//practice in Java, since o.equals(o) will return false. We should evaluate that differently.
//Dec 8, 2011 - Added "uuid", since we should never assume one uuid equals another
//May 6, 2013 - Added "random", since two calls asking for a random
if (!id.equals(x.id) || args.length != x.args.length || id.toString().equals("uuid") || id.toString().equals("random")) {
return false;
}
return ExtUtil.arrayEquals(args, x.args, false);
} else {
return false;
}
}
@Override
public int hashCode() {
int argsHash = 0;
for (XPathExpression arg : args) {
argsHash ^= arg.hashCode();
}
return id.hashCode() ^ argsHash;
}
@Override
public void readExternal(DataInputStream in, PrototypeFactory pf) throws IOException, DeserializationException {
id = (XPathQName)ExtUtil.read(in, XPathQName.class);
Vector v = (Vector)ExtUtil.read(in, new ExtWrapListPoly(), pf);
args = new XPathExpression[v.size()];
for (int i = 0; i < args.length; i++)
args[i] = (XPathExpression)v.elementAt(i);
}
@Override
public void writeExternal(DataOutputStream out) throws IOException {
Vector v = new Vector();
for (int i = 0; i < args.length; i++)
v.addElement(args[i]);
ExtUtil.write(out, id);
ExtUtil.write(out, new ExtWrapListPoly(v));
}
/**
* Evaluate the function call.
*
* First check if the function is a member of the built-in function suite. If not, then check
* for any custom handlers registered to handler the function. If not, throw and exception.
*
* Both function name and appropriate arguments are taken into account when finding a suitable
* handler. For built-in functions, the number of arguments must match; for custom functions,
* the supplied arguments must match one of the function prototypes defined by the handler.
*/
@Override
public Object evalRaw(DataInstance model, EvaluationContext evalContext) {
String name = id.toString();
Object[] argVals = new Object[args.length];
Hashtable funcHandlers = evalContext.getFunctionHandlers();
//TODO: Func handlers should be able to declare the desire for short circuiting as well
if (name.equals("if") && args.length == 3) {
return ifThenElse(model, evalContext, args, argVals);
} else if (name.equals("coalesce") && args.length == 2) {
//Not sure if unpacking here is quiiite right, but it seems right
argVals[0] = XPathFuncExpr.unpack(args[0].eval(model, evalContext));
if (!isNull(argVals[0])) {
return argVals[0];
} else {
argVals[1] = args[1].eval(model, evalContext);
return argVals[1];
}
}
for (int i = 0; i < args.length; i++) {
argVals[i] = args[i].eval(model, evalContext);
}
XPathArityException customFuncArityError = null;
// check for custom handler, use this if it exists.
try {
IFunctionHandler handler = (IFunctionHandler)funcHandlers.get(name);
if (handler != null) {
return evalCustomFunction(handler, argVals, evalContext);
}
} catch (XPathArityException e) {
// we matched the name but not the arg count. continue in case the
// default has the right arity, and if no default found, raise this
// error on exit
customFuncArityError = e;
}
try {
//check built-in functions
if (name.equals("true")) {
checkArity(name, 0, args.length);
return Boolean.TRUE;
} else if (name.equals("false")) {
checkArity(name, 0, args.length);
return Boolean.FALSE;
} else if (name.equals("boolean")) {
checkArity(name, 1, args.length);
return toBoolean(argVals[0]);
} else if (name.equals("number")) {
checkArity(name, 1, args.length);
return toNumeric(argVals[0]);
} else if (name.equals("int")) { //non-standard
checkArity(name, 1, args.length);
return toInt(argVals[0]);
} else if (name.equals("double")) { //non-standard
checkArity(name, 1, args.length);
return toDouble(argVals[0]);
} else if (name.equals("string")) {
checkArity(name, 1, args.length);
return toString(argVals[0]);
} else if (name.equals("date")) { //non-standard
checkArity(name, 1, args.length);
return toDate(argVals[0]);
} else if (name.equals("not")) {
checkArity(name, 1, args.length);
return boolNot(argVals[0]);
} else if (name.equals("boolean-from-string")) {
checkArity(name, 1, args.length);
return boolStr(argVals[0]);
} else if (name.equals("format-date")) {
checkArity(name, 2, args.length);
return dateStr(argVals[0], argVals[1]);
} else if ((name.equals("selected") || name.equals("is-selected"))) { //non-standard
checkArity(name, 2, args.length);
return multiSelected(argVals[0], argVals[1]);
} else if (name.equals("count-selected")) { //non-standard
checkArity(name, 1, args.length);
return countSelected(argVals[0]);
} else if (name.equals("selected-at")) { //non-standard
checkArity(name, 2, args.length);
return selectedAt(argVals[0], argVals[1]);
} else if (name.equals("position")) {
//TODO: Technically, only the 0 length argument is valid here.
if (args.length > 1) {
throw new XPathArityException(name, "0 or 1 arguments", args.length);
}
if (args.length == 1) {
return position(((XPathNodeset)argVals[0]).getRefAt(0));
} else if (evalContext.getContextPosition() != -1) {
return new Double(evalContext.getContextPosition());
} else {
return position(evalContext.getContextRef());
}
} else if (name.equals("count")) {
checkArity(name, 1, args.length);
return count(argVals[0]);
} else if (name.equals("sum")) {
checkArity(name, 1, args.length);
if (argVals[0] instanceof XPathNodeset) {
return sum(((XPathNodeset)argVals[0]).toArgList());
} else {
throw new XPathTypeMismatchException("not a nodeset");
}
} else if (name.equals("max")) {
if (args.length == 0) {
throw new XPathArityException(name, "at least one argument", args.length);
}
if (argVals.length == 1 && argVals[0] instanceof XPathNodeset) {
return max(((XPathNodeset)argVals[0]).toArgList());
} else {
return max(argVals);
}
} else if (name.equals("min")) {
if (args.length == 0) {
throw new XPathArityException(name, "at least one argument", args.length);
}
if (argVals.length == 1 && argVals[0] instanceof XPathNodeset) {
return min(((XPathNodeset)argVals[0]).toArgList());
} else {
return min(argVals);
}
} else if (name.equals("today")) {
checkArity(name, 0, args.length);
return DateUtils.roundDate(new Date());
} else if (name.equals("now")) {
checkArity(name, 0, args.length);
return new Date();
} else if (name.equals("concat")) {
if (args.length == 1 && argVals[0] instanceof XPathNodeset) {
return join("", ((XPathNodeset)argVals[0]).toArgList());
} else {
return join("", argVals);
}
} else if (name.equals("join")) {
if (args.length == 0) {
throw new XPathArityException(name, "at least one argument", args.length);
}
if (args.length == 2 && argVals[1] instanceof XPathNodeset) {
return join(argVals[0], ((XPathNodeset)argVals[1]).toArgList());
} else {
return join(argVals[0], subsetArgList(argVals, 1));
}
} else if (name.equals("substr")) {
if (!(args.length == 2 || args.length == 3)) {
throw new XPathArityException(name, "two or three arguments", args.length);
}
return substring(argVals[0], argVals[1], args.length == 3 ? argVals[2] : null);
} else if (name.equals("string-length")) {
checkArity(name, 1, args.length);
return stringLength(argVals[0]);
} else if (name.equals("upper-case")) {
checkArity(name, 1, args.length);
return normalizeCase(argVals[0], true);
} else if (name.equals("lower-case")) {
checkArity(name, 1, args.length);
return normalizeCase(argVals[0], false);
} else if (name.equals("contains")) {
checkArity(name, 2, args.length);
return toString(argVals[0]).indexOf(toString(argVals[1])) != -1;
} else if (name.equals("starts-with")) {
checkArity(name, 2, args.length);
return toString(argVals[0]).startsWith(toString(argVals[1]));
} else if (name.equals("ends-with")) {
checkArity(name, 2, args.length);
return toString(argVals[0]).endsWith(toString(argVals[1]));
} else if (name.equals("translate")) {
checkArity(name, 3, args.length);
return translate(argVals[0], argVals[1], argVals[2]);
} else if (name.equals("replace")) {
checkArity(name, 3, args.length);
return replace(argVals[0], argVals[1], argVals[2]);
} else if (name.equals("checklist")) { //non-standard
if (args.length < 2) {
throw new XPathArityException(name, "two or more arguments", args.length);
}
if (args.length == 3 && argVals[2] instanceof XPathNodeset) {
return checklist(argVals[0], argVals[1], ((XPathNodeset)argVals[2]).toArgList());
} else {
return checklist(argVals[0], argVals[1], subsetArgList(argVals, 2));
}
} else if (name.equals("weighted-checklist")) { //non-standard
if (!(args.length >= 2 && args.length % 2 == 0)) {
throw new XPathArityException(name, "an even number of arguments", args.length);
}
if (args.length == 4 && argVals[2] instanceof XPathNodeset && argVals[3] instanceof XPathNodeset) {
Object[] factors = ((XPathNodeset)argVals[2]).toArgList();
Object[] weights = ((XPathNodeset)argVals[3]).toArgList();
if (factors.length != weights.length) {
throw new XPathTypeMismatchException("weighted-checklist: nodesets not same length");
}
return checklistWeighted(argVals[0], argVals[1], factors, weights);
} else {
return checklistWeighted(argVals[0], argVals[1], subsetArgList(argVals, 2, 2), subsetArgList(argVals, 3, 2));
}
} else if (name.equals("regex")) { //non-standard
checkArity(name, 2, args.length);
return regex(argVals[0], argVals[1]);
} else if (name.equals("depend")) { //non-standard
if (args.length == 0) {
throw new XPathArityException(name, "at least one argument", args.length);
}
return argVals[0];
} else if (name.equals("random")) { //non-standard
checkArity(name, 0, args.length);
//calculated expressions may be recomputed w/o warning! use with caution!!
return new Double(MathUtils.getRand().nextDouble());
} else if (name.equals("uuid")) { //non-standard
if (args.length > 1) {
throw new XPathArityException(name, "0 or 1 arguments", args.length);
}
//calculated expressions may be recomputed w/o warning! use with caution!!
if (args.length == 0) {
return PropertyUtils.genUUID();
}
int len = toInt(argVals[0]).intValue();
return PropertyUtils.genGUID(len);
} else if (name.equals("pow")) { //XPath 3.0
checkArity(name, 2, args.length);
return power(argVals[0], argVals[1]);
} else if (name.equals("abs")) {
checkArity(name, 1, args.length);
return new Double(Math.abs(toDouble(argVals[0]).doubleValue()));
} else if (name.equals("ceiling")) {
checkArity(name, 1, args.length);
return new Double(Math.ceil(toDouble(argVals[0]).doubleValue()));
} else if (name.equals("floor")) {
checkArity(name, 1, args.length);
return new Double(Math.floor(toDouble(argVals[0]).doubleValue()));
} else if (name.equals("round")) {
checkArity(name, 1, args.length);
return new Double((double)(Math.floor(toDouble(argVals[0]).doubleValue() + 0.5)));
} else if (name.equals("log")) { //XPath 3.0
checkArity(name, 1, args.length);
return log(argVals[0]);
} else if (name.equals("log10")) { //XPath 3.0
checkArity(name, 1, args.length);
return log10(argVals[0]);
} else if (name.equals("sin")) { //XPath 3.0
checkArity(name, 1, args.length);
return sin(argVals[0]);
}else if (name.equals("cos")) { //XPath 3.0
checkArity(name, 1, args.length);
return cosin(argVals[0]);
}else if (name.equals("tan")) { //XPath 3.0
checkArity(name, 1, args.length);
return tan(argVals[0]);
}else if (name.equals("asin")) { //XPath 3.0
checkArity(name, 1, args.length);
return asin(argVals[0]);
}else if (name.equals("acos")) { //XPath 3.0
checkArity(name, 1, args.length);
return acos(argVals[0]);
}else if (name.equals("atan")) { //XPath 3.0
checkArity(name, 1, args.length);
return atan(argVals[0]);
}else if (name.equals("atan2")) { //XPath 3.0
checkArity(name, 2, args.length);
return atan2(argVals[0], argVals[1]);
}else if (name.equals("sqrt")) { //XPath 3.0
checkArity(name, 1, args.length);
return sqrt(argVals[0]);
}else if (name.equals("exp")) { //XPath 3.0
checkArity(name, 1, args.length);
return exp(argVals[0]);
}else if (name.equals("pi")) { //XPath 3.0
checkArity(name, 0, args.length);
return pi();
}else {
if (customFuncArityError != null) {
throw customFuncArityError;
}
throw new XPathUnhandledException("function \'" + name + "\'");
}
//Specific list of issues that we know come up
} catch (ClassCastException cce) {
String args = "";
for (int i = 0; i < argVals.length; ++i) {
args += "'" + String.valueOf(unpack(argVals[i])) + "'" + (i == argVals.length - 1 ? "" : ", ");
}
throw new XPathException("There was likely an invalid argument to the function '" + name + "'. The final list of arguments were: [" + args + "]" + ". Full error " + cce.getMessage());
}
}
/**
* Throws an arity exception if expected arity doesn't match the provided arity.
*
* @param name the function name
* @param expectedArity expected number of arguments to the function
* @param providedArity number of arguments actually provided to the function
*/
private static void checkArity(String name, int expectedArity, int providedArity)
throws XPathArityException {
if (expectedArity != providedArity) {
throw new XPathArityException(name, expectedArity, providedArity);
}
}
/**
* Given a handler registered to handle the function, try to coerce the
* function arguments into one of the prototypes defined by the handler. If
* no suitable prototype found, throw an eval exception. Otherwise,
* evaluate.
*
* Note that if the handler supports 'raw args', it will receive the full,
* unaltered argument list if no prototype matches. (this lets functions
* support variable-length argument lists)
*/
private static Object evalCustomFunction(IFunctionHandler handler, Object[] args,
EvaluationContext ec) {
Vector prototypes = handler.getPrototypes();
Enumeration e = prototypes.elements();
Object[] typedArgs = null;
boolean argPrototypeArityMatch = false;
Class[] proto;
while (typedArgs == null && e.hasMoreElements()) {
// try to coerce args into prototype, stopping on first success
proto = (Class[])e.nextElement();
typedArgs = matchPrototype(args, proto);
argPrototypeArityMatch = argPrototypeArityMatch ||
(proto.length == args.length);
}
if (typedArgs != null) {
return handler.eval(typedArgs, ec);
} else if (handler.rawArgs()) {
// should we have support for expanding nodesets here?
return handler.eval(args, ec);
} else if (!argPrototypeArityMatch) {
// When the argument count doesn't match any of the prototype
// sizes, we have an arity error.
throw new XPathArityException(handler.getName(),
"a different number of arguments",
args.length);
} else {
throw new XPathTypeMismatchException("for function \'" +
handler.getName() + "\'");
}
}
/**
* Given a prototype defined by the function handler, attempt to coerce the
* function arguments to match that prototype (checking # args, type
* conversion, etc.). If it is coercible, return the type-converted
* argument list -- these will be the arguments used to evaluate the
* function. If not coercible, return null.
*/
private static Object[] matchPrototype(Object[] args, Class[] prototype) {
Object[] typed = null;
if (prototype.length == args.length) {
typed = new Object[args.length];
for (int i = 0; i < prototype.length; i++) {
typed[i] = null;
// how to handle type conversions of custom types?
if (prototype[i].isAssignableFrom(args[i].getClass())) {
typed[i] = args[i];
} else {
try {
if (prototype[i] == Boolean.class) {
typed[i] = toBoolean(args[i]);
} else if (prototype[i] == Double.class) {
typed[i] = toNumeric(args[i]);
} else if (prototype[i] == String.class) {
typed[i] = toString(args[i]);
} else if (prototype[i] == Date.class) {
typed[i] = toDate(args[i]);
}
} catch (XPathTypeMismatchException xptme) {
}
}
if (typed[i] == null) {
return null;
}
}
}
return typed;
}
public static boolean isNull(Object o) {
if (o == null) {
return true; //true 'null' values aren't allowed in the xpath engine, but whatever
} else if (o instanceof String && ((String)o).length() == 0) {
return true;
} else if (o instanceof Double && ((Double)o).isNaN()) {
return true;
} else {
return false;
}
}
public static Double stringLength(Object o) {
String s = toString(o);
if (s == null) {
return new Double(0.0);
}
return new Double(s.length());
}
/**
* convert a value to a boolean using xpath's type conversion rules
*/
public static Boolean toBoolean(Object o) {
Boolean val = null;
o = unpack(o);
if (o instanceof Boolean) {
val = (Boolean)o;
} else if (o instanceof Double) {
double d = ((Double)o).doubleValue();
val = new Boolean(Math.abs(d) > 1.0e-12 && !Double.isNaN(d));
} else if (o instanceof String) {
String s = (String)o;
val = new Boolean(s.length() > 0);
} else if (o instanceof Date) {
val = Boolean.TRUE;
} else if (o instanceof IExprDataType) {
val = ((IExprDataType)o).toBoolean();
}
if (val != null) {
return val;
} else {
throw new XPathTypeMismatchException("converting to boolean");
}
}
public static Double toDouble(Object o) {
if (o instanceof Date) {
return DateUtils.fractionalDaysSinceEpoch((Date)o);
} else {
return toNumeric(o);
}
}
/**
* convert a value to a number using xpath's type conversion rules (note that xpath itself makes
* no distinction between integer and floating point numbers)
*/
public static Double toNumeric(Object o) {
Double val = null;
o = unpack(o);
if (o instanceof Boolean) {
val = new Double(((Boolean)o).booleanValue() ? 1 : 0);
} else if (o instanceof Double) {
val = (Double)o;
} else if (o instanceof String) {
/* annoying, but the xpath spec doesn't recognize scientific notation, or +/-Infinity
* when converting a string to a number
*/
String s = (String)o;
double d;
try {
s = s.trim();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (c != '-' && c != '.' && (c < '0' || c > '9'))
throw new NumberFormatException();
}
d = Double.parseDouble(s);
val = new Double(d);
} catch (NumberFormatException nfe) {
val = new Double(Double.NaN);
}
} else if (o instanceof Date) {
val = new Double(DateUtils.daysSinceEpoch((Date)o));
} else if (o instanceof IExprDataType) {
val = ((IExprDataType)o).toNumeric();
}
if (val != null) {
return val;
} else {
throw new XPathTypeMismatchException("converting '" + (o == null ? "null" : o.toString()) + "' to numeric");
}
}
/**
* convert a number to an integer by truncating the fractional part. if non-numeric, coerce the
* value to a number first. note that the resulting return value is still a Double, as required
* by the xpath engine
*/
public static Double toInt(Object o) {
Double val = toNumeric(o);
if (val.isInfinite() || val.isNaN()) {
return val;
} else if (val.doubleValue() >= Long.MAX_VALUE || val.doubleValue() <= Long.MIN_VALUE) {
return val;
} else {
long l = val.longValue();
Double dbl = new Double(l);
if (l == 0 && (val.doubleValue() < 0. || val.equals(new Double(-0.)))) {
dbl = new Double(-0.);
}
return dbl;
}
}
/**
* convert a value to a string using xpath's type conversion rules
*/
public static String toString(Object o) {
String val = null;
o = unpack(o);
if (o instanceof Boolean) {
val = (((Boolean)o).booleanValue() ? "true" : "false");
} else if (o instanceof Double) {
double d = ((Double)o).doubleValue();
if (Double.isNaN(d)) {
val = "NaN";
} else if (Math.abs(d) < 1.0e-12) {
val = "0";
} else if (Double.isInfinite(d)) {
val = (d < 0 ? "-" : "") + "Infinity";
} else if (Math.abs(d - (int)d) < 1.0e-12) {
val = String.valueOf((int)d);
} else {
val = String.valueOf(d);
}
} else if (o instanceof String) {
val = (String)o;
} else if (o instanceof Date) {
val = DateUtils.formatDate((Date)o, DateUtils.FORMAT_ISO8601);
} else if (o instanceof IExprDataType) {
val = ((IExprDataType)o).toString();
}
if (val != null) {
return val;
} else {
if (o == null) {
throw new XPathTypeMismatchException("attempt to cast null value to string");
} else {
throw new XPathTypeMismatchException("converting object of type " + o.getClass().toString() + " to string");
}
}
}
/**
* convert a value to a date. note that xpath has no intrinsic representation of dates, so this
* is off-spec. dates convert to strings as 'yyyy-mm-dd', convert to numbers as # of days since
* the unix epoch, and convert to booleans always as 'true'
*
* string and int conversions are reversable, however:
* * cannot convert bool to date
* * empty string and NaN (xpath's 'null values') go unchanged, instead of being converted
* into a date (which would cause an error, since Date has no null value (other than java
* null, which the xpath engine can't handle))
* * note, however, than non-empty strings that aren't valid dates _will_ cause an error
* during conversion
*/
public static Object toDate(Object o) {
o = unpack(o);
if (o instanceof Double) {
Double n = toInt(o);
if (n.isNaN()) {
return n;
}
if (n.isInfinite() || n.doubleValue() > Integer.MAX_VALUE || n.doubleValue() < Integer.MIN_VALUE) {
throw new XPathTypeMismatchException("converting out-of-range value to date");
}
return DateUtils.dateAdd(DateUtils.getDate(1970, 1, 1), n.intValue());
} else if (o instanceof String) {
String s = (String)o;
if (s.length() == 0) {
return s;
}
Date d = DateUtils.parseDateTime(s);
if (d == null) {
throw new XPathTypeMismatchException("converting string " + s + " to date");
} else {
return d;
}
} else if (o instanceof Date) {
return DateUtils.roundDate((Date)o);
} else {
String type = o == null ? "null" : o.getClass().getName();
throw new XPathTypeMismatchException("converting unexpected type " + type + " to date");
}
}
public static Boolean boolNot(Object o) {
boolean b = toBoolean(o).booleanValue();
return new Boolean(!b);
}
public static Boolean boolStr(Object o) {
String s = toString(o);
if (s.equalsIgnoreCase("true") || s.equals("1"))
return Boolean.TRUE;
else
return Boolean.FALSE;
}
public static String dateStr(Object od, Object of) {
if (od instanceof Date) {
//There's no reason to pull out the time info here if
//this is already a date (might still have time info
//that we want to preserve).
//we round at all of the relevant points up to here,
//and we only print out the date info when asked anyway.
} else {
od = toDate(od);
}
if (od instanceof Date) {
return DateUtils.format((Date)od, toString(of));
} else {
return "";
}
}
private Double position(TreeReference refAt) {
return new Double(refAt.getMultLast());
}
public static Object ifThenElse(DataInstance model, EvaluationContext ec, XPathExpression[] args, Object[] argVals) {
argVals[0] = args[0].eval(model, ec);
boolean b = toBoolean(argVals[0]).booleanValue();
return (b ? args[1].eval(model, ec) : args[2].eval(model, ec));
}
/**
* return whether a particular choice of a multi-select is selected
*
* @param o1 XML-serialized answer to multi-select question (i.e, space-delimited choice values)
* @param o2 choice to look for
*/
public static Boolean multiSelected(Object o1, Object o2) {
o2 = unpack(o2);
if (!(o2 instanceof String)) {
throw generateBadArgumentMessage("selected", 2, "single potential value from the list of select options", o2);
}
String s1 = (String)unpack(o1);
String s2 = ((String)o2).trim();
return new Boolean((" " + s1 + " ").indexOf(" " + s2 + " ") != -1);
}
public static XPathException generateBadArgumentMessage(String functionName, int argNumber, String type, Object endValue) {
return new XPathException("Bad argument to function '" + functionName + "'. Argument #" + argNumber + " should be a " + type + ", but instead evaluated to: " + String.valueOf(endValue));
}
/**
* return the number of choices in a multi-select answer
*
* @param o XML-serialized answer to multi-select question (i.e, space-delimited choice values)
*/
public static Double countSelected(Object o) {
Object evalResult = unpack(o);
if (!(evalResult instanceof String)) {
throw new XPathTypeMismatchException("count-selected argument was not a select list");
}
String s = (String)evalResult;
return new Double(DateUtils.split(s, " ", true).size());
}
/**
* Get the Nth item in a selected list
*
* @param o1 XML-serialized answer to multi-select question (i.e, space-delimited choice values)
* @param o2 the integer index into the list to return
*/
public static String selectedAt(Object o1, Object o2) {
String selection = (String)unpack(o1);
int index = toInt(o2).intValue();
Vector<String> entries = DateUtils.split(selection, " ", true);
if (entries.size() <= index) {
throw new XPathException("Attempting to select element " + index +
" of a list with only " + entries.size() + " elements.");
} else {
return entries.elementAt(index);
}
}
/**
* count the number of nodes in a nodeset
*/
public static Double count(Object o) {
if (o instanceof XPathNodeset) {
return new Double(((XPathNodeset)o).size());
} else {
throw new XPathTypeMismatchException("not a nodeset");
}
}
/**
* sum the values in a nodeset; each element is coerced to a numeric value
*/
public static Double sum(Object argVals[]) {
double sum = 0.0;
for (int i = 0; i < argVals.length; i++) {
sum += toNumeric(argVals[i]).doubleValue();
}
return new Double(sum);
}
/**
* Identify the largest value from the list of provided values.
*/
private static Object max(Object[] argVals) {
double max = Double.MIN_VALUE;
for (int i = 0; i < argVals.length; i++) {
max = Math.max(max, toNumeric(argVals[i]).doubleValue());
}
return new Double(max);
}
private static Object min(Object[] argVals) {
double min = Double.MAX_VALUE;
for (int i = 0; i < argVals.length; i++) {
min = Math.min(min, toNumeric(argVals[i]).doubleValue());
}
return new Double(min);
}
/**
* concatenate an abritrary-length argument list of string values together
*/
public static String join(Object oSep, Object[] argVals) {
String sep = toString(oSep);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < argVals.length; i++) {
sb.append(toString(argVals[i]));
if (i < argVals.length - 1)
sb.append(sep);
}
return sb.toString();
}
/*
* Implementation decisions:
* -Returns the empty string if o1.equals("")
* -Returns the empty string for any inputs that would
* cause an IndexOutOfBoundsException on call to Java's substring method,
* after start and end have been adjusted
*/
public static String substring(Object o1, Object o2, Object o3) {
String s = toString(o1);
if (s.length() == 0) {
return "";
}
int start = toInt(o2).intValue();
int len = s.length();
int end = (o3 != null ? toInt(o3).intValue() : len);
if (start < 0) {
start = len + start;
}
if (end < 0) {
end = len + end;
}
start = Math.min(Math.max(0, start), end);
end = Math.min(Math.max(0, end), end);
return ((start <= end && end <= len) ? s.substring(start, end) : "");
}
/**
* Perform toUpperCase or toLowerCase on given object.
*/
private String normalizeCase(Object o, boolean toUpper) {
String s = toString(o);
if (toUpper) {
return s.toUpperCase();
}
return s.toLowerCase();
}
/**
* Replace each of a given set of characters with another set of characters.
* If the characters to replace are "abc" and the replacement string is "def",
* each "a" in the source string will be replaced with "d", each "b" with "e", etc.
* If a character appears multiple times in the string of characters to replace, the
* first occurrence is the one that will be used.
*
* Any extra characters in the string of characters to replace will be deleted from the source.
* Any extra characters in the string of replacement characters will be ignored.
*
* @param o1 String to manipulate
* @param o2 String of characters to replace
* @param o3 String of replacement characters
*/
private String translate(Object o1, Object o2, Object o3) {
String source = toString(o1);
String from = toString(o2);
String to = toString(o3);
Hashtable<Character, Character> map = new Hashtable<Character, Character>();
for (int i = 0; i < Math.min(from.length(), to.length()); i++) {
if (!map.containsKey(new Character(from.charAt(i)))) {
map.put(new Character(from.charAt(i)), new Character(to.charAt(i)));
}
}
String toDelete = from.substring(Math.min(from.length(), to.length()));
String returnValue = "";
for (int i = 0; i < source.length(); i++) {
Character current = new Character(source.charAt(i));
if (toDelete.indexOf(current) == -1) {
if (map.containsKey(current)) {
current = map.get(current);
}
returnValue += current;
}
}
return returnValue;
}
/**
* Regex-based replacement.
*
* @param o1 String to manipulate
* @param o2 Pattern to search for
* @param o3 Replacement string. Contrary to the XPath spec, this function does NOT
* support backreferences (e.g., replace("abbc", "a(.*)c", "$1") will return "a$1c", not "bb").
* @return String
*/
private String replace(Object o1, Object o2, Object o3) {
String source = toString(o1);
RE pattern = new RE(toString(o2));
String replacement = toString(o3);
return pattern.subst(source, replacement);
}
/**
* perform a 'checklist' computation, enabling expressions like 'if there are at least 3 risk
* factors active'
*
* @param oMin a numeric value expressing the minimum number of factors required.
* if -1, no minimum is applicable
* @param oMax a numeric value expressing the maximum number of allowed factors.
* if -1, no maximum is applicable
* @param factors individual factors that are coerced to boolean values
* @return true if the count of 'true' factors is between the applicable minimum and maximum,
* inclusive
*/
public static Boolean checklist(Object oMin, Object oMax, Object[] factors) {
int min = toNumeric(oMin).intValue();
int max = toNumeric(oMax).intValue();
int count = 0;
for (int i = 0; i < factors.length; i++) {
if (toBoolean(factors[i]).booleanValue())
count++;
}
return new Boolean((min < 0 || count >= min) && (max < 0 || count <= max));
}
/**
* very similar to checklist, only each factor is assigned a real-number 'weight'.
*
* the first and second args are again the minimum and maximum, but -1 no longer means
* 'not applicable'.
*
* subsequent arguments come in pairs: first the boolean value, then the floating-point
* weight for that value
*
* the weights of all the 'true' factors are summed, and the function returns whether
* this sum is between the min and max
*/
public static Boolean checklistWeighted(Object oMin, Object oMax, Object[] flags, Object[] weights) {
double min = toNumeric(oMin).doubleValue();
double max = toNumeric(oMax).doubleValue();
double sum = 0.;
for (int i = 0; i < flags.length; i++) {
boolean flag = toBoolean(flags[i]).booleanValue();
double weight = toNumeric(weights[i]).doubleValue();
if (flag)
sum += weight;
}
return new Boolean(sum >= min && sum <= max);
}
/**
* determine if a string matches a regular expression.
*
* @param o1 string being matched
* @param o2 regular expression
*/
public static Boolean regex(Object o1, Object o2) {
String str = toString(o1);
String re = toString(o2);
RE regexp;
try {
regexp = new RE(re);
} catch (RESyntaxException e) {
throw new XPathException("The regular expression '" + str + "' is invalid.");
}
boolean result;
try {
result = regexp.match(str);
} catch (StackOverflowError e) {
throw new XPathException("The regular expression '" + str + "' took too long to process.");
}
return new Boolean(result);
}
private static Object[] subsetArgList(Object[] args, int start) {
return subsetArgList(args, start, 1);
}
/**
* return a subset of an argument list as a new arguments list
*
* @param start index to start at
* @param skip sub-list will contain every nth argument, where n == skip (default: 1)
*/
private static Object[] subsetArgList(Object[] args, int start, int skip) {
if (start > args.length || skip < 1) {
throw new RuntimeException("error in subsetting arglist");
}
Object[] subargs = new Object[(int)MathUtils.divLongNotSuck(args.length - start - 1, skip) + 1];
for (int i = start, j = 0; i < args.length; i += skip, j++) {
subargs[j] = args[i];
}
return subargs;
}
public static Object unpack(Object o) {
if (o instanceof XPathNodeset) {
return ((XPathNodeset)o).unpack();
} else {
return o;
}
}
@Override
public Object pivot(DataInstance model, EvaluationContext evalContext, Vector<Object> pivots, Object sentinal) throws UnpivotableExpressionException {
String name = id.toString();
//for now we'll assume that all that functions do is return the composition of their components
Object[] argVals = new Object[args.length];
//Identify whether this function is an identity: IE: can reflect back the pivot sentinal with no modification
String[] identities = new String[]{"string-length"};
boolean id = false;
for (String identity : identities) {
if (identity.equals(name)) {
id = true;
}
}
//get each argument's pivot
for (int i = 0; i < args.length; i++) {
argVals[i] = args[i].pivot(model, evalContext, pivots, sentinal);
}
boolean pivoted = false;
//evaluate the pivots
for (int i = 0; i < argVals.length; ++i) {
if (argVals[i] == null) {
//one of our arguments contained pivots,
pivoted = true;
} else if (sentinal.equals(argVals[i])) {
//one of our arguments is the sentinal, return the sentinal if possible
if (id) {
return sentinal;
} else {
//This function modifies the sentinal in a way that makes it impossible to capture
//the pivot.
throw new UnpivotableExpressionException();
}
}
}
if (pivoted) {
if (id) {
return null;
} else {
//This function modifies the sentinal in a way that makes it impossible to capture
//the pivot.
throw new UnpivotableExpressionException();
}
}
//TODO: Inner eval here with eval'd args to improve speed
return eval(model, evalContext);
}
/**
* Implementation of natural logarithm
*
* @param o Value
* @return Natural log of value
*/
private Double log(Object o) {
//#if polish.cldc
//# throw new XPathUnsupportedException("Sorry, logarithms are not supported on your platform");
//#else
double value = toDouble(o).doubleValue();
return Math.log(value);
//#endif
}
/**
* Returns the sine of the argument, expressed in radians.
*
* @param o Value
* @return sine of value
*/
private Double sin(Object o) {
//#if polish.cldc
//# throw new XPathUnsupportedException("Sorry, sines are not supported on your platform");
//#else
double value = toDouble(o).doubleValue();
return Math.sin(value);
//#endif
}
/**
* Returns the cosine of the argument, expressed in radians.
*
* @param o Value
* @return cosine of value
*/
private Double cosin(Object o) {
//#if polish.cldc
//# throw new XPathUnsupportedException("Sorry, cosines are not supported on your platform");
//#else
double value = toDouble(o).doubleValue();
return Math.cos(value);
//#endif
}
/**
* Returns the tangent of the argument, expressed in radians.
*
* @param o Value
* @return tan of value
*/
private Double tan(Object o) {
//#if polish.cldc
//# throw new XPathUnsupportedException("Sorry, tangents are not supported on your platform");
//#else
double value = toDouble(o).doubleValue();
return Math.tan(value);
//#endif
}
/**
* Returns the square root of the argument, expressed in radians.
*
* @param o Value
* @return tan of value
*/
private Double sqrt(Object o) {
//#if polish.cldc
//# throw new XPathUnsupportedException("Sorry, square roots are not supported on your platform");
//#else
double value = toDouble(o).doubleValue();
return Math.sqrt(value);
//#endif
}
/**
* Returns the arc cosine of the argument, expressed in radians.
*
* @param o Value
* @return tan of value
*/
private Double acos(Object o) {
//#if polish.cldc
//# throw new XPathUnsupportedException("Sorry, arc cosines are not supported on your platform");
//#else
double value = toDouble(o).doubleValue();
return Math.acos(value);
//#endif
}
/**
* Returns the arc sine of the argument, expressed in radians.
*
* @param o Value
* @return tan of value
*/
private Double asin(Object o) {
//#if polish.cldc
//# throw new XPathUnsupportedException("Sorry, arc sines are not supported on your platform");
//#else
double value = toDouble(o).doubleValue();
return Math.asin(value);
//#endif
}
/**
* Returns the arc tan of the argument, expressed in radians.
*
* @param o Value
* @return tan of value
*/
private Double atan(Object o) {
//#if polish.cldc
//# throw new XPathUnsupportedException("Sorry, arc tans are not supported on your platform");
//#else
double value = toDouble(o).doubleValue();
return Math.atan(value);
//#endif
}
/**
* Implementation of logarithm with base ten
*
* @param o Value
* @return Base ten log of value
*/
private Double log10(Object o) {
//#if polish.cldc
//# throw new XPathUnsupportedException("Sorry, logarithms are not supported on your platform");
//#else
double value = toDouble(o).doubleValue();
return Math.log10(value);
//#endif
}
/**
* Implementation of logarithm with base ten
*
* @return Base ten log of value
*/
private Double pi() {
//#if polish.cldc
//# throw new XPathUnsupportedException("Sorry, Pi are not supported on your platform");
//#else
return Math.PI;
//#endif
}
/**
* Implementation of logarithm with base ten
*
* @param o1, o2 Value
* @return Base ten log of value
*/
private Double atan2(Object o1, Object o2) {
//#if polish.cldc
//# throw new XPathUnsupportedException("Sorry, atan are not supported on your platform");
//#else
double value1 = toDouble(o1).doubleValue();
double value2 = toDouble(o2).doubleValue();
return Math.atan2(value1, value2);
//#endif
}
/**
* Implementation of logarithm with base ten
*
* @param o Value
* @return Base ten log of value
*/
private Double exp(Object o) {
//#if polish.cldc
//# throw new XPathUnsupportedException("Sorry, exponentials are not supported on your platform");
//#else
double value = toDouble(o).doubleValue();
return Math.exp(value);
//#endif
}
/**
* Best faith effort at getting a result for math.pow
*
* @param o1 The base number
* @param o2 The exponent of the number that it is to be raised to
* @return An approximation of o1 ^ o2. If there is a native power
* function, it is utilized. It there is not, a recursive exponent is
* run if (b) is an integer value, and a taylor series approximation is
* used otherwise.
*/
private Double power(Object o1, Object o2) {
//#if polish.cldc
//# //CLDC doesn't support craziness like "power" functions, so we're on our own.
//# return powerApprox(o1, o2);
//#else
//Just use the native lib! should be available.
double a = toDouble(o1).doubleValue();
double b = toDouble(o2).doubleValue();
return Math.pow(a, b);
//#endif
}
private Double powerApprox(Object o1, Object o2) {
double a = toDouble(o1).doubleValue();
Double db = toDouble(o2);
//We need to determine if "b" is a double, or an integer.
if (Math.abs(db.doubleValue() - toInt(db).doubleValue()) > DOUBLE_TOLERANCE) {
throw new XPathUnsupportedException("Sorry, power functions with non-integer exponents are not supported on your platform");
} else {
//Integer it is, whew!
int b = db.intValue();
//One last check. If b is negative, we need to invert A,
//and then do the exponent.
if (b < 0) {
b = -b;
a = 1.0 / a;
}
//Ok, now we can do a simple recursive solution
return power(a, b);
}
}
private static Double power(double a, int b) {
if (b == 0) {
return new Double(1.0);
}
double ret = a;
for (int i = 1; i < b; ++i) {
ret *= a;
}
return new Double(ret);
}
/**
* This code is fairly legit, but it not compliant with actual
* floating point math reqs. I don't know whether we
* should expose the option of using it, exactly.
*/
public static double pow(final double a, final double b) {
final long tmp = Double.doubleToLongBits(a);
final long tmp2 = (long)(b * (tmp - 4606921280493453312L)) + 4606921280493453312L;
return Double.longBitsToDouble(tmp2);
}
public static final double DOUBLE_TOLERANCE = 1.0e-12;
/**
* Take in a value (only a string for now, TODO: Extend?) that doesn't
* have any type information and attempt to infer a more specific type
* that may assist in equality or comparison operations
*
* @param attrValue A typeless data object
* @return The passed in object in as specific of a type as was able to
* be identified.
*/
public static Object InferType(String attrValue) {
//Throwing exceptions from parsing doubles is _very_ slow, which is the purpose
//of this cache. In high performant situations, this prevents a ton of overhead.
Double d = mDoubleParseCache.retrieve(attrValue);
if(d != null) {
if(d.isNaN()) {
return attrValue;
} else {
return d;
}
}
try {
Double ret = new Double(Double.parseDouble(attrValue));
mDoubleParseCache.register(attrValue, ret);
return ret;
} catch (NumberFormatException ife) {
//Not a double
mDoubleParseCache.register(attrValue, new Double(Double.NaN));
}
//TODO: What about dates? That is a _super_ expensive
//operation to be testing, though...
return attrValue;
}
/**
* Gets a human readable string representing an xpath nodeset.
*
* @param nodeset An xpath nodeset to be visualized
* @return A string representation of the nodeset's references
*/
public static String getSerializedNodeset(XPathNodeset nodeset) {
if (nodeset.size() == 1) {
return XPathFuncExpr.toString(nodeset);
}
StringBuffer sb = new StringBuffer();
sb.append("{nodeset: ");
for (int i = 0; i < nodeset.size(); ++i) {
String ref = nodeset.getRefAt(i).toString(true);
sb.append(ref);
if (i != nodeset.size() - 1) {
sb.append(", ");
}
}
sb.append("}");
return sb.toString();
}
} |
package com.supinfo.controler.connection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class ConnectToServer {
private int portNumber;
private String serverHostname;
private String fromServer;
private String fromClient;
public void ConnectToServer() {
//TODO Change NOVA to freljord
this.ConnectToServer("NOVA", 4165);
}
public void ConnectToServer(String hostname,int port){
this.portNumber = port;
this.serverHostname = hostname;
}
private void openConnection(String toSend) {
try(
Socket clientSocket =new Socket(serverHostname, portNumber);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in =new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
while ((fromServer = in.readLine()) != null) {
if (toSend != null) {
out.println(toSend);
}
System.out.println("Server: " + fromServer);
if (fromServer.equals("Bye."))
break;
}
} catch (UnknownHostException e) {
System.err.println("Don't know about host " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to " +
serverHostname);
System.exit(1);
} finally {
}
}
} |
package org.mskcc.cbio.portal.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import javax.sql.DataSource;
public class SpringUtil
{
private static final Log log = LogFactory.getLog(SpringUtil.class);
private static AccessControl accessControl;
private static ApplicationContext context;
public static void setAccessControl(AccessControl accessControl) {
log.debug("Setting access control");
SpringUtil.accessControl = accessControl;
}
public static AccessControl getAccessControl()
{
return accessControl;
}
public static synchronized void initDataSource()
{
if (SpringUtil.context == null) {
context = new ClassPathXmlApplicationContext("classpath:applicationContext-business.xml");
}
}
} |
package com.gmail.nossr50.datatypes;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import com.gmail.nossr50.mcMMO;
import com.gmail.nossr50.config.Config;
import com.gmail.nossr50.database.Database;
import com.gmail.nossr50.skills.utilities.AbilityType;
import com.gmail.nossr50.skills.utilities.SkillType;
import com.gmail.nossr50.skills.utilities.ToolType;
import com.gmail.nossr50.spout.SpoutConfig;
import com.gmail.nossr50.spout.huds.HudType;
import com.gmail.nossr50.spout.huds.SpoutHud;
import com.gmail.nossr50.util.Misc;
public class PlayerProfile {
private String playerName;
// HUD
private SpoutHud spoutHud;
private HudType hudType;
// Toggles
private boolean loaded;
private boolean placedAnvil;
private boolean placedSalvageAnvil;
private boolean godMode;
private boolean greenTerraMode, treeFellerMode, superBreakerMode, gigaDrillBreakerMode, serratedStrikesMode, skullSplitterMode, berserkMode;
private boolean greenTerraInformed = true, berserkInformed = true, skullSplitterInformed = true, gigaDrillBreakerInformed = true,
superBreakerInformed = true, blastMiningInformed = true, serratedStrikesInformed = true, treeFellerInformed = true;
private boolean hoePreparationMode, shovelPreparationMode, swordsPreparationMode, fistsPreparationMode,
pickaxePreparationMode, axePreparationMode;
private boolean abilityUse = true;
// Timestamps
private long recentlyHurt;
private int respawnATS;
// mySQL STUFF
private int userId;
private HashMap<SkillType, Integer> skills = new HashMap<SkillType, Integer>(); //Skills and Levels
HashMap<SkillType, Integer> skillsXp = new HashMap<SkillType, Integer>(); //Skills and Xp
HashMap<AbilityType, Integer> skillsDATS = new HashMap<AbilityType, Integer>();
HashMap<ToolType, Integer> toolATS = new HashMap<ToolType, Integer>();
private final static String location = mcMMO.getUsersFilePath();
public PlayerProfile(String playerName, boolean addNew) {
this.playerName = playerName;
if (mcMMO.spoutEnabled) {
hudType = SpoutConfig.getInstance().defaultHudType;
}
else {
hudType = HudType.DISABLED;
}
for (AbilityType abilityType : AbilityType.values()) {
skillsDATS.put(abilityType, 0);
}
for (SkillType skillType : SkillType.values()) {
if (!skillType.isChildSkill()) {
skills.put(skillType, 0);
skillsXp.put(skillType, 0);
}
}
if (Config.getInstance().getUseMySQL()) {
if (!loadMySQL() && addNew) {
addMySQLPlayer();
loaded = true;
}
}
else if (!load() && addNew) {
addPlayer();
loaded = true;
}
}
public String getPlayerName() {
return playerName;
}
public boolean loadMySQL() {
String tablePrefix = Config.getInstance().getMySQLTablePrefix();
userId = Database.getInt("SELECT id FROM " + tablePrefix + "users WHERE user = '" + playerName + "'");
if (userId == 0) {
return false;
}
HashMap<Integer, ArrayList<String>> huds = Database.read("SELECT hudtype FROM " + tablePrefix + "huds WHERE user_id = " + userId);
if (huds.get(1) == null) {
Database.write("INSERT INTO " + tablePrefix + "huds (user_id) VALUES (" + userId + ")");
}
else {
for (HudType type : HudType.values()) {
if (type.toString().equals(huds.get(1).get(0))) {
hudType = type;
}
}
}
/*
* I'm still learning MySQL, this is a fix for adding a new table
* its not pretty but it works
*/
HashMap<Integer, ArrayList<String>> cooldowns = Database.read("SELECT mining, woodcutting, unarmed, herbalism, excavation, swords, axes, blast_mining FROM " + tablePrefix + "cooldowns WHERE user_id = " + userId);
ArrayList<String> cooldownValues = cooldowns.get(1);
if (cooldownValues == null) {
Database.write("INSERT INTO " + tablePrefix + "cooldowns (user_id) VALUES (" + userId + ")");
mcMMO.p.getLogger().warning(playerName + "does not exist in the cooldown table. Their cooldowns will be reset.");
}
else {
skillsDATS.put(AbilityType.SUPER_BREAKER, Integer.valueOf(cooldownValues.get(0)));
skillsDATS.put(AbilityType.TREE_FELLER, Integer.valueOf(cooldownValues.get(1)));
skillsDATS.put(AbilityType.BERSERK, Integer.valueOf(cooldownValues.get(2)));
skillsDATS.put(AbilityType.GREEN_TERRA, Integer.valueOf(cooldownValues.get(3)));
skillsDATS.put(AbilityType.GIGA_DRILL_BREAKER, Integer.valueOf(cooldownValues.get(4)));
skillsDATS.put(AbilityType.SERRATED_STRIKES, Integer.valueOf(cooldownValues.get(5)));
skillsDATS.put(AbilityType.SKULL_SPLIITER, Integer.valueOf(cooldownValues.get(6)));
skillsDATS.put(AbilityType.BLAST_MINING, Integer.valueOf(cooldownValues.get(7)));
}
HashMap<Integer, ArrayList<String>> stats = Database.read("SELECT taming, mining, repair, woodcutting, unarmed, herbalism, excavation, archery, swords, axes, acrobatics, fishing FROM " + tablePrefix + "skills WHERE user_id = " + userId);
ArrayList<String> statValues = stats.get(1);
if (statValues == null) {
Database.write("INSERT INTO " + tablePrefix + "skills (user_id) VALUES (" + userId + ")");
mcMMO.p.getLogger().warning(playerName + "does not exist in the skills table. Their stats will be reset.");
}
else {
skills.put(SkillType.TAMING, Integer.valueOf(statValues.get(0)));
skills.put(SkillType.MINING, Integer.valueOf(statValues.get(1)));
skills.put(SkillType.REPAIR, Integer.valueOf(statValues.get(2)));
skills.put(SkillType.WOODCUTTING, Integer.valueOf(statValues.get(3)));
skills.put(SkillType.UNARMED, Integer.valueOf(statValues.get(4)));
skills.put(SkillType.HERBALISM, Integer.valueOf(statValues.get(5)));
skills.put(SkillType.EXCAVATION, Integer.valueOf(statValues.get(6)));
skills.put(SkillType.ARCHERY, Integer.valueOf(statValues.get(7)));
skills.put(SkillType.SWORDS, Integer.valueOf(statValues.get(8)));
skills.put(SkillType.AXES, Integer.valueOf(statValues.get(9)));
skills.put(SkillType.ACROBATICS, Integer.valueOf(statValues.get(10)));
skills.put(SkillType.FISHING, Integer.valueOf(statValues.get(11)));
}
HashMap<Integer, ArrayList<String>> experience = Database.read("SELECT taming, mining, repair, woodcutting, unarmed, herbalism, excavation, archery, swords, axes, acrobatics, fishing FROM " + tablePrefix + "experience WHERE user_id = " + userId);
ArrayList<String> experienceValues = experience.get(1);
if (experienceValues == null) {
Database.write("INSERT INTO " + tablePrefix + "experience (user_id) VALUES (" + userId + ")");
mcMMO.p.getLogger().warning(playerName + "does not exist in the experience table. Their experience will be reset.");
}
else {
skillsXp.put(SkillType.TAMING, Integer.valueOf(experienceValues.get(0)));
skillsXp.put(SkillType.MINING, Integer.valueOf(experienceValues.get(1)));
skillsXp.put(SkillType.REPAIR, Integer.valueOf(experienceValues.get(2)));
skillsXp.put(SkillType.WOODCUTTING, Integer.valueOf(experienceValues.get(3)));
skillsXp.put(SkillType.UNARMED, Integer.valueOf(experienceValues.get(4)));
skillsXp.put(SkillType.HERBALISM, Integer.valueOf(experienceValues.get(5)));
skillsXp.put(SkillType.EXCAVATION, Integer.valueOf(experienceValues.get(6)));
skillsXp.put(SkillType.ARCHERY, Integer.valueOf(experienceValues.get(7)));
skillsXp.put(SkillType.SWORDS, Integer.valueOf(experienceValues.get(8)));
skillsXp.put(SkillType.AXES, Integer.valueOf(experienceValues.get(9)));
skillsXp.put(SkillType.ACROBATICS, Integer.valueOf(experienceValues.get(10)));
skillsXp.put(SkillType.FISHING, Integer.valueOf(experienceValues.get(11)));
}
loaded = true;
return true;
}
public void addMySQLPlayer() {
String tablePrefix = Config.getInstance().getMySQLTablePrefix();
Database.write("INSERT INTO " + tablePrefix + "users (user, lastlogin) VALUES ('" + playerName + "'," + System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR + ")");
userId = Database.getInt("SELECT id FROM "+tablePrefix + "users WHERE user = '" + playerName + "'");
Database.write("INSERT INTO " + tablePrefix + "cooldowns (user_id) VALUES (" + userId + ")");
Database.write("INSERT INTO " + tablePrefix + "skills (user_id) VALUES (" + userId + ")");
Database.write("INSERT INTO " + tablePrefix + "experience (user_id) VALUES (" + userId + ")");
}
public boolean load() {
try {
// Open the user file
FileReader file = new FileReader(location);
BufferedReader in = new BufferedReader(file);
String line;
while ((line = in.readLine()) != null) {
// Find if the line contains the player we want.
String[] character = line.split(":");
if (!character[0].equals(playerName)) {
continue;
}
if (character.length > 1 && Misc.isInt(character[1]))
skills.put(SkillType.MINING, Integer.valueOf(character[1]));
if (character.length > 4 && Misc.isInt(character[4]))
skillsXp.put(SkillType.MINING, Integer.valueOf(character[4]));
if (character.length > 5 && Misc.isInt(character[5]))
skills.put(SkillType.WOODCUTTING, Integer.valueOf(character[5]));
if (character.length > 6 && Misc.isInt(character[6]))
skillsXp.put(SkillType.WOODCUTTING, Integer.valueOf(character[6]));
if (character.length > 7 && Misc.isInt(character[7]))
skills.put(SkillType.REPAIR, Integer.valueOf(character[7]));
if (character.length > 8 && Misc.isInt(character[8]))
skills.put(SkillType.UNARMED, Integer.valueOf(character[8]));
if (character.length > 9 && Misc.isInt(character[9]))
skills.put(SkillType.HERBALISM, Integer.valueOf(character[9]));
if (character.length > 10 && Misc.isInt(character[10]))
skills.put(SkillType.EXCAVATION, Integer.valueOf(character[10]));
if (character.length > 11 && Misc.isInt(character[11]))
skills.put(SkillType.ARCHERY, Integer.valueOf(character[11]));
if (character.length > 12 && Misc.isInt(character[12]))
skills.put(SkillType.SWORDS, Integer.valueOf(character[12]));
if (character.length > 13 && Misc.isInt(character[13]))
skills.put(SkillType.AXES, Integer.valueOf(character[13]));
if (character.length > 14 && Misc.isInt(character[14]))
skills.put(SkillType.ACROBATICS, Integer.valueOf(character[14]));
if (character.length > 15 && Misc.isInt(character[15]))
skillsXp.put(SkillType.REPAIR, Integer.valueOf(character[15]));
if (character.length > 16 && Misc.isInt(character[16]))
skillsXp.put(SkillType.UNARMED, Integer.valueOf(character[16]));
if (character.length > 17 && Misc.isInt(character[17]))
skillsXp.put(SkillType.HERBALISM, Integer.valueOf(character[17]));
if (character.length > 18 && Misc.isInt(character[18]))
skillsXp.put(SkillType.EXCAVATION, Integer.valueOf(character[18]));
if (character.length > 19 && Misc.isInt(character[19]))
skillsXp.put(SkillType.ARCHERY, Integer.valueOf(character[19]));
if (character.length > 20 && Misc.isInt(character[20]))
skillsXp.put(SkillType.SWORDS, Integer.valueOf(character[20]));
if (character.length > 21 && Misc.isInt(character[21]))
skillsXp.put(SkillType.AXES, Integer.valueOf(character[21]));
if (character.length > 22 && Misc.isInt(character[22]))
skillsXp.put(SkillType.ACROBATICS, Integer.valueOf(character[22]));
if (character.length > 24 && Misc.isInt(character[24]))
skills.put(SkillType.TAMING, Integer.valueOf(character[24]));
if (character.length > 25 && Misc.isInt(character[25]))
skillsXp.put(SkillType.TAMING, Integer.valueOf(character[25]));
if (character.length > 26)
skillsDATS.put(AbilityType.BERSERK, Integer.valueOf(character[26]));
if (character.length > 27)
skillsDATS.put(AbilityType.GIGA_DRILL_BREAKER, Integer.valueOf(character[27]));
if (character.length > 28)
skillsDATS.put(AbilityType.TREE_FELLER, Integer.valueOf(character[28]));
if (character.length > 29)
skillsDATS.put(AbilityType.GREEN_TERRA, Integer.valueOf(character[29]));
if (character.length > 30)
skillsDATS.put(AbilityType.SERRATED_STRIKES, Integer.valueOf(character[30]));
if (character.length > 31)
skillsDATS.put(AbilityType.SKULL_SPLIITER, Integer.valueOf(character[31]));
if (character.length > 32)
skillsDATS.put(AbilityType.SUPER_BREAKER, Integer.valueOf(character[32]));
if (character.length > 33) {
for (HudType type : HudType.values()) {
if (type.toString().equalsIgnoreCase(character[33])) {
hudType = type;
}
}
}
if (character.length > 34)
skills.put(SkillType.FISHING, Integer.valueOf(character[34]));
if (character.length > 35)
skillsXp.put(SkillType.FISHING, Integer.valueOf(character[35]));
if (character.length > 36)
skillsDATS.put(AbilityType.BLAST_MINING, Integer.valueOf(character[36]));
loaded = true;
in.close();
return true;
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public void save() {
Long timestamp = System.currentTimeMillis();
// If we are using mysql save to database
if (Config.getInstance().getUseMySQL()) {
String tablePrefix = Config.getInstance().getMySQLTablePrefix();
Database.write("UPDATE " + tablePrefix + "huds SET hudtype = '" + hudType.toString() + "' WHERE user_id = " + userId);
Database.write("UPDATE " + tablePrefix + "users SET lastlogin = " + ((int) (timestamp / Misc.TIME_CONVERSION_FACTOR)) + " WHERE id = " + userId);
Database.write("UPDATE " + tablePrefix + "cooldowns SET "
+ " mining = " + skillsDATS.get(AbilityType.SUPER_BREAKER)
+ ", woodcutting = " + skillsDATS.get(AbilityType.TREE_FELLER)
+ ", unarmed = " + skillsDATS.get(AbilityType.BERSERK)
+ ", herbalism = " + skillsDATS.get(AbilityType.GREEN_TERRA)
+ ", excavation = " + skillsDATS.get(AbilityType.GIGA_DRILL_BREAKER)
+ ", swords = " + skillsDATS.get(AbilityType.SERRATED_STRIKES)
+ ", axes = " + skillsDATS.get(AbilityType.SKULL_SPLIITER)
+ ", blast_mining = " + skillsDATS.get(AbilityType.BLAST_MINING)
+ " WHERE user_id = " + userId);
Database.write("UPDATE " + tablePrefix + "skills SET "
+ " taming = " + skills.get(SkillType.TAMING)
+ ", mining = " + skills.get(SkillType.MINING)
+ ", repair = " + skills.get(SkillType.REPAIR)
+ ", woodcutting = " + skills.get(SkillType.WOODCUTTING)
+ ", unarmed = " + skills.get(SkillType.UNARMED)
+ ", herbalism = " + skills.get(SkillType.HERBALISM)
+ ", excavation = " + skills.get(SkillType.EXCAVATION)
+ ", archery = " + skills.get(SkillType.ARCHERY)
+ ", swords = " + skills.get(SkillType.SWORDS)
+ ", axes = " + skills.get(SkillType.AXES)
+ ", acrobatics = " + skills.get(SkillType.ACROBATICS)
+ ", fishing = " + skills.get(SkillType.FISHING)
+ " WHERE user_id = " + userId);
Database.write("UPDATE " + tablePrefix + "experience SET "
+ " taming = " + skillsXp.get(SkillType.TAMING)
+ ", mining = " + skillsXp.get(SkillType.MINING)
+ ", repair = " + skillsXp.get(SkillType.REPAIR)
+ ", woodcutting = " + skillsXp.get(SkillType.WOODCUTTING)
+ ", unarmed = " + skillsXp.get(SkillType.UNARMED)
+ ", herbalism = " + skillsXp.get(SkillType.HERBALISM)
+ ", excavation = " + skillsXp.get(SkillType.EXCAVATION)
+ ", archery = " + skillsXp.get(SkillType.ARCHERY)
+ ", swords = " + skillsXp.get(SkillType.SWORDS)
+ ", axes = " + skillsXp.get(SkillType.AXES)
+ ", acrobatics = " + skillsXp.get(SkillType.ACROBATICS)
+ ", fishing = " + skillsXp.get(SkillType.FISHING)
+ " WHERE user_id = " + userId);
}
else {
// Otherwise save to flatfile
try {
// Open the file
FileReader file = new FileReader(location);
BufferedReader in = new BufferedReader(file);
StringBuilder writer = new StringBuilder();
String line;
// While not at the end of the file
while ((line = in.readLine()) != null) {
// Read the line in and copy it to the output it's not the player
// we want to edit
if (!line.split(":")[0].equals(playerName)) {
writer.append(line).append("\r\n");
}
else {
// Otherwise write the new player information
writer.append(playerName).append(":");
writer.append(skills.get(SkillType.MINING)).append(":");
writer.append(":");
writer.append(":");
writer.append(skillsXp.get(SkillType.MINING)).append(":");
writer.append(skills.get(SkillType.WOODCUTTING)).append(":");
writer.append(skillsXp.get(SkillType.WOODCUTTING)).append(":");
writer.append(skills.get(SkillType.REPAIR)).append(":");
writer.append(skills.get(SkillType.UNARMED)).append(":");
writer.append(skills.get(SkillType.HERBALISM)).append(":");
writer.append(skills.get(SkillType.EXCAVATION)).append(":");
writer.append(skills.get(SkillType.ARCHERY)).append(":");
writer.append(skills.get(SkillType.SWORDS)).append(":");
writer.append(skills.get(SkillType.AXES)).append(":");
writer.append(skills.get(SkillType.ACROBATICS)).append(":");
writer.append(skillsXp.get(SkillType.REPAIR)).append(":");
writer.append(skillsXp.get(SkillType.UNARMED)).append(":");
writer.append(skillsXp.get(SkillType.HERBALISM)).append(":");
writer.append(skillsXp.get(SkillType.EXCAVATION)).append(":");
writer.append(skillsXp.get(SkillType.ARCHERY)).append(":");
writer.append(skillsXp.get(SkillType.SWORDS)).append(":");
writer.append(skillsXp.get(SkillType.AXES)).append(":");
writer.append(skillsXp.get(SkillType.ACROBATICS)).append(":");
writer.append(":");
writer.append(skills.get(SkillType.TAMING)).append(":");
writer.append(skillsXp.get(SkillType.TAMING)).append(":");
// Need to store the DATS of abilities nao
// Berserk, Gigadrillbreaker, Tree Feller, Green Terra, Serrated Strikes, Skull Splitter, Super Breaker
writer.append(String.valueOf(skillsDATS.get(AbilityType.BERSERK))).append(":");
writer.append(String.valueOf(skillsDATS.get(AbilityType.GIGA_DRILL_BREAKER))).append(":");
writer.append(String.valueOf(skillsDATS.get(AbilityType.TREE_FELLER))).append(":");
writer.append(String.valueOf(skillsDATS.get(AbilityType.GREEN_TERRA))).append(":");
writer.append(String.valueOf(skillsDATS.get(AbilityType.SERRATED_STRIKES))).append(":");
writer.append(String.valueOf(skillsDATS.get(AbilityType.SKULL_SPLIITER))).append(":");
writer.append(String.valueOf(skillsDATS.get(AbilityType.SUPER_BREAKER))).append(":");
writer.append(hudType.toString()).append(":");
writer.append(skills.get(SkillType.FISHING)).append(":");
writer.append(skillsXp.get(SkillType.FISHING)).append(":");
writer.append(String.valueOf(skillsDATS.get(AbilityType.BLAST_MINING))).append(":");
writer.append("\r\n");
}
}
in.close();
// Write the new file
FileWriter out = new FileWriter(location);
out.write(writer.toString());
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
public void addPlayer() {
try {
// Open the file to write the player
FileWriter file = new FileWriter(location, true);
BufferedWriter out = new BufferedWriter(file);
// Add the player to the end
out.append(playerName).append(":");
out.append("0:"); // mining
out.append(":");
out.append(":");
out.append("0:");
out.append("0:"); // woodcutting
out.append("0:"); // woodCuttingXp
out.append("0:"); // repair
out.append("0:"); // unarmed
out.append("0:"); // herbalism
out.append("0:"); // excavation
out.append("0:"); // archery
out.append("0:"); // swords
out.append("0:"); // axes
out.append("0:"); // acrobatics
out.append("0:"); // repairXp
out.append("0:"); // unarmedXp
out.append("0:"); // herbalismXp
out.append("0:"); // excavationXp
out.append("0:"); // archeryXp
out.append("0:"); // swordsXp
out.append("0:"); // axesXp
out.append("0:"); // acrobaticsXp
out.append(":");
out.append("0:"); // taming
out.append("0:"); // tamingXp
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append("0:"); // DATS
out.append(hudType.toString()).append(":"); // HUD
out.append("0:"); // Fishing
out.append("0:"); // FishingXp
out.append("0:"); // Blast Mining
// Add more in the same format as the line above
out.newLine();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* mySQL Stuff
*/
public int getMySQLuserId() {
return userId;
}
public boolean isLoaded() {
return loaded;
}
/*
* God Mode
*/
public boolean getGodMode() {
return godMode;
}
public void toggleGodMode() {
godMode = !godMode;
}
/*
* Repair Anvil Placement
*/
public void togglePlacedAnvil() {
placedAnvil = !placedAnvil;
}
public Boolean getPlacedAnvil() {
return placedAnvil;
}
/*
* Salvage Anvil Placement
*/
public void togglePlacedSalvageAnvil() {
placedSalvageAnvil = !placedSalvageAnvil;
}
public Boolean getPlacedSalvageAnvil() {
return placedSalvageAnvil;
}
/*
* HUD Stuff
*/
public HudType getHudType() {
return hudType;
}
public SpoutHud getSpoutHud() {
return spoutHud;
}
public void setSpoutHud(SpoutHud spoutHud) {
this.spoutHud = spoutHud;
}
public void setHudType(HudType hudType) {
this.hudType = hudType;
}
/*
* Tools
*/
/**
* Reset the prep modes of all tools.
*/
public void resetToolPrepMode() {
for (ToolType tool : ToolType.values()) {
setToolPreparationMode(tool, false);
}
}
/**
* Get the current prep mode of a tool.
*
* @param tool Tool to get the mode for
* @return true if the tool is prepped, false otherwise
*/
public boolean getToolPreparationMode(ToolType tool) {
switch (tool) {
case AXE:
return axePreparationMode;
case FISTS:
return fistsPreparationMode;
case HOE:
return hoePreparationMode;
case PICKAXE:
return pickaxePreparationMode;
case SHOVEL:
return shovelPreparationMode;
case SWORD:
return swordsPreparationMode;
default:
return false;
}
}
/**
* Set the current prep mode of a tool.
*
* @param tool Tool to set the mode for
* @param bool true if the tool should be prepped, false otherwise
*/
public void setToolPreparationMode(ToolType tool, boolean bool) {
switch (tool) {
case AXE:
axePreparationMode = bool;
break;
case FISTS:
fistsPreparationMode = bool;
break;
case HOE:
hoePreparationMode = bool;
break;
case PICKAXE:
pickaxePreparationMode = bool;
break;
case SHOVEL:
shovelPreparationMode = bool;
break;
case SWORD:
swordsPreparationMode = bool;
break;
default:
break;
}
}
/**
* Get the current prep ATS of a tool.
*
* @param tool Tool to get the ATS for
* @return the ATS for the tool
*/
public long getToolPreparationATS(ToolType tool) {
return toolATS.get(tool);
}
/**
* Set the current prep ATS of a tool.
*
* @param tool Tool to set the ATS for
* @param ATS the ATS of the tool
*/
public void setToolPreparationATS(ToolType tool, long ATS) {
int startTime = (int) (ATS / Misc.TIME_CONVERSION_FACTOR);
toolATS.put(tool, startTime);
}
/*
* Abilities
*/
/**
* Reset the prep modes of all tools.
*/
public void resetAbilityMode() {
for (AbilityType ability : AbilityType.values()) {
setAbilityMode(ability, false);
}
}
/**
* Get the mode of an ability.
*
* @param ability The ability to check
* @return true if the ability is enabled, false otherwise
*/
public boolean getAbilityMode(AbilityType ability) {
switch (ability) {
case BERSERK:
return berserkMode;
case SUPER_BREAKER:
return superBreakerMode;
case GIGA_DRILL_BREAKER:
return gigaDrillBreakerMode;
case GREEN_TERRA:
return greenTerraMode;
case SKULL_SPLIITER:
return skullSplitterMode;
case TREE_FELLER:
return treeFellerMode;
case SERRATED_STRIKES:
return serratedStrikesMode;
default:
return false;
}
}
/**
* Set the mode of an ability.
*
* @param ability The ability to check
* @param bool True if the ability is active, false otherwise
*/
public void setAbilityMode(AbilityType ability, boolean bool) {
switch (ability) {
case BERSERK:
berserkMode = bool;
break;
case SUPER_BREAKER:
superBreakerMode = bool;
break;
case GIGA_DRILL_BREAKER:
gigaDrillBreakerMode = bool;
break;
case GREEN_TERRA:
greenTerraMode = bool;
break;
case SKULL_SPLIITER:
skullSplitterMode = bool;
break;
case TREE_FELLER:
treeFellerMode = bool;
break;
case SERRATED_STRIKES:
serratedStrikesMode = bool;
break;
default:
break;
}
}
/**
* Get the informed state of an ability
*
* @param ability The ability to check
* @return true if the ability is informed, false otherwise
*/
public boolean getAbilityInformed(AbilityType ability) {
switch (ability) {
case BERSERK:
return berserkInformed;
case BLAST_MINING:
return blastMiningInformed;
case SUPER_BREAKER:
return superBreakerInformed;
case GIGA_DRILL_BREAKER:
return gigaDrillBreakerInformed;
case GREEN_TERRA:
return greenTerraInformed;
case SKULL_SPLIITER:
return skullSplitterInformed;
case TREE_FELLER:
return treeFellerInformed;
case SERRATED_STRIKES:
return serratedStrikesInformed;
default:
return false;
}
}
/**
* Set the informed state of an ability.
*
* @param ability The ability to check
* @param bool True if the ability is informed, false otherwise
*/
public void setAbilityInformed(AbilityType ability, boolean bool) {
switch (ability) {
case BERSERK:
berserkInformed = bool;
break;
case BLAST_MINING:
blastMiningInformed = bool;
break;
case SUPER_BREAKER:
superBreakerInformed = bool;
break;
case GIGA_DRILL_BREAKER:
gigaDrillBreakerInformed = bool;
break;
case GREEN_TERRA:
greenTerraInformed = bool;
break;
case SKULL_SPLIITER:
skullSplitterInformed = bool;
break;
case TREE_FELLER:
treeFellerInformed = bool;
break;
case SERRATED_STRIKES:
serratedStrikesInformed = bool;
break;
default:
break;
}
}
public boolean getAbilityUse() {
return abilityUse;
}
public void toggleAbilityUse() {
abilityUse = !abilityUse;
}
/*
* Recently Hurt
*/
public long getRecentlyHurt() {
return recentlyHurt;
}
public void setRecentlyHurt(long value) {
recentlyHurt = value;
}
public void actualizeRecentlyHurt() {
respawnATS = (int) (System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR);
}
/*
* Cooldowns
*/
/**
* Get the current DATS of a skill.
*
* @param abilityType Ability to get the DATS for
* @return the DATS for the ability
*/
public long getSkillDATS(AbilityType abilityType) {
return skillsDATS.get(abilityType);
}
/**
* Set the current DATS of a skill.
*
* @param abilityType Ability to set the DATS for
* @param DATS the DATS of the ability
*/
public void setSkillDATS(AbilityType abilityType, long DATS) {
int wearsOff = (int) (DATS * .001D);
skillsDATS.put(abilityType, wearsOff);
}
/**
* Reset all skill cooldowns.
*/
public void resetCooldowns() {
for (AbilityType x : skillsDATS.keySet()) {
skillsDATS.put(x, 0);
}
}
/*
* Exploit Prevention
*/
public int getRespawnATS() {
return respawnATS;
}
public void actualizeRespawnATS() {
respawnATS = (int) (System.currentTimeMillis() / Misc.TIME_CONVERSION_FACTOR);
}
/*
* Xp Functions
*/
public int getSkillLevel(SkillType skillType) {
if (skillType.isChildSkill()) {
return getChildSkillLevel(skillType);
}
return skills.get(skillType);
}
public int getChildSkillLevel(SkillType skillType) {
switch (skillType) {
case SMELTING:
return ((getSkillLevel(SkillType.MINING) / 4) + (getSkillLevel(SkillType.REPAIR) / 4)); //TODO: Make this cleaner somehow
default:
return 0;
}
}
public int getSkillXpLevel(SkillType skillType) {
return skillsXp.get(skillType);
}
public void setSkillXpLevel(SkillType skillType, int newValue) {
skillsXp.put(skillType, newValue);
}
public void skillUp(SkillType skillType, int newValue) {
skills.put(skillType, skills.get(skillType) + newValue);
}
/**
* Remove Xp from a skill.
*
* @param skillType Type of skill to modify
* @param xp Amount of xp to remove
*/
public void removeXp(SkillType skillType, int xp) {
if (skillType.isChildSkill()) {
return;
}
skillsXp.put(skillType, skillsXp.get(skillType) - xp);
}
/**
* Modify a skill level.
*
* @param skillType Type of skill to modify
* @param newValue New level value for the skill
*/
public void modifySkill(SkillType skillType, int newValue) {
if (skillType.isChildSkill()) {
return;
}
skills.put(skillType, newValue);
skillsXp.put(skillType, 0);
}
/**
* Add levels to a skill.
*
* @param skillType Type of skill to add levels to
* @param levels Number of levels to add
*/
public void addLevels(SkillType skillType, int levels) {
if (skillType.isChildSkill()) {
return;
}
skills.put(skillType, skills.get(skillType) + levels);
skillsXp.put(skillType, 0);
}
/**
* Get the amount of Xp remaining before the next level.
*
* @param skillType Type of skill to check
* @return the Xp remaining until next level
*/
public int getXpToLevel(SkillType skillType) {
return 1020 + (skills.get(skillType) * Config.getInstance().getFormulaMultiplierCurve());
}
} |
package edu.pdx.cs410J.junit;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* This class tests the functionality of the <code>Section</code> class
*/
public class SectionTest {
@Test
public void testAddStudent() {
Student student = new Student("123-45-6789");
Course course = new Course("CS", 410, 4);
Section section =
new Section(course, Section.SPRING, 2001);
section.addStudent(student);
assertEquals(1, section.getClassSize());
}
@Test(expected = IllegalArgumentException.class)
public void testDropStudentNotEnrolled() {
Student student = new Student("123-45-6789");
Course course = new Course("CS", 410, 4);
Section section =
new Section(course, Section.SPRING, 2001);
section.dropStudent(student);
}
} |
package org.ow2.chameleon.rose.util;
import static java.util.Collections.emptyList;
import static org.osgi.framework.Constants.SERVICE_ID;
import static org.osgi.framework.Constants.SERVICE_PID;
import static org.osgi.service.remoteserviceadmin.RemoteConstants.ENDPOINT_FRAMEWORK_UUID;
import static org.osgi.service.remoteserviceadmin.RemoteConstants.ENDPOINT_ID;
import static org.osgi.service.remoteserviceadmin.RemoteConstants.SERVICE_IMPORTED_CONFIGS;
import static org.ow2.chameleon.rose.ExporterService.ENDPOINT_CONFIG_PREFIX;
import static org.ow2.chameleon.rose.RoseMachine.ENDPOINT_LISTENER_INTEREST;
import static org.ow2.chameleon.rose.RoseMachine.EndpointListerInterrest.ALL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.packageadmin.ExportedPackage;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.service.remoteserviceadmin.EndpointDescription;
import org.osgi.service.remoteserviceadmin.EndpointListener;
import org.osgi.service.remoteserviceadmin.RemoteConstants;
import org.ow2.chameleon.rose.ExporterService;
import org.ow2.chameleon.rose.ImporterService;
import org.ow2.chameleon.rose.RoseMachine;
import org.ow2.chameleon.rose.RoseMachine.EndpointListerInterrest;
/**
* This class contains some useful static methods.
*
* @author barjo
*/
public final class RoseTools {
/**
* Get the endpoint id from the {@link ServiceReference}. If the name
* property if not set, use the {@link RemoteConstants#ENDPOINT_ID} property
* or the {@link Constants#SERVICE_PID} or the {@link Constants#SERVICE_ID}
* + <code>service</code> as a prefix.
*
* @param sref
* @param configs
* @return {@link String} the endpoint id.
*/
public static String computeEndpointId(final ServiceReference sref,
final List<String> configs) {
Object name = sref.getProperty(ENDPOINT_ID);
// get the endpoint name from the given name properties
int i = 0;
while (name == null & configs != null && i < configs.size()) {
name = sref.getProperty(configs.get(i++) + ENDPOINT_ID);
}
// try with instance.name
if (name == null) {
name = sref.getProperty("instance.name");
}
// try with service.pid
if (name == null) {
name = sref.getProperty(SERVICE_PID);
}
// try with service.id
if (name == null) {
name = "service" + String.valueOf(sref.getProperty(SERVICE_ID));
}
return String.valueOf(name);
}
/**
* Compute some {@link EndpointDescription} extra properties from
* <code>sref</code>, <code>extraProps</code> and <code>configPrefix</code>.
*
* @param sref
* @param extraProps
* @param configPrefix
* Configuration prefix (e.g. <code>jsonrpc,org.jabsorb</code>
* @return {@link Map} containing the extra properties.
*/
public static Map<String, Object> computeEndpointExtraProperties(
ServiceReference sref, Map<String, Object> extraProps,
List<String> configPrefix, String machineId) {
Map<String, Object> properties = new HashMap<String, Object>();
if (extraProps != null) { // Add given properties
properties.putAll(extraProps);
}
// Set the SERVICE_IMPORTED_CONFIGS property
properties.put(SERVICE_IMPORTED_CONFIGS, configPrefix);
// Set the ENDPOINT_ID property
properties.put(ENDPOINT_ID, computeEndpointId(sref, configPrefix));
// Set the Framework uuid
properties.put(ENDPOINT_FRAMEWORK_UUID, machineId);
return properties;
}
/**
* Return a {@link Dictionary} representation of the
* {@link EndpointDescription}.
*
* @param enddesc
* @return a {@link Dictionary} representation of the
* {@link EndpointDescription}.
*/
public static Dictionary<String, Object> endDescToDico(
EndpointDescription enddesc) {
return new Hashtable<String, Object>(enddesc.getProperties());
}
public static EndpointListerInterrest getEndpointListenerInterrest(
ServiceReference reference) {
Object ointerrest = reference.getProperty(ENDPOINT_LISTENER_INTEREST);
EndpointListerInterrest interrest = null;
// Parse the ENDPOINT_LISTENER_INTERRET property
if (ointerrest instanceof EndpointListerInterrest) {
interrest = (EndpointListerInterrest) ointerrest;
} else if (ointerrest instanceof String) {
interrest = EndpointListerInterrest.valueOf((String) ointerrest);
} else if (ointerrest == null) {
interrest = ALL;
} else {
throw new IllegalArgumentException(
"The ENDPOINT_LISTENER_INTEREST property is neither an EndpointListerInterrest or a String object.");
}
return interrest;
}
/**
* @param context
* {@link BundleContext}
* @return A Snapshot of All {@link ExporterService} available within this
* Machine.
*/
public static List<ExporterService> getAllExporter(BundleContext context) {
try {
return getAllExporter(context, "(" + ENDPOINT_CONFIG_PREFIX + "=*)");
} catch (InvalidSyntaxException e) {
assert false; // What would Dr. Gordon Freeman do ?
}
return emptyList();
}
/**
* @param context
* {@link BundleContext}
* @param filter
* @return A Snapshot of All {@link ExporterService} available within this
* Machine which match <code>filter</code>.
* @throws InvalidSyntaxException
* if <code>filter</code> is not valid.
*/
public static List<ExporterService> getAllExporter(BundleContext context,
String filter) throws InvalidSyntaxException {
List<ExporterService> exporters = new ArrayList<ExporterService>();
ServiceReference[] srefs = context.getAllServiceReferences(
ExporterService.class.getName(), filter);
for (ServiceReference sref : srefs) {
exporters.add((ExporterService) context.getService(sref));
context.ungetService(sref);
}
return exporters;
}
/**
* @param context
* {@link BundleContext}
* @return A Snapshot of All {@link ImporterService} available within this
* Machine.
*/
public static List<ImporterService> getAllImporter(BundleContext context) {
try {
return getAllImporter(context, "("
+ ImporterService.ENDPOINT_CONFIG_PREFIX + "=*)");
} catch (InvalidSyntaxException e) {
assert false; // What would Dr. Gordon Freeman do ?
}
return emptyList();
}
/**
* @param context
* {@link BundleContext}
* @param filter
* @return A Snapshot of All {@link ImporterService} available within this
* Machine which match <code>filter</code>.
* @throws InvalidSyntaxException
* if <code>filter</code> is not valid.
*/
public static List<ImporterService> getAllImporter(BundleContext context,
String filter) throws InvalidSyntaxException {
List<ImporterService> importers = new ArrayList<ImporterService>();
ServiceReference[] srefs = context.getAllServiceReferences(
ImporterService.class.getName(), filter);
for (ServiceReference sref : srefs) {
importers.add((ImporterService) context.getService(sref));
context.ungetService(sref);
}
return importers;
}
public static ServiceRegistration registerProxy(BundleContext context,
Object proxy, EndpointDescription description,
Map<String, Object> properties) {
Hashtable<String, Object> props = new Hashtable<String, Object>();
if (properties != null){
props.putAll(properties);
}
props.putAll(description.getProperties());
return context.registerService((String[]) description.getInterfaces()
.toArray(), proxy, props);
}
/**
* Try to load the {@link EndpointDescription} interfaces from the
* {@link PackageAdmin} of the gateway.
*
* FIXME throw exception rather than returning null
*
* @param context
* The {@link BundleContext} from which we get the
* {@link PackageAdmin}
* @param description
* The {@link EndpointDescription}
* @return null if all specified interfaces cannot be load or the interface
* {@link List}.
*/
public static List<Class<?>> loadClass(BundleContext context,
EndpointDescription description) {
ServiceReference sref = context.getServiceReference(PackageAdmin.class
.getName());
List<String> interfaces = description.getInterfaces();
List<Class<?>> klass = new ArrayList<Class<?>>(interfaces.size());
if (sref == null) { // no package admin !
return null;
}
PackageAdmin padmin = (PackageAdmin) context.getService(sref);
context.ungetService(sref);
for (int i = 0; i < interfaces.size(); i++) {
String itf = interfaces.get(i);
String pname = itf.substring(0, itf.lastIndexOf(".")); // extract package name
ExportedPackage pkg = padmin.getExportedPackage(pname);
try {
if (pkg.getVersion().compareTo(
description.getPackageVersion(pname)) >= 0) {
klass.add(pkg.getExportingBundle().loadClass(itf));
}
} catch (ClassNotFoundException e) {
continue;// XXX return null or continue
}
}
if (klass.isEmpty() || klass.size() < interfaces.size()) {
return null;
}
return klass;
}
/**
* Subtracts all elements in the second list from the first list,
* placing the results in a new list.
* <p>
* This differs from {@link List#removeAll(Collection)} in that
* cardinality is respected; if <Code>list1</Code> contains two
* occurrences of <Code>null</Code> and <Code>list2</Code> only
* contains one occurrence, then the returned list will still contain
* one occurrence.
*
* @param list1 the list to subtract from
* @param list2 the list to subtract
* @return a new list containing the results
* @throws NullPointerException if either list is null
*/
public static <T> List<T> listSubtract(final List<T> list1, final List<T> list2) {
final List<T> result = new ArrayList<T>(list1);
result.removeAll(list2);
return result;
}
} |
package org.xwiki.rendering.internal.parser.pygments;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.annotation.Requirement;
import org.xwiki.configuration.ConfigurationSource;
/**
* All configuration options for the Pygments based highlight parser macro.
*
* @version $Id$
* @since 2.0M1
*/
@Component
public class DefaultPygmentsParserConfiguration implements PygmentsParserConfiguration
{
/**
* Prefix for configuration keys for the Velocity Macro module.
*/
private static final String PREFIX = "rendering.macro.code.pygments.";
/**
* Defines from where to read the Pygments configuration data.
*/
@Requirement
private ConfigurationSource configuration;
/**
* {@inheritDoc}
*
* @see PygmentsParserConfiguration#getFilter()
*/
public String getStyle()
{
return this.configuration.getProperty(PREFIX + "style", String.class);
}
} |
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.util.Arrays;
import static org.junit.Assert.assertArrayEquals;
class BaseConverterTest {
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
public void testSingleBitOneToDecimal() {
final BaseConverter baseConverter = new BaseConverter(2, new int[]{1});
final int[] expectedDigits = new int[]{1};
final int[] actualDigits = baseConverter.convertToBase(10);
assertArrayEquals(
String.format(
"Expected digits: %s but found digits: %s",
Arrays.toString(expectedDigits),
Arrays.toString(actualDigits)),
expectedDigits,
actualDigits);
}
@Ignore("Remove to run test")
@Test
public void testBinaryToSingleDecimal() {
final BaseConverter baseConverter = new BaseConverter(2, new int[]{1, 0, 1});
final int[] expectedDigits = new int[]{5};
final int[] actualDigits = baseConverter.convertToBase(10);
assertArrayEquals(
String.format(
"Expected digits: %s but found digits: %s",
Arrays.toString(expectedDigits),
Arrays.toString(actualDigits)),
expectedDigits,
actualDigits);
}
@Ignore("Remove to run test")
@Test
public void testSingleDecimalToBinary() {
final BaseConverter baseConverter = new BaseConverter(10, new int[]{5});
final int[] expectedDigits = new int[]{1, 0, 1};
final int[] actualDigits = baseConverter.convertToBase(2);
assertArrayEquals(
String.format(
"Expected digits: %s but found digits: %s",
Arrays.toString(expectedDigits),
Arrays.toString(actualDigits)),
expectedDigits,
actualDigits);
}
@Ignore("Remove to run test")
@Test
public void testBinaryToMultipleDecimal() {
final BaseConverter baseConverter = new BaseConverter(2, new int[]{1, 0, 1, 0, 1, 0});
final int[] expectedDigits = new int[]{4, 2};
final int[] actualDigits = baseConverter.convertToBase(10);
assertArrayEquals(
String.format(
"Expected digits: %s but found digits: %s",
Arrays.toString(expectedDigits),
Arrays.toString(actualDigits)),
expectedDigits,
actualDigits);
}
@Ignore("Remove to run test")
@Test
public void testDecimalToBinary() {
final BaseConverter baseConverter = new BaseConverter(10, new int[]{4, 2});
final int[] expectedDigits = new int[]{1, 0, 1, 0, 1, 0};
final int[] actualDigits = baseConverter.convertToBase(2);
assertArrayEquals(
String.format(
"Expected digits: %s but found digits: %s",
Arrays.toString(expectedDigits),
Arrays.toString(actualDigits)),
expectedDigits,
actualDigits);
}
@Ignore("Remove to run test")
@Test
public void testTrinaryToHexadecimal() {
final BaseConverter baseConverter = new BaseConverter(3, new int[]{1, 1, 2, 0});
final int[] expectedDigits = new int[]{2, 10};
final int[] actualDigits = baseConverter.convertToBase(16);
assertArrayEquals(
String.format(
"Expected digits: %s but found digits: %s",
Arrays.toString(expectedDigits),
Arrays.toString(actualDigits)),
expectedDigits,
actualDigits);
}
@Ignore("Remove to run test")
@Test
public void testHexadecimalToTrinary() {
final BaseConverter baseConverter = new BaseConverter(16, new int[]{2, 10});
final int[] expectedDigits = new int[]{1, 1, 2, 0};
final int[] actualDigits = baseConverter.convertToBase(3);
assertArrayEquals(
String.format(
"Expected digits: %s but found digits: %s",
Arrays.toString(expectedDigits),
Arrays.toString(actualDigits)),
expectedDigits,
actualDigits);
}
@Ignore("Remove to run test")
@Test
public void test15BitInteger() {
final BaseConverter baseConverter = new BaseConverter(97, new int[]{3, 46, 60});
final int[] expectedDigits = new int[]{6, 10, 45};
final int[] actualDigits = baseConverter.convertToBase(73);
assertArrayEquals(
String.format(
"Expected digits: %s but found digits: %s",
Arrays.toString(expectedDigits),
Arrays.toString(actualDigits)),
expectedDigits,
actualDigits);
}
@Ignore("Remove to run test")
@Test
public void testEmptyDigits() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("You must supply at least one digit.");
new BaseConverter(2, new int[]{});
}
@Ignore("Remove to run test")
@Test
public void testSingleZero() {
final BaseConverter baseConverter = new BaseConverter(10, new int[]{0});
final int[] expectedDigits = new int[]{0};
final int[] actualDigits = baseConverter.convertToBase(2);
assertArrayEquals(
String.format(
"Expected digits: %s but found digits: %s",
Arrays.toString(expectedDigits),
Arrays.toString(actualDigits)),
expectedDigits,
actualDigits);
}
@Ignore("Remove to run test")
@Test
public void testMultipleZeros() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Digits may not contain leading zeros.");
new BaseConverter(10, new int[]{0, 0, 0});
}
@Ignore("Remove to run test")
@Test
public void testLeadingZeros() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Digits may not contain leading zeros.");
new BaseConverter(7, new int[]{0, 6, 0});
}
@Ignore("Remove to run test")
@Test
public void testNegativeDigit() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Digits may not be negative.");
new BaseConverter(2, new int[]{1, -1, 1, 0, 1, 0});
}
@Ignore("Remove to run test")
@Test
public void testInvalidPositiveDigit() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("All digits must be strictly less than the base.");
new BaseConverter(2, new int[]{1, 2, 1, 0, 1, 0});
}
@Ignore("Remove to run test")
@Test
public void testFirstBaseIsOne() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Bases must be at least 2.");
new BaseConverter(1, new int[]{});
}
@Ignore("Remove to run test")
@Test
public void testSecondBaseIsOne() {
final BaseConverter baseConverter = new BaseConverter(2, new int[]{1, 0, 1, 0, 1, 0});
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Bases must be at least 2.");
baseConverter.convertToBase(1);
}
@Ignore("Remove to run test")
@Test
public void testFirstBaseIsZero() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Bases must be at least 2.");
new BaseConverter(0, new int[]{});
}
@Ignore("Remove to run test")
@Test
public void testSecondBaseIsZero() {
final BaseConverter baseConverter = new BaseConverter(2, new int[]{1, 0, 1, 0, 1, 0});
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Bases must be at least 2.");
baseConverter.convertToBase(0);
}
@Ignore("Remove to run test")
@Test
public void testFirstBaseIsNegative() {
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Bases must be at least 2.");
new BaseConverter(-2, new int[]{});
}
@Ignore("Remove to run test")
@Test
public void testSecondBaseIsNegative() {
final BaseConverter baseConverter = new BaseConverter(2, new int[]{1});
expectedException.expect(IllegalArgumentException.class);
expectedException.expectMessage("Bases must be at least 2.");
baseConverter.convertToBase(-7);
}
} |
package codeine.servlet;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import codeine.permissions.IUserWithPermissions;
import codeine.utils.ExceptionUtils;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Lists;
public class ManageStatisticsCollector {
Cache<String, String> usersInfo = CacheBuilder.newBuilder().maximumSize(20).build();
Cache<String, UrlInfo> urlsInfo = CacheBuilder.newBuilder().maximumSize(20).build();
public synchronized ManageStatisticsInfo getCollected() {
List<UrlInfo> urls = Lists.newArrayList(urlsInfo.asMap().values());
Comparator<UrlInfo> c = new Comparator<ManageStatisticsCollector.UrlInfo>() {
@Override
public int compare(UrlInfo o1, UrlInfo o2) {
return o1.hitCount == o2.hitCount ? o1.path.compareTo(o2.path) : Integer.compare(o1.hitCount, o2.hitCount);
}
};
Collections.sort(urls, c);
return new ManageStatisticsInfo(usersInfo.asMap().keySet(), urls);
}
public synchronized void userAccess(IUserWithPermissions user, final String pathInfo) {
usersInfo.put(user.user().username(), user.user().username());
Callable<UrlInfo> callable = new Callable<ManageStatisticsCollector.UrlInfo>() {
@Override
public UrlInfo call() throws Exception {
return new UrlInfo(pathInfo);
}
};
try {
UrlInfo urlInfo = urlsInfo.get(pathInfo, callable);
urlInfo.hitCount++;
} catch (ExecutionException e) {
throw ExceptionUtils.asUnchecked(e);
}
}
public static class UrlInfo {
public UrlInfo(String pathInfo) {
path = pathInfo;
}
private String path;
private int hitCount;
}
} |
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class RectangleCounterTest {
private RectangleCounter rectangleCounter;
@Before
public void setUp() {
rectangleCounter = new RectangleCounter();
}
@Test
public void testInputWithNoColumnsContainsNoRectangles() {
String[] inputGrid = new String[]{};
assertEquals(0, rectangleCounter.countRectangles(inputGrid));
}
@Ignore
@Test
public void testNonTrivialInputWithNoRectangles() {
String[] inputGrid = new String[]{" "};
assertEquals(0, rectangleCounter.countRectangles(inputGrid));
}
@Ignore
@Test
public void testInputWithOneRectangle() {
String[] inputGrid = new String[]{
"+-+",
"| |",
"+-+"
};
assertEquals(1, rectangleCounter.countRectangles(inputGrid));
}
@Ignore
@Test
public void testInputWithTwoRectanglesWithoutSharedEdges() {
String[] inputGrid = new String[]{
" +-+",
" | |",
"+-+-+",
"| | ",
"+-+ "
};
assertEquals(2, rectangleCounter.countRectangles(inputGrid));
}
@Ignore
@Test
public void testInputWithFiveRectanglesWithSharedEdges() {
String[] inputGrid = new String[]{
" +-+",
" | |",
"+-+-+",
"| | |",
"+-+-+"
};
assertEquals(5, rectangleCounter.countRectangles(inputGrid));
}
@Ignore
@Test
public void testThatRectangleOfHeightOneIsCounted() {
String[] inputGrid = new String[]{
"+
"+
};
assertEquals(1, rectangleCounter.countRectangles(inputGrid));
}
@Ignore
@Test
public void testThatRectangleOfWidthOneIsCounted() {
String[] inputGrid = new String[]{
"++",
"||",
"++"
};
assertEquals(1, rectangleCounter.countRectangles(inputGrid));
}
@Ignore
@Test
public void testThatOneByOneSquareIsCounted() {
String[] inputGrid = new String[]{
"++",
"++"
};
assertEquals(1, rectangleCounter.countRectangles(inputGrid));
}
@Ignore
@Test
public void testThatIncompleteRectanglesAreNotCounted() {
String[] inputGrid = new String[]{
" +-+",
" |",
"+-+-+",
"| | -",
"+-+-+"
};
assertEquals(1, rectangleCounter.countRectangles(inputGrid));
}
@Ignore
@Test
public void testThatRectanglesOfDifferentSizesAreAllCounted() {
String[] inputGrid = new String[]{
"+
"| | |",
"+
"| | |",
"+
};
assertEquals(3, rectangleCounter.countRectangles(inputGrid));
}
@Ignore
@Test
public void testThatIntersectionsWithoutCornerCharacterDoNotCountAsRectangleCorners() {
String[] inputGrid = new String[]{
"+
"| | |",
"+
"| | |",
"+
};
assertEquals(2, rectangleCounter.countRectangles(inputGrid));
}
@Ignore
@Test
public void testLargeInputWithManyRectangles() {
String[] inputGrid = new String[]{
"+
"| +
"+
"| +
"+
"+
"+
" +-+"
};
assertEquals(60, rectangleCounter.countRectangles(inputGrid));
}
} |
package integration;
import org.junit.Before;
import org.junit.Test;
import static com.codeborne.selenide.Condition.text;
import static com.codeborne.selenide.Selenide.$;
public class HoverTest extends IntegrationTest {
@Before
public void openTestPageWithJQuery() {
openFile("page_with_jquery.html");
}
@Test
public void canEmulateHover() {
$("#hoverable").shouldHave(text("It's not hover"));
$("#hoverable").hover();
$("#hoverable").shouldHave(text("It's hover"));
$("h1").hover();
$("#hoverable").shouldHave(text("It's not hover"));
}
} |
package com.jomofisher.cmakeify;
import com.jomofisher.cmakeify.CMakeify.OSType;
import com.jomofisher.cmakeify.model.*;
import java.io.*;
import java.util.*;
public class BashScriptBuilder extends ScriptBuilder {
final private static String ABORT_LAST_FAILED = "rc=$?; if [[ $rc != 0 ]]; then exit $rc; fi";
final private static String TOOLS_FOLDER = ".cmakeify/tools";
final private static String DOWNLOADS_FOLDER = ".cmakeify/downloads";
final private StringBuilder body = new StringBuilder();
final private Map<String, String> zips = new HashMap<>();
final private OSType hostOS;
final private File workingFolder;
final private File rootBuildFolder;
final private File zipsFolder;
final private File cdepFile;
final private File androidFolder;
final private String targetGroupId;
final private String targetArtifactId;
final private String targetVersion;
final private Set<File> outputLocations = new HashSet<>();
final private PrintStream out;
final private OS specificTargetOS;
BashScriptBuilder(PrintStream out,
OSType hostOS,
File workingFolder,
String targetGroupId,
String targetArtifactId,
String targetVersion,
OS specificTargetOS) {
this.out = out;
this.hostOS = hostOS;
this.workingFolder = workingFolder;
this.rootBuildFolder = new File(workingFolder, "build");
this.zipsFolder = new File(rootBuildFolder, "zips");
if (specificTargetOS == null) {
this.cdepFile = new File(zipsFolder, "cdep-manifest.yml");
} else {
this.cdepFile = new File(zipsFolder, String.format("cdep-manifest-%s.yml", specificTargetOS));
}
this.androidFolder = new File(rootBuildFolder, "Android");
this.targetGroupId = targetGroupId;
this.targetArtifactId = targetArtifactId;
this.targetVersion = targetVersion;
this.specificTargetOS = specificTargetOS;
}
private BashScriptBuilder body(String format, Object... args) {
String write = String.format(format + "\n", args);
if (write.contains(">")) {
throw new RuntimeException(write);
}
if (write.contains("<")) {
throw new RuntimeException(write);
}
if (write.contains("&")) {
throw new RuntimeException(write);
}
body.append(write);
return this;
}
private BashScriptBuilder bodyWithRedirect(String format, Object... args) {
String write = String.format(format + "\n", args);
if (!write.contains(">")) {
throw new RuntimeException(write);
}
if (write.contains("<")) {
throw new RuntimeException(write);
}
body.append(write);
return this;
}
private BashScriptBuilder cdep(String format, Object... args) {
String embed = String.format(format, args);
body.append(String.format("printf \"%%s\\r\\n\" \"%s\" >> %s \n", embed, cdepFile));
return this;
}
private void recordOutputLocation(File folder) {
out.printf("Writing to %s\n", folder);
if (this.outputLocations.contains(folder)) {
throw new RuntimeException(String.format("Output location %s written twice", folder));
}
try {
File canonical = folder.getCanonicalFile();
if (this.outputLocations.contains(canonical)) {
throw new RuntimeException(String.format("Output location %s written twice", folder));
}
this.outputLocations.add(folder);
this.outputLocations.add(canonical);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
ScriptBuilder createEmptyBuildFolder(HardNameDependency dependencies[]) {
body("rm -rf %s", rootBuildFolder);
body("mkdir -p %s", zipsFolder);
body("mkdir -p %s/", TOOLS_FOLDER);
body("mkdir -p %s/", DOWNLOADS_FOLDER);
cdep("# Generated by CMakeify");
cdep("coordinate:");
cdep(" groupId: %s", targetGroupId);
cdep(" artifactId: %s", targetArtifactId);
cdep(" version: %s", targetVersion);
if (dependencies != null && dependencies.length > 0) {
cdep("dependencies:");
for (HardNameDependency dependency : dependencies) {
cdep(" - compile: %s", dependency.compile);
cdep(" sha256: %s", dependency.sha256);
}
}
return this;
}
private ArchiveUrl getHostArchive(RemoteArchive remote) {
switch (hostOS) {
case Linux:
return remote.linux;
case MacOS:
return remote.darwin;
}
throw new RuntimeException(hostOS.toString());
}
@Override
ScriptBuilder download(RemoteArchive remote) {
ArchiveInfo archive = new ArchiveInfo(getHostArchive(remote));
return bodyWithRedirect(archive.downloadToFolder(DOWNLOADS_FOLDER)).bodyWithRedirect(archive.uncompressToFolder(
DOWNLOADS_FOLDER,
TOOLS_FOLDER));
}
@Override
File writeToShellScript() {
BufferedWriter writer = null;
File file = new File(".cmakeify/build.sh");
file.getAbsoluteFile().mkdirs();
file.delete();
try {
writer = new BufferedWriter(new FileWriter(file));
writer.write(body.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
}
return file;
}
@Override
ScriptBuilder checkForCompilers(Collection<String> compilers) {
for (String compiler : compilers) {
body("if [[ -z \"$(which %s)\" ]]; then", compiler);
body(" echo CMAKEIFY ERROR: Missing %s. Please install.", compiler);
body(" exit 110");
body("fi");
}
return this;
}
@Override
ScriptBuilder cmakeAndroid(String cmakeVersion,
RemoteArchive cmakeRemote,
String target,
String cmakeFlags,
String flavor,
String flavorFlags,
String ndkVersion,
RemoteArchive ndkRemote,
String includes[],
String lib,
String compiler,
String runtime,
String platform,
String abi,
boolean multipleFlavors,
boolean multipleCMake,
boolean multipleNDK,
boolean multipleCompiler,
boolean multipleRuntime,
boolean multiplePlatforms,
boolean multipleAbi) {
body("echo Executing script for %s %s %s %s %s %s %s", flavor, ndkVersion, platform, compiler, runtime, target, abi);
if (lib != null && lib.length() > 0) {
throw new RuntimeException("lib is no longer supported, use buildTarget");
}
if (target != null && target.length() > 0 && lib != null && lib.length() > 0) {
throw new RuntimeException("cmakify.yml has both lib and target, only one is allowed");
}
if (target != null && target.length() > 0 && (lib == null || lib.length() == 0)) {
lib = String.format("lib%s.a", target);
}
if (cmakeFlags == null) {
cmakeFlags = "";
}
String cmakeExe = String.format("%s/%s/bin/cmake", TOOLS_FOLDER, getHostArchive(cmakeRemote).unpackroot);
File outputFolder = androidFolder;
String zipName = targetArtifactId + "-android";
if (multipleCMake) {
outputFolder = new File(outputFolder, "cmake-" + cmakeVersion);
zipName += "-cmake-" + cmakeVersion;
}
if (multipleNDK) {
outputFolder = new File(outputFolder, ndkVersion);
zipName += "-" + ndkVersion;
}
if (multipleCompiler) {
outputFolder = new File(outputFolder, compiler);
zipName += "-" + compiler;
}
if (multipleRuntime) {
String fixedRuntime = runtime.replace('+', 'x');
outputFolder = new File(outputFolder, fixedRuntime);
zipName += "-" + fixedRuntime;
}
if (multiplePlatforms) {
outputFolder = new File(outputFolder, "android-" + platform);
zipName += "-platform-" + platform;
}
if (multipleFlavors) {
outputFolder = new File(outputFolder, "flavor-" + flavor);
zipName += "-" + flavor;
}
if (multipleAbi) {
outputFolder = new File(outputFolder, "abi-" + abi);
zipName += "-" + abi;
}
zipName += ".zip";
File zip = new File(zipsFolder, zipName).getAbsoluteFile();
File headers = new File(zipsFolder, "headers.zip").getAbsoluteFile();
recordOutputLocation(zip);
File buildFolder = new File(outputFolder, "cmake-generated-files");
String ndkFolder = String.format("%s/%s", TOOLS_FOLDER, getHostArchive(ndkRemote).unpackroot);
File redistFolder = new File(outputFolder, "redist").getAbsoluteFile();
File headerFolder = new File(outputFolder, "header").getAbsoluteFile();
File stagingFolder = new File(outputFolder, "staging").getAbsoluteFile();
File abiBuildFolder = new File(buildFolder, abi);
File archFolder = new File(String.format("%s/platforms/android-%s/arch-%s",
new File(ndkFolder).getAbsolutePath(),
platform,
Abi.getByName(abi).getArchitecture()));
body("if [ -d '%s' ]; then", archFolder);
body(" echo Creating make project in %s", abiBuildFolder);
File stagingAbiFolder = new File(String.format("%s/lib/%s", stagingFolder, abi));
recordOutputLocation(stagingAbiFolder);
String command = String.format("%s \\\n" +
" -H%s \\\n" +
" -B%s \\\n" +
" -DCMAKE_ANDROID_NDK_TOOLCHAIN_VERSION=%s \\\n" +
" -DCMAKE_ANDROID_NDK_TOOLCHAIN_DEBUG=1 \\\n" +
" -DCMAKE_SYSTEM_NAME=Android \\\n" +
" -DCMAKE_SYSTEM_VERSION=%s \\\n" +
" -DCMAKEIFY_REDIST_INCLUDE_DIRECTORY=%s/include \\\n" +
" -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=%s \\\n" +
" -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=%s \\\n" +
" -DCMAKE_ANDROID_STL_TYPE=%s_static \\\n" +
" -DCMAKE_ANDROID_NDK=%s \\\n" +
" -DCMAKE_ANDROID_ARCH_ABI=%s %s %s\n",
cmakeExe,
workingFolder,
abiBuildFolder,
compiler,
platform,
headerFolder,
stagingAbiFolder,
stagingAbiFolder,
runtime,
new File(ndkFolder).getAbsolutePath(),
abi,
flavorFlags,
cmakeFlags);
body(" echo Executing %s", command);
body(" " + command);
body(" " + ABORT_LAST_FAILED);
if (target != null && target.length() > 0) {
body(String.format(" %s --build %s --target %s -- -j8", cmakeExe, abiBuildFolder, target));
} else {
body(String.format(" %s --build %s -- -j8", cmakeExe, abiBuildFolder));
}
body(" " + ABORT_LAST_FAILED);
String stagingLib = String.format("%s/%s", stagingAbiFolder, lib);
File redistAbiFolder = new File(String.format("%s/lib/%s", redistFolder, abi));
recordOutputLocation(redistAbiFolder);
if (lib != null && lib.length() > 0) {
body(" if [ -f '%s' ]; then", stagingLib);
body(" mkdir -p %s", redistAbiFolder);
body(" cp %s %s/%s", stagingLib, redistAbiFolder, lib);
body(" " + ABORT_LAST_FAILED);
body(" else");
body(" echo CMAKEIFY ERROR: CMake build did not produce %s", stagingLib);
body(" exit 100");
body(" fi");
} else {
body(" echo cmakeify.yml did not specify lib or target. No output library expected.");
}
body("else");
body(" echo Build skipped ABI %s because arch folder didnt exist: %s", abi, archFolder);
body("fi");
zips.put(zip.getAbsolutePath(), redistFolder.getPath());
body("if [ -d '%s' ]; then", stagingFolder);
// Create a folder with something in it so there'e always something to zip
body(" mkdir -p %s", redistFolder);
bodyWithRedirect(" echo Android %s %s %s %s %s %s > %s/cmakeify.txt",
cmakeVersion,
flavor,
ndkVersion,
platform,
compiler,
runtime,
redistFolder);
writeExtraIncludesToBody(includes, headerFolder);
writeCreateZipFromRedistFolderToBody(zip, redistFolder);
body(" if [ -d '%s' ]; then", headerFolder);
writeCreateZipFromRedistFolderToBody(headers, headerFolder);
body(" fi", headerFolder);
writeZipFileStatisticsToBody(zip);
cdep(" - lib: %s", lib);
cdep(" file: %s", zip.getName());
cdep(" sha256: $SHASUM256");
cdep(" size: $ARCHIVESIZE");
if (multipleFlavors) {
cdep(" flavor: %s", flavor);
}
cdep(" runtime: %s", runtime);
cdep(" platform: %s", platform);
cdep(" ndk: %s", ndkVersion);
cdep(" abi: %s", abi);
if (multipleCompiler) {
cdep(" compiler: %s", compiler);
}
if (multipleCMake) {
cdep(" builder: cmake-%s", cmakeVersion);
}
body("fi");
return this;
}
private void writeZipFileStatisticsToBody(File zip) {
body(" SHASUM256=$(shasum -a 256 %s | awk '{print $1}')", zip);
body(" " + ABORT_LAST_FAILED);
body(" ARCHIVESIZE=$(ls -l %s | awk '{print $5}')", zip);
body(" " + ABORT_LAST_FAILED);
}
@Override
ScriptBuilder cmakeLinux(String cmakeVersion,
RemoteArchive cmakeRemote,
String target,
String cmakeFlags,
Toolset toolset,
String lib,
boolean multipleCMake,
boolean multipleCompiler) {
if (target != null && target.length() > 0 && lib != null && lib.length() > 0) {
throw new RuntimeException("cmakify.yml has both lib and target, only one is allowed");
}
if (target != null && target.length() > 0 && (lib == null || lib.length() == 0)) {
lib = String.format("lib%s.a", target);
}
if (cmakeFlags == null) {
cmakeFlags = "";
}
String cmakeExe = String.format("%s/%s/bin/cmake", TOOLS_FOLDER, getHostArchive(cmakeRemote).unpackroot);
File outputFolder = new File(rootBuildFolder, "Linux");
String zipName = targetArtifactId + "-linux";
if (multipleCMake) {
outputFolder = new File(outputFolder, "cmake-" + cmakeVersion);
zipName += "-cmake-" + cmakeVersion;
}
if (multipleCompiler) {
outputFolder = new File(outputFolder, toolset.c);
zipName += "-" + toolset.c;
}
zipName += ".zip";
File zip = new File(zipsFolder, zipName).getAbsoluteFile();
File headers = new File(zipsFolder, "headers.zip").getAbsoluteFile();
File buildFolder = new File(outputFolder, "cmake-generated-files");
File headerFolder = new File(outputFolder, "header").getAbsoluteFile();
File redistFolder = new File(outputFolder, "redist").getAbsoluteFile();
body("echo Building to %s", outputFolder);
body("mkdir -p %s/include", redistFolder);
recordOutputLocation(zip);
recordOutputLocation(outputFolder);
recordOutputLocation(redistFolder);
body(String.format("%s \\\n" +
" -H%s \\\n" +
" -B%s \\\n" +
" -DCMAKEIFY_REDIST_INCLUDE_DIRECTORY=%s/include \\\n" +
" -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=%s/lib \\\n" +
" -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=%s/lib \\\n" +
" -DCMAKE_SYSTEM_NAME=Linux \\\n" +
" -DCMAKE_C_COMPILER=%s \\\n" +
" -DCMAKE_CXX_COMPILER=%s %s",
cmakeExe,
workingFolder,
buildFolder,
headerFolder,
redistFolder,
redistFolder,
toolset.c,
toolset.cxx,
cmakeFlags));
if (target != null && target.length() > 0) {
body(String.format("%s --build %s --target %s -- -j8", cmakeExe, buildFolder, target));
} else {
body(String.format("%s --build %s -- -j8", cmakeExe, buildFolder));
}
body(ABORT_LAST_FAILED);
zips.put(zip.getAbsolutePath(), redistFolder.getPath());
body("# Zip Linux redist if folder was created in %s", redistFolder);
body("if [ -d '%s' ]; then", redistFolder);
body(" if [ -f '%s' ]; then", zip);
body(" echo CMAKEIFY ERROR: Linux zip %s would be overwritten", zip);
body(" exit 500");
body(" fi");
writeCreateZipFromRedistFolderToBody(zip, redistFolder);
body(" if [ -d '%s' ]; then", headerFolder);
writeCreateZipFromRedistFolderToBody(headers, headerFolder);
body(" fi", headerFolder);
writeZipFileStatisticsToBody(zip);
body(" " + ABORT_LAST_FAILED);
cdep(" - lib: %s", lib);
cdep(" file: %s", zip.getName());
cdep(" sha256: $SHASUM256");
cdep(" size: $ARCHIVESIZE");
body("else");
body(" echo CMAKEIFY ERROR: Did not create %s", redistFolder);
body(" exit 520");
body("fi");
return this;
}
@Override
ScriptBuilder cmakeiOS(String cmakeVersion,
RemoteArchive cmakeRemote,
String target,
String cmakeFlags,
String flavor,
String flavorFlags,
String includes[],
String lib,
iOSPlatform platform,
iOSArchitecture architecture,
String sdk,
boolean multipleFlavor,
boolean multipleCMake,
boolean multiplePlatform,
boolean multipleArchitecture,
boolean multipleSdk) {
if (target != null && target.length() > 0 && lib != null && lib.length() > 0) {
throw new RuntimeException("cmakify.yml has both lib and target, only one is allowed");
}
if (target != null && target.length() > 0 && (lib == null || lib.length() == 0)) {
lib = String.format("lib%s.a", target);
}
if (cmakeFlags == null) {
cmakeFlags = "";
}
if (!isSupportediOSPlatformArchitecture(platform, architecture)) {
out.printf("Skipping iOS %s %s because it isn't supported by XCode\n", platform, architecture);
return this;
}
String cmakeExe = String.format("%s/%s/bin/cmake", TOOLS_FOLDER, getHostArchive(cmakeRemote).unpackroot);
File outputFolder = new File(rootBuildFolder, "iOS");
String zipName = targetArtifactId + "-ios";
if (multipleCMake) {
outputFolder = new File(outputFolder, "cmake-" + cmakeVersion);
zipName += "-cmake-" + cmakeVersion;
}
if (multipleFlavor) {
outputFolder = new File(outputFolder, "flavor-" + flavor);
zipName += "-" + flavor;
}
if (multiplePlatform) {
outputFolder = new File(outputFolder, "platform-" + platform.toString());
zipName += "-platform-" + platform.toString();
}
if (multipleArchitecture) {
outputFolder = new File(outputFolder, "architecture-" + architecture.toString());
zipName += "-architecture-" + architecture.toString();
}
if (multipleSdk) {
outputFolder = new File(outputFolder, "sdk-" + sdk);
zipName += "-sdk-" + sdk;
}
zipName += ".zip";
File zip = new File(zipsFolder, zipName).getAbsoluteFile();
File headers = new File(zipsFolder, "headers.zip").getAbsoluteFile();
File buildFolder = new File(outputFolder, "cmake-generated-files");
File headerFolder = new File(outputFolder, "header").getAbsoluteFile();
File redistFolder = new File(outputFolder, "redist").getAbsoluteFile();
File stagingFolder = new File(outputFolder, "staging").getAbsoluteFile();
if (hostOS != OSType.MacOS) {
body("echo No XCode available. NOT building to %s", outputFolder);
} else {
body("CDEP_IOS_CLANG=$(xcrun -sdk iphoneos -find clang)");
body("CDEP_IOS_AR=$(xcrun -sdk iphoneos -find ar)");
body("CDEP_XCODE_DEVELOPER_DIR=$(xcode-select -print-path)");
body("CDEP_IOS_DEVELOPER_ROOT=${CDEP_XCODE_DEVELOPER_DIR}/Platforms/%s.platform/Developer", platform);
body("CDEP_IOS_SDK_ROOT=${CDEP_IOS_DEVELOPER_ROOT}/SDKs/%s%s.sdk", platform, sdk);
body("if [ ! -d \"${CDEP_IOS_SDK_ROOT}\" ]; then");
body(" echo Not building for non-existent SDK root ${CDEP_IOS_SDK_ROOT}. Listing available:");
body(" ls ${CDEP_IOS_DEVELOPER_ROOT}/SDKs");
body("else");
body(" echo Building to %s", outputFolder);
body(" mkdir -p %s/include", redistFolder);
}
recordOutputLocation(zip);
recordOutputLocation(outputFolder);
recordOutputLocation(redistFolder);
recordOutputLocation(stagingFolder);
String command = String.format("%s \\\n" +
" -H%s \\\n" +
" -B%s \\\n" +
" -DCMAKE_C_COMPILER=${CDEP_IOS_CLANG}\\\n" +
" -DCMAKE_CXX_COMPILER=${CDEP_IOS_CLANG} \\\n" +
" -DCMAKE_C_COMPILER_WORKS=1 \\\n" +
" -DCMAKE_CXX_COMPILER_WORKS=1 \\\n" +
" -DCMAKE_AR=${CDEP_IOS_AR}\\\n" +
" -DCMAKE_OSX_SYSROOT=${CDEP_IOS_SDK_ROOT} \\\n" +
" -DCMAKE_OSX_ARCHITECTURES=%s \\\n" +
" -DCMAKEIFY_REDIST_INCLUDE_DIRECTORY=%s/include \\\n" +
" -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=%s/lib \\\n" +
" -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=%s/lib %s %s \\\n",
cmakeExe,
workingFolder,
buildFolder,
architecture,
headerFolder,
stagingFolder,
stagingFolder,
cmakeFlags,
flavorFlags);
if (hostOS == OSType.MacOS) {
body(" echo Executing %s", command);
body(" " + command);
if (target != null && target.length() > 0) {
body(String.format("echo %s --build %s --target %s -- -j8", cmakeExe, buildFolder, target));
body(String.format("%s --build %s --target %s -- -j8", cmakeExe, buildFolder, target));
} else {
body(String.format("echo %s --build %s -- -j8", cmakeExe, buildFolder));
body(String.format("%s --build %s -- -j8", cmakeExe, buildFolder));
}
body(" " + ABORT_LAST_FAILED);
if (lib != null && lib.length() > 0) {
String stagingLib = String.format("%s/lib/%s", stagingFolder, lib);
body(" if [ -f '%s' ]; then", stagingLib);
body(" mkdir -p %s/lib", redistFolder);
body(" cp %s %s/lib/%s", stagingLib, redistFolder, lib);
body(" " + ABORT_LAST_FAILED);
body(" else");
body(" echo CMAKEIFY ERROR: CMake build did not produce %s", stagingLib);
body(" exit 100");
body(" fi");
}
zips.put(zip.getAbsolutePath(), redistFolder.getPath());
body(" if [ -d '%s' ]; then", stagingFolder);
// Create a folder with something in it so there'e always something to zip
body(" mkdir -p %s", redistFolder);
bodyWithRedirect(" echo iOS %s %s > %s/cmakeify.txt", cmakeVersion, platform, redistFolder);
writeExtraIncludesToBody(includes, headerFolder);
writeCreateZipFromRedistFolderToBody(zip, redistFolder);
body(" if [ -d '%s' ]; then", headerFolder);
writeCreateZipFromRedistFolderToBody(headers, headerFolder);
body(" fi", headerFolder);
writeZipFileStatisticsToBody(zip);
if (lib == null || lib.length() > 0) {
body(" else");
body(" echo CMAKEIFY ERROR: Build did not produce an output in %s", stagingFolder);
body(" exit 200");
}
body(" fi");
// Still create the manifest for what would have been built.
cdep(" - lib: %s", lib);
cdep(" file: %s", zip.getName());
cdep(" sha256: $SHASUM256");
cdep(" size: $ARCHIVESIZE");
if (multipleFlavor) {
cdep(" flavor: %s", flavor);
}
cdep(" platform: %s", platform);
cdep(" architecture: %s", architecture);
cdep(" sdk: %s", sdk);
if (multipleCMake) {
cdep(" builder: cmake-%s", cmakeVersion);
}
body("fi");
}
return this;
}
private boolean isSupportediOSPlatformArchitecture(iOSPlatform platform, iOSArchitecture architecture) {
if (platform.equals(iOSPlatform.iPhoneOS)) {
if (architecture.equals(iOSArchitecture.arm64)) {
return true;
}
if (architecture.equals(iOSArchitecture.armv7)) {
return true;
}
return architecture.equals(iOSArchitecture.armv7s);
}
if (platform.equals(iOSPlatform.iPhoneSimulator)) {
if (architecture.equals(iOSArchitecture.i386)) {
return true;
}
return architecture.equals(iOSArchitecture.x86_64);
}
throw new RuntimeException(platform.toString());
}
private void writeCreateZipFromRedistFolderToBody(File zip, File folder) {
body(" pushd %s", folder);
body(" " + ABORT_LAST_FAILED);
body(" zip %s . -r", zip);
body(" " + ABORT_LAST_FAILED);
body(" if [ -f '%s' ]; then", zip);
body(" echo Zip %s was created", zip);
body(" else");
body(" echo CMAKEIFY ERROR: Zip %s was not created", zip);
body(" exit 402");
body(" fi");
body(" popd");
body(" " + ABORT_LAST_FAILED);
}
private void writeExtraIncludesToBody(String[] includes, File redistFolder) {
if (includes != null) {
for (String include : includes) {
body(" if [ ! -d '%s/%s' ]; then", workingFolder, include);
body(" echo CMAKEIFY ERROR: Extra include folder '%s/%s' does not exist", workingFolder, include);
body(" exit 600");
body(" fi");
body(" pushd %s", workingFolder);
if (include.startsWith("include")) {
body(" echo find %s -name '*.h' {pipe} cpio -pdm %s", include, redistFolder);
body(" find %s -name '*.h' | cpio -pdm %s", include, redistFolder);
body(" echo find %s -name '*.hpp' {pipe} cpio -pdm %s", include, redistFolder);
body(" find %s -name '*.hpp' | cpio -pdm %s", include, redistFolder);
} else {
body(" find %s -name '*.h' | cpio -pdm %s/include", include, redistFolder);
body(" find %s -name '*.hpp' | cpio -pdm %s/include", include, redistFolder);
}
body(" popd");
body(" " + ABORT_LAST_FAILED);
}
}
}
@Override
ScriptBuilder startBuilding(OS target) {
switch (target) {
case android:
cdep("android:");
cdep(" archives:");
return this;
case linux:
cdep("linux:");
cdep(" archives:");
return this;
case windows:
cdep("windows:");
cdep(" archives:");
return this;
case iOS:
cdep("iOS:");
cdep(" archives:");
return this;
}
throw new RuntimeException(target.toString());
}
@Override
ScriptBuilder buildRedistFiles(File workingFolder, String[] includes, String example) {
if (example != null && example.length() > 0) {
cdep("example: |");
String lines[] = example.split("\\r?\\n");
for (String line : lines) {
cdep(" %s", line);
}
}
body("cat %s", cdepFile);
body("echo - %s", new File(cdepFile.getParentFile(), "cdep-manifest.yml"));
for (String zip : zips.keySet()) {
String relativeZip = new File(".").toURI().relativize(new File(zip).toURI()).getPath();
body("if [ -f '%s' ]; then", relativeZip);
body(" echo - %s", relativeZip);
body("fi");
}
return this;
}
@Override
ScriptBuilder deployRedistFiles(
RemoteArchive githubRelease,
OS[] allTargets,
boolean uploadBadges) {
File combinedManifest = new File(cdepFile.getParentFile(), "cdep-manifest.yml");
File headers = new File(cdepFile.getParentFile(), "headers.zip");
if (targetVersion == null || targetVersion.length() == 0 || targetVersion.equals("0.0.0")) {
body("echo Skipping upload because targetVersion='%s' %s", targetVersion, targetVersion.length());
if (!combinedManifest.equals(cdepFile)) {
body("# cdep-manifest.yml tracking: %s to %s", cdepFile, combinedManifest);
body("echo cp %s %s", cdepFile, combinedManifest);
body("cp %s %s", cdepFile, combinedManifest);
body(ABORT_LAST_FAILED);
} else {
body("# cdep-manifest.yml tracking: not copying because it has the same name as combined");
body("echo not copying %s to %s because it was already there", combinedManifest, cdepFile);
body("ls %s", combinedManifest.getParent());
body(ABORT_LAST_FAILED);
}
return this;
}
body("echo Not skipping upload because targetVersion='%s' %s", targetVersion, targetVersion.length());
// Merging manifests from multiple travis runs is a PITA.
// All runs need to upload cdep-manifest-[targetOS].yml.
// The final run needs to figure out that it is the final run and also upload a merged
// cdep-manifest.yml.
// None of this needs to happen if specificTargetOS is null because that means there aren't
// multiple travis runs.
if (specificTargetOS != null) {
assert !cdepFile.toString().endsWith("cdep-manifest.yml");
if (allTargets.length == 1) {
// There is a specificTargetOS specified but it is the only one.
// We can combine the file locally.
body("cp %s %s", cdepFile, combinedManifest);
body(ABORT_LAST_FAILED);
body("if [ -f '%s' ]; then", headers);
body("./cdep merge headers %s %s %s", combinedManifest, headers, combinedManifest);
body(ABORT_LAST_FAILED);
upload(headers, githubRelease);
body(ABORT_LAST_FAILED);
body("fi");
upload(combinedManifest, githubRelease);
body(ABORT_LAST_FAILED);
} else {
// Accumulate a list of all targets to merge except for this one
String otherCoordinates = "";
for (OS os : allTargets) {
if (os != specificTargetOS) {
otherCoordinates += String.format("%s:%s/%s:%s ", targetGroupId, targetArtifactId, os, targetVersion);
}
}
// Now add this file
String coordinates = otherCoordinates + cdepFile.toString();
// Merge any existing manifest with the currently generated one.
body("echo ./cdep merge %s %s", coordinates, combinedManifest);
body("./cdep merge %s %s", coordinates, combinedManifest);
body(ABORT_LAST_FAILED);
// If the merge succeeded, that means we got all of the coordinates.
// We can upload. Also need to fetch any partial dependencies so that
// downstream calls to ./cdep for tests will have assets all ready.
body("if [ -f '%s' ]; then", combinedManifest);
body(" echo Fetching partial dependencies");
body(" echo ./cdep fetch %s", coordinates);
body(" ./cdep fetch %s", coordinates);
body(" " + ABORT_LAST_FAILED);
body(" echo Uploading %s", combinedManifest);
body("if [ -f '%s' ]; then", headers);
body("./cdep merge headers %s %s %s", combinedManifest, headers, combinedManifest);
body(ABORT_LAST_FAILED);
upload(headers, githubRelease);
body(ABORT_LAST_FAILED);
body("fi");
upload(combinedManifest, githubRelease);
body(ABORT_LAST_FAILED);
if (uploadBadges) {
uploadBadges();
}
body("else");
// If the merged failed then we still have to create a combined manifest for test
// purposes but it won't be uploaded.
body(" cp %s %s", cdepFile, combinedManifest);
body(" " + ABORT_LAST_FAILED);
body("fi");
// Upload the uncombined manifest
upload(cdepFile, githubRelease);
}
} else {
// There is not a specificTargetOS so there aren't multiple travis runs.
// Just upload cdep-manifest.yml.
assert cdepFile.toString().endsWith("cdep-manifest.yml");
body("if [ -f '%s' ]; then", headers);
body("./cdep merge headers %s %s %s", cdepFile, headers, cdepFile);
body(ABORT_LAST_FAILED);
upload(headers, githubRelease);
body(ABORT_LAST_FAILED);
body("fi");
upload(cdepFile, githubRelease);
body(ABORT_LAST_FAILED);
if (uploadBadges) {
uploadBadges();
}
}
for (String zip : zips.keySet()) {
String relativeZip = new File(".").toURI().relativize(new File(zip).toURI()).getPath();
body("if [ -f '%s' ]; then", relativeZip);
body(" echo Uploading %s", relativeZip);
upload(new File(relativeZip), githubRelease);
body("fi");
}
return this;
}
private void upload(File file, RemoteArchive githubRelease) {
String user = targetGroupId.substring(targetGroupId.lastIndexOf(".") + 1);
body(" echo %s/%s/github-release upload --user %s --repo %s --tag %s --name %s --file %s",
TOOLS_FOLDER,
getHostArchive(githubRelease).unpackroot,
user,
targetArtifactId,
targetVersion, file.getName(), file.getAbsolutePath());
body(" %s/%s/github-release upload --user %s --repo %s --tag %s --name %s --file %s",
TOOLS_FOLDER,
getHostArchive(githubRelease).unpackroot,
user,
targetArtifactId,
targetVersion, file.getName(), file.getAbsolutePath());
body(ABORT_LAST_FAILED);
}
private ScriptBuilder uploadBadges() {
// Record build information
String badgeUrl = String.format("%s:%s:%s", targetGroupId, targetArtifactId, targetVersion);
badgeUrl = badgeUrl.replace(":", "%3A");
badgeUrl = badgeUrl.replace("-", "
badgeUrl = String.format("https://img.shields.io/badge/cdep-%s-brightgreen.svg", badgeUrl);
String badgeFolder = String.format("%s/%s", targetGroupId, targetArtifactId);
body("if [ -n \"$TRAVIS_TAG\" ]; then");
body(" if [ -n \"$CDEP_BADGES_API_KEY\" ]; then");
body(" echo git clone https://github.com/cdep-io/cdep-io.github.io.git");
body(" git clone https://github.com/cdep-io/cdep-io.github.io.git");
body(" " + ABORT_LAST_FAILED);
body(" pushd cdep-io.github.io");
body(" mkdir -p %s/latest", badgeFolder);
bodyWithRedirect(" echo curl %s > %s/latest/latest.svg ", badgeUrl, badgeFolder);
bodyWithRedirect(" curl %s > %s/latest/latest.svg ", badgeUrl, badgeFolder);
body(" " + ABORT_LAST_FAILED);
body(" echo git add %s/latest/latest.svg", badgeFolder);
body(" git add %s/latest/latest.svg", badgeFolder);
body(" " + ABORT_LAST_FAILED);
body(" echo git -c user.name='cmakeify' -c user.email='cmakeify' commit -m init");
body(" git -c user.name='cmakeify' -c user.email='cmakeify' commit -m init");
body(" " + ABORT_LAST_FAILED);
body(" echo git push -f -q https://cdep-io:$CDEP_BADGES_API_KEY@github.com/cdep-io/cdep-io.github.io");
body(" git push -f -q https://cdep-io:$CDEP_BADGES_API_KEY@github.com/cdep-io/cdep-io.github.io");
body(" " + ABORT_LAST_FAILED);
body(" popd");
body(" else");
body(" echo Add CDEP_BADGES_API_KEY to Travis settings to get badges!");
body(" fi");
body("fi");
return this;
}
@Override
public String toString() {
return body.toString();
}
} |
package org.opendaylight.controller.config.persist.storage.directory.autodetect;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.apache.commons.lang3.StringUtils;
import org.opendaylight.controller.config.persist.storage.directory.DirectoryPersister;
import org.opendaylight.controller.config.persist.storage.file.xml.model.ConfigSnapshot;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
enum FileType {
plaintext, xml;
public static final String XML_STORAGE_FIRST_LINE = "<" + ConfigSnapshot.SNAPSHOT_ROOT_ELEMENT_NAME + ">";
private static final String XML_FILE_DEFINITION_LINE = "<?xml";
static FileType getFileType(File file) {
String firstLine = readFirstLine(file);
if(isPlaintextStorage(firstLine)) {
return plaintext;
} else if(isXmlStorage(firstLine))
return xml;
throw new IllegalArgumentException("File " + file + " is not of permitted storage type: " + Arrays.toString(FileType.values()));
}
private static boolean isXmlStorage(String firstLine) {
boolean isXml = false;
isXml |= firstLine.startsWith(XML_STORAGE_FIRST_LINE);
isXml |= firstLine.startsWith(XML_FILE_DEFINITION_LINE);
return isXml;
}
private static boolean isPlaintextStorage(String firstLine) {
return firstLine.startsWith(DirectoryPersister.MODULES_START);
}
@VisibleForTesting
static String readFirstLine(File file) {
FirstLineReadingProcessor callback = new FirstLineReadingProcessor();
try {
return Files.readLines(file, Charsets.UTF_8, callback);
} catch (IOException e) {
throw new IllegalArgumentException("Unable to detect file type of file " + file, e);
}
}
private static class FirstLineReadingProcessor implements com.google.common.io.LineProcessor<String> {
private String firstNonBlankLine;
@Override
public boolean processLine(String line) throws IOException {
if(isEmptyLine(line)) {
return true;
} else {
firstNonBlankLine = line.trim();
return false;
}
}
private boolean isEmptyLine(String line) {
return StringUtils.isBlank(line);
}
@Override
public String getResult() {
return firstNonBlankLine;
}
}
} |
package javax.time;
import static javax.time.calendrical.ISODateTimeRule.DAY_OF_MONTH;
import static javax.time.calendrical.ISODateTimeRule.HOUR_OF_AMPM;
import static javax.time.calendrical.ISODateTimeRule.HOUR_OF_DAY;
import static javax.time.calendrical.ISODateTimeRule.MINUTE_OF_HOUR;
import static javax.time.calendrical.ISODateTimeRule.YEAR;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
import static org.testng.Assert.assertSame;
import static org.testng.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.time.calendrical.Calendrical;
import javax.time.calendrical.CalendricalRule;
import javax.time.calendrical.Chronology;
import javax.time.calendrical.MockRuleNoValue;
import javax.time.format.TextStyle;
import javax.time.zone.ZoneOffsetInfo;
import javax.time.zone.ZoneOffsetTransition;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
* Test TimeZone.
*
* @author Michael Nascimento Santos
* @author Stephen Colebourne
*/
@Test
public class TestZoneId {
private static final ZoneId ZONE_PARIS = ZoneId.of("Europe/Paris");
public static final String LATEST_TZDB = "2010i";
// Basics
public void test_interfaces() {
Object obj = ZoneId.UTC;
assertTrue(obj instanceof Calendrical);
assertTrue(obj instanceof Serializable);
}
public void test_immutable() {
Class<ZoneId> cls = ZoneId.class;
assertTrue(Modifier.isPublic(cls.getModifiers()));
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
if (Modifier.isStatic(field.getModifiers()) == false) {
assertTrue(Modifier.isPrivate(field.getModifiers()));
assertTrue(Modifier.isFinal(field.getModifiers()) ||
(Modifier.isVolatile(field.getModifiers()) && Modifier.isTransient(field.getModifiers())));
}
}
}
public void test_serialization_UTC() throws Exception {
ZoneId test = ZoneId.UTC;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baos);
out.writeObject(test);
baos.close();
byte[] bytes = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream in = new ObjectInputStream(bais);
ZoneId result = (ZoneId) in.readObject();
assertSame(result, test);
}
public void test_serialization_fixed() throws Exception {
ZoneId test = ZoneId.of("UTC+01:30");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baos);
out.writeObject(test);
baos.close();
byte[] bytes = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream in = new ObjectInputStream(bais);
ZoneId result = (ZoneId) in.readObject();
assertEquals(result, test);
}
public void test_serialization_Europe() throws Exception {
ZoneId test = ZoneId.of("Europe/London");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baos);
out.writeObject(test);
baos.close();
byte[] bytes = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream in = new ObjectInputStream(bais);
ZoneId result = (ZoneId) in.readObject();
assertEquals(result, test);
}
public void test_serialization_America() throws Exception {
ZoneId test = ZoneId.of("America/Chicago");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baos);
out.writeObject(test);
baos.close();
byte[] bytes = baos.toByteArray();
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream in = new ObjectInputStream(bais);
ZoneId result = (ZoneId) in.readObject();
assertEquals(result, test);
}
// UTC
public void test_constant_UTC() {
ZoneId test = ZoneId.UTC;
assertEquals(test.getID(), "UTC");
assertEquals(test.getGroupID(), "");
assertEquals(test.getRegionID(), "UTC");
assertEquals(test.getVersionID(), "");
assertEquals(test.getText(TextStyle.FULL, Locale.UK), "UTC");
assertEquals(test.isFixed(), true);
assertEquals(test.getRules().isFixedOffset(), true);
assertEquals(test.getRules().getOffset(Instant.ofEpochSecond(0L)), ZoneOffset.UTC);
ZoneOffsetInfo info = test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 6, 30));
assertEquals(info.isTransition(), false);
assertEquals(info.getTransition(), null);
assertEquals(info.getOffset(), ZoneOffset.UTC);
assertEquals(info.getEstimatedOffset(), ZoneOffset.UTC);
assertSame(test, ZoneId.of("UTC"));
assertSame(test, ZoneId.of(ZoneOffset.UTC));
}
// OLD_IDS_PRE_2005
public void test_constant_OLD_IDS_PRE_2005() {
Map<String, String> ids = ZoneId.OLD_IDS_PRE_2005;
assertEquals(ids.get("EST"), "America/Indianapolis");
assertEquals(ids.get("MST"), "America/Phoenix");
assertEquals(ids.get("HST"), "Pacific/Honolulu");
assertEquals(ids.get("ACT"), "Australia/Darwin");
assertEquals(ids.get("AET"), "Australia/Sydney");
assertEquals(ids.get("AGT"), "America/Argentina/Buenos_Aires");
assertEquals(ids.get("ART"), "Africa/Cairo");
assertEquals(ids.get("AST"), "America/Anchorage");
assertEquals(ids.get("BET"), "America/Sao_Paulo");
assertEquals(ids.get("BST"), "Asia/Dhaka");
assertEquals(ids.get("CAT"), "Africa/Harare");
assertEquals(ids.get("CNT"), "America/St_Johns");
assertEquals(ids.get("CST"), "America/Chicago");
assertEquals(ids.get("CTT"), "Asia/Shanghai");
assertEquals(ids.get("EAT"), "Africa/Addis_Ababa");
assertEquals(ids.get("ECT"), "Europe/Paris");
assertEquals(ids.get("IET"), "America/Indiana/Indianapolis");
assertEquals(ids.get("IST"), "Asia/Kolkata");
assertEquals(ids.get("JST"), "Asia/Tokyo");
assertEquals(ids.get("MIT"), "Pacific/Apia");
assertEquals(ids.get("NET"), "Asia/Yerevan");
assertEquals(ids.get("NST"), "Pacific/Auckland");
assertEquals(ids.get("PLT"), "Asia/Karachi");
assertEquals(ids.get("PNT"), "America/Phoenix");
assertEquals(ids.get("PRT"), "America/Puerto_Rico");
assertEquals(ids.get("PST"), "America/Los_Angeles");
assertEquals(ids.get("SST"), "Pacific/Guadalcanal");
assertEquals(ids.get("VST"), "Asia/Ho_Chi_Minh");
}
@Test(expectedExceptions=UnsupportedOperationException.class)
public void test_constant_OLD_IDS_PRE_2005_immutable() {
Map<String, String> ids = ZoneId.OLD_IDS_PRE_2005;
ids.clear();
}
// OLD_IDS_POST_2005
public void test_constant_OLD_IDS_POST_2005() {
Map<String, String> ids = ZoneId.OLD_IDS_POST_2005;
assertEquals(ids.get("EST"), "UTC-05:00");
assertEquals(ids.get("MST"), "UTC-07:00");
assertEquals(ids.get("HST"), "UTC-10:00");
assertEquals(ids.get("ACT"), "Australia/Darwin");
assertEquals(ids.get("AET"), "Australia/Sydney");
assertEquals(ids.get("AGT"), "America/Argentina/Buenos_Aires");
assertEquals(ids.get("ART"), "Africa/Cairo");
assertEquals(ids.get("AST"), "America/Anchorage");
assertEquals(ids.get("BET"), "America/Sao_Paulo");
assertEquals(ids.get("BST"), "Asia/Dhaka");
assertEquals(ids.get("CAT"), "Africa/Harare");
assertEquals(ids.get("CNT"), "America/St_Johns");
assertEquals(ids.get("CST"), "America/Chicago");
assertEquals(ids.get("CTT"), "Asia/Shanghai");
assertEquals(ids.get("EAT"), "Africa/Addis_Ababa");
assertEquals(ids.get("ECT"), "Europe/Paris");
assertEquals(ids.get("IET"), "America/Indiana/Indianapolis");
assertEquals(ids.get("IST"), "Asia/Kolkata");
assertEquals(ids.get("JST"), "Asia/Tokyo");
assertEquals(ids.get("MIT"), "Pacific/Apia");
assertEquals(ids.get("NET"), "Asia/Yerevan");
assertEquals(ids.get("NST"), "Pacific/Auckland");
assertEquals(ids.get("PLT"), "Asia/Karachi");
assertEquals(ids.get("PNT"), "America/Phoenix");
assertEquals(ids.get("PRT"), "America/Puerto_Rico");
assertEquals(ids.get("PST"), "America/Los_Angeles");
assertEquals(ids.get("SST"), "Pacific/Guadalcanal");
assertEquals(ids.get("VST"), "Asia/Ho_Chi_Minh");
}
@Test(expectedExceptions=UnsupportedOperationException.class)
public void test_constant_OLD_IDS_POST_2005_immutable() {
Map<String, String> ids = ZoneId.OLD_IDS_POST_2005;
ids.clear();
}
// mapped factory
public void test_of_string_Map() {
Map<String, String> map = new HashMap<String, String>();
map.put("LONDON", "Europe/London");
map.put("PARIS", "Europe/Paris");
ZoneId test = ZoneId.of("LONDON", map);
assertEquals(test.getID(), "Europe/London");
}
public void test_of_string_Map_lookThrough() {
Map<String, String> map = new HashMap<String, String>();
map.put("LONDON", "Europe/London");
map.put("PARIS", "Europe/Paris");
ZoneId test = ZoneId.of("Europe/Madrid", map);
assertEquals(test.getID(), "Europe/Madrid");
}
public void test_of_string_Map_emptyMap() {
Map<String, String> map = new HashMap<String, String>();
ZoneId test = ZoneId.of("Europe/Madrid", map);
assertEquals(test.getID(), "Europe/Madrid");
}
@Test(expectedExceptions=CalendricalException.class)
public void test_of_string_Map_unknown() {
Map<String, String> map = new HashMap<String, String>();
ZoneId.of("Unknown", map);
}
// regular factory
@DataProvider(name="String_UTC")
Object[][] data_of_string_UTC() {
return new Object[][] {
{""}, {"Z"},
{"+00"},{"+0000"},{"+00:00"},{"+000000"},{"+00:00:00"},
{"-00"},{"-0000"},{"-00:00"},{"-000000"},{"-00:00:00"},
};
}
@Test(dataProvider="String_UTC")
public void test_of_string_UTC(String id) {
ZoneId test = ZoneId.of("UTC" + id);
assertSame(test, ZoneId.UTC);
}
@Test(dataProvider="String_UTC")
public void test_of_string_GMT(String id) {
ZoneId test = ZoneId.of("GMT" + id);
assertSame(test, ZoneId.UTC);
}
@DataProvider(name="String_Fixed")
Object[][] data_of_string_Fixed() {
return new Object[][] {
{"", "UTC"},
{"+01", "UTC+01:00"},
{"+0100", "UTC+01:00"},{"+01:00", "UTC+01:00"},
{"+010000", "UTC+01:00"},{"+01:00:00", "UTC+01:00"},
{"+12", "UTC+12:00"},
{"+1234", "UTC+12:34"},{"+12:34", "UTC+12:34"},
{"+123456", "UTC+12:34:56"},{"+12:34:56", "UTC+12:34:56"},
{"-02", "UTC-02:00"},
{"-0200", "UTC-02:00"},{"-02:00", "UTC-02:00"},
{"-020000", "UTC-02:00"},{"-02:00:00", "UTC-02:00"},
};
}
@Test(dataProvider="String_Fixed")
public void test_of_string_FixedUTC(String input, String id) {
ZoneId test = ZoneId.of("UTC" + input);
assertEquals(test.getID(), id);
assertEquals(test.getGroupID(), "");
assertEquals(test.getRegionID(), id);
assertEquals(test.getVersionID(), "");
assertEquals(test.getText(TextStyle.FULL, Locale.UK), id);
assertEquals(test.isFixed(), true);
assertEquals(test.getRules().isFixedOffset(), true);
ZoneOffset offset = id.length() == 3 ? ZoneOffset.UTC : ZoneOffset.of(id.substring(3));
assertEquals(test.getRules().getOffset(Instant.ofEpochSecond(0L)), offset);
ZoneOffsetInfo info = test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 6, 30));
assertEquals(info.isTransition(), false);
assertEquals(info.getTransition(), null);
assertEquals(info.getOffset(), offset);
assertEquals(info.getEstimatedOffset(), offset);
}
@Test(dataProvider="String_Fixed")
public void test_of_string_FixedGMT(String input, String id) {
ZoneId test = ZoneId.of("GMT" + input);
assertEquals(test.getID(), id);
assertEquals(test.getGroupID(), "");
assertEquals(test.getRegionID(), id);
assertEquals(test.getVersionID(), "");
assertEquals(test.getText(TextStyle.FULL, Locale.UK), id);
assertEquals(test.isFixed(), true);
assertEquals(test.getRules().isFixedOffset(), true);
ZoneOffset offset = id.length() == 3 ? ZoneOffset.UTC : ZoneOffset.of(id.substring(3));
assertEquals(test.getRules().getOffset(Instant.ofEpochSecond(0L)), offset);
ZoneOffsetInfo info = test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 6, 30));
assertEquals(info.isTransition(), false);
assertEquals(info.getTransition(), null);
assertEquals(info.getOffset(), offset);
assertEquals(info.getEstimatedOffset(), offset);
}
@DataProvider(name="String_UTC_Invalid")
Object[][] data_of_string_UTC_invalid() {
return new Object[][] {
{"A"}, {"B"}, {"C"}, {"D"}, {"E"}, {"F"}, {"G"}, {"H"}, {"I"}, {"J"}, {"K"}, {"L"}, {"M"},
{"N"}, {"O"}, {"P"}, {"Q"}, {"R"}, {"S"}, {"T"}, {"U"}, {"V"}, {"W"}, {"X"}, {"Y"},
{"+0:00"}, {"+00:0"}, {"+0:0"},
{"+000"}, {"+00000"},
{"+0:00:00"}, {"+00:0:00"}, {"+00:00:0"}, {"+0:0:0"}, {"+0:0:00"}, {"+00:0:0"}, {"+0:00:0"},
{"+01_00"}, {"+01;00"}, {"+01@00"}, {"+01:AA"},
{"+19"}, {"+19:00"}, {"+18:01"}, {"+18:00:01"}, {"+1801"}, {"+180001"},
{"-0:00"}, {"-00:0"}, {"-0:0"},
{"-000"}, {"-00000"},
{"-0:00:00"}, {"-00:0:00"}, {"-00:00:0"}, {"-0:0:0"}, {"-0:0:00"}, {"-00:0:0"}, {"-0:00:0"},
{"-19"}, {"-19:00"}, {"-18:01"}, {"-18:00:01"}, {"-1801"}, {"-180001"},
{"-01_00"}, {"-01;00"}, {"-01@00"}, {"-01:AA"},
{"@01:00"},
};
}
@Test(dataProvider="String_UTC_Invalid", expectedExceptions=CalendricalException.class)
public void test_of_string_UTC_invalid(String id) {
ZoneId.of("UTC" + id);
}
@Test(dataProvider="String_UTC_Invalid", expectedExceptions=CalendricalException.class)
public void test_of_string_UTCp0_invalid(String id) {
ZoneId.of("UTC+0");
}
@Test(dataProvider="String_UTC_Invalid", expectedExceptions=CalendricalException.class)
public void test_of_string_GMT_invalid(String id) {
ZoneId.of("GMT" + id);
}
@DataProvider(name="String_Invalid")
Object[][] data_of_string_invalid() {
return new Object[][] {
{""}, {":"}, {"
{""}, {"`"}, {"!"}, {"\""}, {""}, {"$"}, {"^"}, {"&"}, {"*"}, {"("}, {")"}, {"="},
{"\\"}, {"|"}, {","}, {"<"}, {">"}, {"?"}, {";"}, {":"}, {"'"}, {"["}, {"]"}, {"{"}, {"}"},
{":A"}, {"`:A"}, {"!:A"}, {"\":A"}, {":A"}, {"$:A"}, {"^:A"}, {"&:A"}, {"*:A"}, {"(:A"}, {"):A"}, {"=:A"}, {"+:A"},
{"\\:A"}, {"|:A"}, {",:A"}, {"<:A"}, {">:A"}, {"?:A"}, {";:A"}, {"::A"}, {"':A"}, {"@:A"}, {"~:A"}, {"[:A"}, {"]:A"}, {"{:A"}, {"}:A"},
{"A:B#"}, {"A:B#`"}, {"A:B#!"}, {"A:B#\""}, {"A:B#"}, {"A:B#$"}, {"A:B#^"}, {"A:B#&"}, {"A:B#*"},
{"A:B#("}, {"A:B#)"}, {"A:B#="}, {"A:B#+"},
{"A:B#\\"}, {"A:B#|"}, {"A:B#,"}, {"A:B#<"}, {"A:B#>"}, {"A:B#?"}, {"A:B#;"}, {"A:B#:"},
{"A:B#'"}, {"A:B#@"}, {"A:B#~"}, {"A:B#["}, {"A:B#]"}, {"A:B#{"}, {"A:B#}"},
};
}
@Test(dataProvider="String_Invalid", expectedExceptions=CalendricalException.class)
public void test_of_string_invalid(String id) {
ZoneId.of(id);
}
@Test(dataProvider="String_Invalid", expectedExceptions=CalendricalException.class)
public void test_ofUnchecked_string_invalid(String id) {
ZoneId.ofUnchecked(id);
}
public void test_of_string_floatingGMT0() {
ZoneId test = ZoneId.of("GMT0");
assertEquals(test.getID(), "GMT0");
assertEquals(test.getGroupID(), "TZDB");
assertEquals(test.getRegionID(), "GMT0");
assertEquals(test.getVersionID(), "");
assertEquals(test.isFixed(), false);
}
public void test_of_string_versionedGMT0() {
ZoneId test = ZoneId.of("GMT0#2008i");
assertEquals(test.getID(), "GMT0#2008i");
assertEquals(test.getGroupID(), "TZDB");
assertEquals(test.getRegionID(), "GMT0");
assertEquals(test.getVersionID(), "2008i");
assertEquals(test.isFixed(), false);
}
public void test_of_string_groupGMT0() {
ZoneId test = ZoneId.of("TZDB:GMT0");
assertEquals(test.getID(), "GMT0");
assertEquals(test.getGroupID(), "TZDB");
assertEquals(test.getRegionID(), "GMT0");
assertEquals(test.getVersionID(), "");
assertEquals(test.isFixed(), false);
}
public void test_of_string_groupVersionedGMT0() {
ZoneId test = ZoneId.of("TZDB:GMT0#2008i");
assertEquals(test.getID(), "GMT0#2008i");
assertEquals(test.getGroupID(), "TZDB");
assertEquals(test.getRegionID(), "GMT0");
assertEquals(test.getVersionID(), "2008i");
assertEquals(test.isFixed(), false);
}
public void test_of_string_floatingLondon() {
ZoneId test = ZoneId.of("Europe/London");
assertEquals(test.getID(), "Europe/London");
assertEquals(test.getGroupID(), "TZDB");
assertEquals(test.getRegionID(), "Europe/London");
assertEquals(test.getVersionID(), "");
assertEquals(test.isFixed(), false);
}
public void test_of_string_versionedLondon() {
ZoneId test = ZoneId.of("Europe/London#2008i");
assertEquals(test.getID(), "Europe/London#2008i");
assertEquals(test.getGroupID(), "TZDB");
assertEquals(test.getRegionID(), "Europe/London");
assertEquals(test.getVersionID(), "2008i");
assertEquals(test.isFixed(), false);
}
public void test_of_string_groupLondon() {
ZoneId test = ZoneId.of("TZDB:Europe/London");
assertEquals(test.getID(), "Europe/London");
assertEquals(test.getGroupID(), "TZDB");
assertEquals(test.getRegionID(), "Europe/London");
assertEquals(test.getVersionID(), "");
assertEquals(test.isFixed(), false);
}
public void test_of_string_groupVersionedLondon() {
ZoneId test = ZoneId.of("TZDB:Europe/London#2008i");
assertEquals(test.getID(), "Europe/London#2008i");
assertEquals(test.getGroupID(), "TZDB");
assertEquals(test.getRegionID(), "Europe/London");
assertEquals(test.getVersionID(), "2008i");
assertEquals(test.isFixed(), false);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_of_string_null() {
ZoneId.of((String) null);
}
@Test(expectedExceptions=CalendricalException.class)
public void test_of_string_unknown_simple() {
ZoneId.of("Unknown");
}
@Test(expectedExceptions=CalendricalException.class)
public void test_of_string_unknown_group() {
ZoneId.of("Unknown:Europe/London");
}
@Test(expectedExceptions=CalendricalException.class)
public void test_of_string_unknown_version() {
ZoneId.of("TZDB:Europe/London#Unknown");
}
@Test(expectedExceptions=CalendricalException.class)
public void test_of_string_unknown_region() {
ZoneId.of("TZDB:Unknown#2008i");
}
public void test_ofUnchecked_string_invalidNotChecked() {
ZoneId test = ZoneId.ofUnchecked("UnknownGroup:UnknownRegion#UnknownVersion");
assertEquals(test.getID(), "UnknownGroup:UnknownRegion#UnknownVersion");
assertEquals(test.getGroupID(), "UnknownGroup");
assertEquals(test.getRegionID(), "UnknownRegion");
assertEquals(test.getVersionID(), "UnknownVersion");
assertEquals(test.isFixed(), false);
}
public void test_ofUnchecked_string_invalidNotChecked_unusualCharacters() {
ZoneId test = ZoneId.ofUnchecked("QWERTYUIOPASDFGHJKLZXCVBNM%@~/+.-_");
assertEquals(test.getID(), "QWERTYUIOPASDFGHJKLZXCVBNM%@~/+.-_");
assertEquals(test.getGroupID(), "TZDB");
assertEquals(test.getRegionID(), "QWERTYUIOPASDFGHJKLZXCVBNM%@~/+.-_");
assertEquals(test.getVersionID(), "");
}
// from()
public void test_factory_Calendricals() {
assertEquals(ZoneId.from(ZONE_PARIS, YearMonth.of(2007, 7), DAY_OF_MONTH.field(15), AmPmOfDay.PM, HOUR_OF_AMPM.field(5), MINUTE_OF_HOUR.field(30)), ZONE_PARIS);
assertEquals(ZoneId.from(ZonedDateTime.of(2007, 7, 15, 17, 30, 0, 0, ZONE_PARIS)), ZONE_PARIS);
}
@Test(expectedExceptions=CalendricalException.class)
public void test_factory_Calendricals_invalid_clash() {
ZoneId.from(ZONE_PARIS, ZoneId.of("Europe/London"));
}
@Test(expectedExceptions=CalendricalException.class)
public void test_factory_Calendricals_invalid_noDerive() {
ZoneId.from(LocalTime.of(12, 30));
}
@Test(expectedExceptions=CalendricalException.class)
public void test_factory_Calendricals_invalid_empty() {
ZoneId.from();
}
@Test(expectedExceptions=NullPointerException.class)
public void test_factory_Calendricals_nullArray() {
ZoneId.from((Calendrical[]) null);
}
@Test(expectedExceptions=NullPointerException.class)
public void test_factory_Calendricals_null() {
ZoneId.from((Calendrical) null);
}
// Europe/London
public void test_London() {
ZoneId test = ZoneId.of("Europe/London");
assertEquals(test.getID(), "Europe/London");
assertEquals(test.getGroupID(), "TZDB");
assertEquals(test.getRegionID(), "Europe/London");
assertEquals(test.getVersionID(), "");
assertEquals(test.isFixed(), false);
}
public void test_London_getOffset() {
ZoneId test = ZoneId.of("Europe/London");
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 1, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(0));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 2, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(0));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(0));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 4, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 5, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 6, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 7, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 8, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 9, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 11, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(0));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 12, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(0));
}
public void test_London_getOffset_toDST() {
ZoneId test = ZoneId.of("Europe/London");
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 24, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(0));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 25, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(0));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 26, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(0));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 27, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(0));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 28, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(0));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 29, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(0));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 30, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(0));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 31, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
// cutover at 01:00Z
assertEquals(test.getRules().getOffset(OffsetDateTime.of(2008, 3, 30, 0, 59, 59, 999999999, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(0));
assertEquals(test.getRules().getOffset(OffsetDateTime.of(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
}
public void test_London_getOffset_fromDST() {
ZoneId test = ZoneId.of("Europe/London");
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 24, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 25, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 26, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 27, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(0));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 28, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(0));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 29, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(0));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 30, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(0));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 31, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(0));
// cutover at 01:00Z
assertEquals(test.getRules().getOffset(OffsetDateTime.of(2008, 10, 26, 0, 59, 59, 999999999, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.of(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(0));
}
public void test_London_getOffsetInfo() {
ZoneId test = ZoneId.of("Europe/London");
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 1, 1)), ZoneOffset.ofHours(0));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 2, 1)), ZoneOffset.ofHours(0));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 1)), ZoneOffset.ofHours(0));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 4, 1)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 5, 1)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 6, 1)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 7, 1)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 8, 1)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 9, 1)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 1)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 11, 1)), ZoneOffset.ofHours(0));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 12, 1)), ZoneOffset.ofHours(0));
}
public void test_London_getOffsetInfo_toDST() {
ZoneId test = ZoneId.of("Europe/London");
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 24)), ZoneOffset.ofHours(0));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 25)), ZoneOffset.ofHours(0));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 26)), ZoneOffset.ofHours(0));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 27)), ZoneOffset.ofHours(0));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 28)), ZoneOffset.ofHours(0));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 29)), ZoneOffset.ofHours(0));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 30)), ZoneOffset.ofHours(0));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 31)), ZoneOffset.ofHours(1));
// cutover at 01:00Z
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.of(2008, 3, 30, 0, 59, 59, 999999999)), ZoneOffset.ofHours(0));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.of(2008, 3, 30, 2, 0, 0, 0)), ZoneOffset.ofHours(1));
}
public void test_London_getOffsetInfo_fromDST() {
ZoneId test = ZoneId.of("Europe/London");
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 24)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 25)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 26)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 27)), ZoneOffset.ofHours(0));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 28)), ZoneOffset.ofHours(0));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 29)), ZoneOffset.ofHours(0));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 30)), ZoneOffset.ofHours(0));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 31)), ZoneOffset.ofHours(0));
// cutover at 01:00Z
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.of(2008, 10, 26, 0, 59, 59, 999999999)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.of(2008, 10, 26, 2, 0, 0, 0)), ZoneOffset.ofHours(0));
}
public void test_London_getOffsetInfo_gap() {
ZoneId test = ZoneId.of("Europe/London");
final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 30, 1, 0, 0, 0);
ZoneOffsetInfo info = test.getRules().getOffsetInfo(dateTime);
assertEquals(info.isTransition(), true);
assertEquals(info.getOffset(), null);
assertEquals(info.getEstimatedOffset(), ZoneOffset.ofHours(1));
ZoneOffsetTransition dis = info.getTransition();
assertEquals(dis.isGap(), true);
assertEquals(dis.isOverlap(), false);
assertEquals(dis.getOffsetBefore(), ZoneOffset.ofHours(0));
assertEquals(dis.getOffsetAfter(), ZoneOffset.ofHours(1));
assertEquals(dis.getInstant(), OffsetDateTime.of(2008, 3, 30, 1, 0, ZoneOffset.UTC).toInstant());
assertEquals(dis.getDateTimeBefore(), OffsetDateTime.of(2008, 3, 30, 1, 0, ZoneOffset.ofHours(0)));
assertEquals(dis.getDateTimeAfter(), OffsetDateTime.of(2008, 3, 30, 2, 0, ZoneOffset.ofHours(1)));
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(-1)), false);
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(0)), true);
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(1)), true);
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(2)), false);
assertEquals(dis.isValidOffset(ZoneOffset.ofHours(0)), false);
assertEquals(dis.isValidOffset(ZoneOffset.ofHours(1)), false);
assertEquals(dis.toString(), "Transition[Gap at 2008-03-30T01:00Z to +01:00]");
assertFalse(dis.equals(null));
assertFalse(dis.equals(ZoneOffset.ofHours(0)));
assertTrue(dis.equals(dis));
final ZoneOffsetTransition otherDis = test.getRules().getOffsetInfo(dateTime).getTransition();
assertTrue(dis.equals(otherDis));
assertEquals(dis.hashCode(), otherDis.hashCode());
}
public void test_London_getOffsetInfo_overlap() {
ZoneId test = ZoneId.of("Europe/London");
final LocalDateTime dateTime = LocalDateTime.of(2008, 10, 26, 1, 0, 0, 0);
ZoneOffsetInfo info = test.getRules().getOffsetInfo(dateTime);
assertEquals(info.isTransition(), true);
assertEquals(info.getOffset(), null);
assertEquals(info.getEstimatedOffset(), ZoneOffset.ofHours(0));
ZoneOffsetTransition dis = info.getTransition();
assertEquals(dis.isGap(), false);
assertEquals(dis.isOverlap(), true);
assertEquals(dis.getOffsetBefore(), ZoneOffset.ofHours(1));
assertEquals(dis.getOffsetAfter(), ZoneOffset.ofHours(0));
assertEquals(dis.getInstant(), OffsetDateTime.of(2008, 10, 26, 1, 0, ZoneOffset.UTC).toInstant());
assertEquals(dis.getDateTimeBefore(), OffsetDateTime.of(2008, 10, 26, 2, 0, ZoneOffset.ofHours(1)));
assertEquals(dis.getDateTimeAfter(), OffsetDateTime.of(2008, 10, 26, 1, 0, ZoneOffset.ofHours(0)));
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(-1)), false);
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(0)), true);
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(1)), true);
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(2)), false);
assertEquals(dis.isValidOffset(ZoneOffset.ofHours(-1)), false);
assertEquals(dis.isValidOffset(ZoneOffset.ofHours(0)), true);
assertEquals(dis.isValidOffset(ZoneOffset.ofHours(1)), true);
assertEquals(dis.isValidOffset(ZoneOffset.ofHours(2)), false);
assertEquals(dis.toString(), "Transition[Overlap at 2008-10-26T02:00+01:00 to Z]");
assertFalse(dis.equals(null));
assertFalse(dis.equals(ZoneOffset.ofHours(1)));
assertTrue(dis.equals(dis));
final ZoneOffsetTransition otherDis = test.getRules().getOffsetInfo(dateTime).getTransition();
assertTrue(dis.equals(otherDis));
assertEquals(dis.hashCode(), otherDis.hashCode());
}
// Europe/Paris
public void test_Paris() {
ZoneId test = ZoneId.of("Europe/Paris");
assertEquals(test.getID(), "Europe/Paris");
assertEquals(test.getGroupID(), "TZDB");
assertEquals(test.getRegionID(), "Europe/Paris");
assertEquals(test.getVersionID(), "");
assertEquals(test.isFixed(), false);
}
public void test_Paris_getOffset() {
ZoneId test = ZoneId.of("Europe/Paris");
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 1, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 2, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 4, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(2));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 5, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(2));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 6, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(2));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 7, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(2));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 8, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(2));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 9, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(2));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(2));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 11, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 12, 1, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
}
public void test_Paris_getOffset_toDST() {
ZoneId test = ZoneId.of("Europe/Paris");
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 24, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 25, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 26, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 27, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 28, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 29, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 30, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 31, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(2));
// cutover at 01:00Z
assertEquals(test.getRules().getOffset(OffsetDateTime.of(2008, 3, 30, 0, 59, 59, 999999999, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.of(2008, 3, 30, 1, 0, 0, 0, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(2));
}
public void test_Paris_getOffset_fromDST() {
ZoneId test = ZoneId.of("Europe/Paris");
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 24, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(2));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 25, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(2));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 26, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(2));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 27, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 28, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 29, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 30, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 31, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
// cutover at 01:00Z
assertEquals(test.getRules().getOffset(OffsetDateTime.of(2008, 10, 26, 0, 59, 59, 999999999, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(2));
assertEquals(test.getRules().getOffset(OffsetDateTime.of(2008, 10, 26, 1, 0, 0, 0, ZoneOffset.UTC).toInstant()), ZoneOffset.ofHours(1));
}
public void test_Paris_getOffsetInfo() {
ZoneId test = ZoneId.of("Europe/Paris");
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 1, 1)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 2, 1)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 1)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 4, 1)), ZoneOffset.ofHours(2));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 5, 1)), ZoneOffset.ofHours(2));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 6, 1)), ZoneOffset.ofHours(2));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 7, 1)), ZoneOffset.ofHours(2));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 8, 1)), ZoneOffset.ofHours(2));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 9, 1)), ZoneOffset.ofHours(2));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 1)), ZoneOffset.ofHours(2));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 11, 1)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 12, 1)), ZoneOffset.ofHours(1));
}
public void test_Paris_getOffsetInfo_toDST() {
ZoneId test = ZoneId.of("Europe/Paris");
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 24)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 25)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 26)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 27)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 28)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 29)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 30)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 31)), ZoneOffset.ofHours(2));
// cutover at 01:00Z which is 02:00+01:00(local Paris time)
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.of(2008, 3, 30, 1, 59, 59, 999999999)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.of(2008, 3, 30, 3, 0, 0, 0)), ZoneOffset.ofHours(2));
}
public void test_Paris_getOffsetInfo_fromDST() {
ZoneId test = ZoneId.of("Europe/Paris");
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 24)), ZoneOffset.ofHours(2));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 25)), ZoneOffset.ofHours(2));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 26)), ZoneOffset.ofHours(2));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 27)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 28)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 29)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 30)), ZoneOffset.ofHours(1));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 31)), ZoneOffset.ofHours(1));
// cutover at 01:00Z which is 02:00+01:00(local Paris time)
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.of(2008, 10, 26, 1, 59, 59, 999999999)), ZoneOffset.ofHours(2));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.of(2008, 10, 26, 3, 0, 0, 0)), ZoneOffset.ofHours(1));
}
public void test_Paris_getOffsetInfo_gap() {
ZoneId test = ZoneId.of("Europe/Paris");
final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 30, 2, 0, 0, 0);
ZoneOffsetInfo info = test.getRules().getOffsetInfo(dateTime);
assertEquals(info.isTransition(), true);
assertEquals(info.getOffset(), null);
assertEquals(info.getEstimatedOffset(), ZoneOffset.ofHours(2));
ZoneOffsetTransition dis = info.getTransition();
assertEquals(dis.isGap(), true);
assertEquals(dis.isOverlap(), false);
assertEquals(dis.getOffsetBefore(), ZoneOffset.ofHours(1));
assertEquals(dis.getOffsetAfter(), ZoneOffset.ofHours(2));
assertEquals(dis.getInstant(), OffsetDateTime.of(2008, 3, 30, 1, 0, ZoneOffset.UTC).toInstant());
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(0)), false);
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(1)), true);
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(2)), true);
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(3)), false);
assertEquals(dis.isValidOffset(ZoneOffset.ofHours(1)), false);
assertEquals(dis.isValidOffset(ZoneOffset.ofHours(2)), false);
assertEquals(dis.toString(), "Transition[Gap at 2008-03-30T02:00+01:00 to +02:00]");
assertFalse(dis.equals(null));
assertFalse(dis.equals(ZoneOffset.ofHours(1)));
assertTrue(dis.equals(dis));
final ZoneOffsetTransition otherDis = test.getRules().getOffsetInfo(dateTime).getTransition();
assertTrue(dis.equals(otherDis));
assertEquals(dis.hashCode(), otherDis.hashCode());
}
public void test_Paris_getOffsetInfo_overlap() {
ZoneId test = ZoneId.of("Europe/Paris");
final LocalDateTime dateTime = LocalDateTime.of(2008, 10, 26, 2, 0, 0, 0);
ZoneOffsetInfo info = test.getRules().getOffsetInfo(dateTime);
assertEquals(info.isTransition(), true);
assertEquals(info.getOffset(), null);
assertEquals(info.getEstimatedOffset(), ZoneOffset.ofHours(1));
ZoneOffsetTransition dis = info.getTransition();
assertEquals(dis.isGap(), false);
assertEquals(dis.isOverlap(), true);
assertEquals(dis.getOffsetBefore(), ZoneOffset.ofHours(2));
assertEquals(dis.getOffsetAfter(), ZoneOffset.ofHours(1));
assertEquals(dis.getInstant(), OffsetDateTime.of(2008, 10, 26, 1, 0, ZoneOffset.UTC).toInstant());
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(0)), false);
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(1)), true);
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(2)), true);
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(3)), false);
assertEquals(dis.isValidOffset(ZoneOffset.ofHours(0)), false);
assertEquals(dis.isValidOffset(ZoneOffset.ofHours(1)), true);
assertEquals(dis.isValidOffset(ZoneOffset.ofHours(2)), true);
assertEquals(dis.isValidOffset(ZoneOffset.ofHours(3)), false);
assertEquals(dis.toString(), "Transition[Overlap at 2008-10-26T03:00+02:00 to +01:00]");
assertFalse(dis.equals(null));
assertFalse(dis.equals(ZoneOffset.ofHours(2)));
assertTrue(dis.equals(dis));
final ZoneOffsetTransition otherDis = test.getRules().getOffsetInfo(dateTime).getTransition();
assertTrue(dis.equals(otherDis));
assertEquals(dis.hashCode(), otherDis.hashCode());
}
// America/New_York
public void test_NewYork() {
ZoneId test = ZoneId.of("America/New_York");
assertEquals(test.getID(), "America/New_York");
assertEquals(test.getGroupID(), "TZDB");
assertEquals(test.getRegionID(), "America/New_York");
assertEquals(test.getVersionID(), "");
assertEquals(test.isFixed(), false);
}
public void test_NewYork_getOffset() {
ZoneId test = ZoneId.of("America/New_York");
ZoneOffset offset = ZoneOffset.ofHours(-5);
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 1, 1, offset).toInstant()), ZoneOffset.ofHours(-5));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 2, 1, offset).toInstant()), ZoneOffset.ofHours(-5));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 1, offset).toInstant()), ZoneOffset.ofHours(-5));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 4, 1, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 5, 1, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 6, 1, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 7, 1, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 8, 1, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 9, 1, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 1, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 11, 1, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 12, 1, offset).toInstant()), ZoneOffset.ofHours(-5));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 1, 28, offset).toInstant()), ZoneOffset.ofHours(-5));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 2, 28, offset).toInstant()), ZoneOffset.ofHours(-5));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 28, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 4, 28, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 5, 28, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 6, 28, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 7, 28, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 8, 28, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 9, 28, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 10, 28, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 11, 28, offset).toInstant()), ZoneOffset.ofHours(-5));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 12, 28, offset).toInstant()), ZoneOffset.ofHours(-5));
}
public void test_NewYork_getOffset_toDST() {
ZoneId test = ZoneId.of("America/New_York");
ZoneOffset offset = ZoneOffset.ofHours(-5);
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 8, offset).toInstant()), ZoneOffset.ofHours(-5));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 9, offset).toInstant()), ZoneOffset.ofHours(-5));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 10, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 11, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 12, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 13, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 3, 14, offset).toInstant()), ZoneOffset.ofHours(-4));
// cutover at 02:00 local
assertEquals(test.getRules().getOffset(OffsetDateTime.of(2008, 3, 9, 1, 59, 59, 999999999, offset).toInstant()), ZoneOffset.ofHours(-5));
assertEquals(test.getRules().getOffset(OffsetDateTime.of(2008, 3, 9, 2, 0, 0, 0, offset).toInstant()), ZoneOffset.ofHours(-4));
}
public void test_NewYork_getOffset_fromDST() {
ZoneId test = ZoneId.of("America/New_York");
ZoneOffset offset = ZoneOffset.ofHours(-4);
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 11, 1, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 11, 2, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 11, 3, offset).toInstant()), ZoneOffset.ofHours(-5));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 11, 4, offset).toInstant()), ZoneOffset.ofHours(-5));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 11, 5, offset).toInstant()), ZoneOffset.ofHours(-5));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 11, 6, offset).toInstant()), ZoneOffset.ofHours(-5));
assertEquals(test.getRules().getOffset(OffsetDateTime.ofMidnight(2008, 11, 7, offset).toInstant()), ZoneOffset.ofHours(-5));
// cutover at 02:00 local
assertEquals(test.getRules().getOffset(OffsetDateTime.of(2008, 11, 2, 1, 59, 59, 999999999, offset).toInstant()), ZoneOffset.ofHours(-4));
assertEquals(test.getRules().getOffset(OffsetDateTime.of(2008, 11, 2, 2, 0, 0, 0, offset).toInstant()), ZoneOffset.ofHours(-5));
}
public void test_NewYork_getOffsetInfo() {
ZoneId test = ZoneId.of("America/New_York");
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 1, 1)), ZoneOffset.ofHours(-5));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 2, 1)), ZoneOffset.ofHours(-5));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 1)), ZoneOffset.ofHours(-5));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 4, 1)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 5, 1)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 6, 1)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 7, 1)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 8, 1)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 9, 1)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 1)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 11, 1)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 12, 1)), ZoneOffset.ofHours(-5));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 1, 28)), ZoneOffset.ofHours(-5));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 2, 28)), ZoneOffset.ofHours(-5));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 28)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 4, 28)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 5, 28)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 6, 28)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 7, 28)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 8, 28)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 9, 28)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 10, 28)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 11, 28)), ZoneOffset.ofHours(-5));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 12, 28)), ZoneOffset.ofHours(-5));
}
public void test_NewYork_getOffsetInfo_toDST() {
ZoneId test = ZoneId.of("America/New_York");
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 8)), ZoneOffset.ofHours(-5));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 9)), ZoneOffset.ofHours(-5));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 10)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 11)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 12)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 13)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 3, 14)), ZoneOffset.ofHours(-4));
// cutover at 02:00 local
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.of(2008, 3, 9, 1, 59, 59, 999999999)), ZoneOffset.ofHours(-5));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.of(2008, 3, 9, 3, 0, 0, 0)), ZoneOffset.ofHours(-4));
}
public void test_NewYork_getOffsetInfo_fromDST() {
ZoneId test = ZoneId.of("America/New_York");
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 11, 1)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 11, 2)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 11, 3)), ZoneOffset.ofHours(-5));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 11, 4)), ZoneOffset.ofHours(-5));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 11, 5)), ZoneOffset.ofHours(-5));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 11, 6)), ZoneOffset.ofHours(-5));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.ofMidnight(2008, 11, 7)), ZoneOffset.ofHours(-5));
// cutover at 02:00 local
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.of(2008, 11, 2, 0, 59, 59, 999999999)), ZoneOffset.ofHours(-4));
checkOffset(test.getRules().getOffsetInfo(LocalDateTime.of(2008, 11, 2, 2, 0, 0, 0)), ZoneOffset.ofHours(-5));
}
public void test_NewYork_getOffsetInfo_gap() {
ZoneId test = ZoneId.of("America/New_York");
final LocalDateTime dateTime = LocalDateTime.of(2008, 3, 9, 2, 0, 0, 0);
ZoneOffsetInfo info = test.getRules().getOffsetInfo(dateTime);
assertEquals(info.isTransition(), true);
assertEquals(info.getOffset(), null);
assertEquals(info.getEstimatedOffset(), ZoneOffset.ofHours(-4));
ZoneOffsetTransition dis = info.getTransition();
assertEquals(dis.isGap(), true);
assertEquals(dis.isOverlap(), false);
assertEquals(dis.getOffsetBefore(), ZoneOffset.ofHours(-5));
assertEquals(dis.getOffsetAfter(), ZoneOffset.ofHours(-4));
assertEquals(dis.getInstant(), OffsetDateTime.of(2008, 3, 9, 2, 0, ZoneOffset.ofHours(-5)).toInstant());
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(-1)), false);
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(-5)), true);
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(-4)), true);
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(2)), false);
assertEquals(dis.isValidOffset(ZoneOffset.ofHours(-5)), false);
assertEquals(dis.isValidOffset(ZoneOffset.ofHours(-4)), false);
assertEquals(dis.toString(), "Transition[Gap at 2008-03-09T02:00-05:00 to -04:00]");
assertFalse(dis.equals(null));
assertFalse(dis.equals(ZoneOffset.ofHours(-5)));
assertTrue(dis.equals(dis));
final ZoneOffsetTransition otherDis = test.getRules().getOffsetInfo(dateTime).getTransition();
assertTrue(dis.equals(otherDis));
assertEquals(dis.hashCode(), otherDis.hashCode());
}
public void test_NewYork_getOffsetInfo_overlap() {
ZoneId test = ZoneId.of("America/New_York");
final LocalDateTime dateTime = LocalDateTime.of(2008, 11, 2, 1, 0, 0, 0);
ZoneOffsetInfo info = test.getRules().getOffsetInfo(dateTime);
assertEquals(info.isTransition(), true);
assertEquals(info.getOffset(), null);
assertEquals(info.getEstimatedOffset(), ZoneOffset.ofHours(-5));
ZoneOffsetTransition dis = info.getTransition();
assertEquals(dis.isGap(), false);
assertEquals(dis.isOverlap(), true);
assertEquals(dis.getOffsetBefore(), ZoneOffset.ofHours(-4));
assertEquals(dis.getOffsetAfter(), ZoneOffset.ofHours(-5));
assertEquals(dis.getInstant(), OffsetDateTime.of(2008, 11, 2, 2, 0, ZoneOffset.ofHours(-4)).toInstant());
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(-1)), false);
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(-5)), true);
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(-4)), true);
// assertEquals(dis.containsOffset(ZoneOffset.zoneOffset(2)), false);
assertEquals(dis.isValidOffset(ZoneOffset.ofHours(-1)), false);
assertEquals(dis.isValidOffset(ZoneOffset.ofHours(-5)), true);
assertEquals(dis.isValidOffset(ZoneOffset.ofHours(-4)), true);
assertEquals(dis.isValidOffset(ZoneOffset.ofHours(2)), false);
assertEquals(dis.toString(), "Transition[Overlap at 2008-11-02T02:00-04:00 to -05:00]");
assertFalse(dis.equals(null));
assertFalse(dis.equals(ZoneOffset.ofHours(-4)));
assertTrue(dis.equals(dis));
final ZoneOffsetTransition otherDis = test.getRules().getOffsetInfo(dateTime).getTransition();
assertTrue(dis.equals(otherDis));
assertEquals(dis.hashCode(), otherDis.hashCode());
}
// getXxx() isXxx()
public void test_get_TzdbFloating() {
ZoneId test = ZoneId.of("Europe/London");
assertEquals(test.getID(), "Europe/London");
assertEquals(test.getGroupID(), "TZDB");
assertEquals(test.getRegionID(), "Europe/London");
assertEquals(test.getVersionID(), "");
assertEquals(test.getGroup().getID(), "TZDB");
assertEquals(test.isFixed(), false);
assertEquals(test.isFloatingVersion(), true);
assertEquals(test.isLatestVersion(), true);
}
public void test_get_TzdbVersioned() {
ZoneId test = ZoneId.of("Europe/London#2008i");
assertEquals(test.getID(), "Europe/London#2008i");
assertEquals(test.getGroupID(), "TZDB");
assertEquals(test.getRegionID(), "Europe/London");
assertEquals(test.getVersionID(), "2008i");
assertEquals(test.getGroup().getID(), "TZDB");
assertEquals(test.isFixed(), false);
assertEquals(test.isFloatingVersion(), false);
assertEquals(test.isLatestVersion(), LATEST_TZDB.equals("2008i"));
}
public void test_get_TzdbFixed() {
ZoneId test = ZoneId.of("UTC+01:30");
assertEquals(test.getID(), "UTC+01:30");
assertEquals(test.getGroupID(), "");
assertEquals(test.getRegionID(), "UTC+01:30");
assertEquals(test.getVersionID(), "");
assertEquals(test.isFixed(), true);
assertEquals(test.isFloatingVersion(), true);
assertEquals(test.isLatestVersion(), true);
}
@Test(expectedExceptions=CalendricalException.class)
public void test_get_TzdbFixed_getGroup() {
ZoneId test = ZoneId.of("UTC+01:30");
test.getGroup();
}
public void test_withFloatingVersion_TzdbFloating() {
ZoneId base = ZoneId.of("Europe/London");
ZoneId test = base.withFloatingVersion();
assertSame(test, base);
}
public void test_withFloatingVersion_TzdbVersioned() {
ZoneId base = ZoneId.of("Europe/London#2008i");
ZoneId test = base.withFloatingVersion();
assertEquals(base.getID(), "Europe/London#2008i");
assertEquals(test.getID(), "Europe/London");
// assertNotSame(test.getRules(), base.getRules()); // TODO: rewrite test with mocks
}
public void test_withFloatingVersion_TzdbFixed() {
ZoneId base = ZoneId.of("UTC+01:30");
ZoneId test = base.withFloatingVersion();
assertSame(test, base);
}
public void test_withLatestVersion_TzdbFloating() {
ZoneId base = ZoneId.of("Europe/London");
ZoneId test = base.withLatestVersion();
assertEquals(base.getID(), "Europe/London");
assertEquals(test.getID(), "Europe/London#" + LATEST_TZDB);
}
public void test_withLatestVersion_TzdbVersioned() {
ZoneId base = ZoneId.of("Europe/London#2008i");
ZoneId test = base.withLatestVersion();
assertEquals(base.getID(), "Europe/London#2008i");
assertEquals(test.getID(), "Europe/London#" + LATEST_TZDB);
// assertNotSame(test.getRules(), base.getRules());
}
public void test_withLatestVersion_TzdbVersioned_alreadyLatest() {
ZoneId base = ZoneId.of("Europe/London#" + LATEST_TZDB);
ZoneId test = base.withLatestVersion();
assertSame(test, base);
assertSame(test.getRules(), base.getRules());
}
public void test_withLatestVersion_TzdbFixed() {
ZoneId base = ZoneId.of("UTC+01:30");
ZoneId test = base.withLatestVersion();
assertSame(test, base);
}
public void test_withVersion_TzdbFloating() {
ZoneId base = ZoneId.of("Europe/London");
ZoneId test = base.withVersion("2008i");
assertEquals(base.getID(), "Europe/London");
assertEquals(test.getID(), "Europe/London#2008i");
}
public void test_withVersion_TzdbFloating_latestVersion() {
ZoneId base = ZoneId.of("Europe/London");
ZoneId test = base.withVersion(LATEST_TZDB);
assertEquals(base.getID(), "Europe/London");
assertEquals(test.getID(), "Europe/London#" + LATEST_TZDB);
}
public void test_withVersion_TzdbFloating_floatingVersion() {
ZoneId base = ZoneId.of("Europe/London");
ZoneId test = base.withVersion("");
assertEquals(test, base);
}
@Test(expectedExceptions=CalendricalException.class)
public void test_withVersion_TzdbFloating_badVersion() {
ZoneId base = ZoneId.of("Europe/London");
base.withVersion("20");
}
@Test(expectedExceptions=NullPointerException.class)
public void test_withVersion_TzdbFloating_null() {
ZoneId base = ZoneId.of("Europe/London");
base.withVersion(null);
}
public void test_withVersion_TzdbVersioned() {
ZoneId base = ZoneId.of("Europe/London#2008i");
ZoneId test = base.withVersion("2009a");
assertEquals(base.getID(), "Europe/London#2008i");
assertEquals(test.getID(), "Europe/London#2009a");
}
public void test_withVersion_TzdbVersioned_latestVersion() {
ZoneId base = ZoneId.of("Europe/London#2008i");
ZoneId test = base.withVersion(LATEST_TZDB);
assertEquals(base.getID(), "Europe/London#2008i");
assertEquals(test.getID(), "Europe/London#" + LATEST_TZDB);
}
public void test_withVersion_TzdbVersioned_sameVersion() {
ZoneId base = ZoneId.of("Europe/London#2008i");
ZoneId test = base.withVersion("2008i");
assertSame(test, base);
}
public void test_withVersion_TzdbVersioned_floatingVersion() {
ZoneId base = ZoneId.of("Europe/London#2008i");
ZoneId test = base.withVersion("");
assertEquals(base.getID(), "Europe/London#2008i");
assertEquals(test.getID(), "Europe/London");
}
@Test(expectedExceptions=CalendricalException.class)
public void test_withVersion_TzdbVersioned_badVersion() {
ZoneId base = ZoneId.of("Europe/London#2008i");
base.withVersion("20");
}
@Test(expectedExceptions=NullPointerException.class)
public void test_withVersion_TzdbVersioned_null() {
ZoneId base = ZoneId.of("Europe/London#2008i");
base.withVersion(null);
}
public void test_withVersion_TzdbFixed_floatingVersion() {
ZoneId base = ZoneId.of("UTC+01:30");
ZoneId test = base.withVersion("");
assertSame(test, base);
}
@Test(expectedExceptions=CalendricalException.class)
public void test_withVersion_TzdbFixed_badVersion() {
ZoneId base = ZoneId.of("UTC+01:30");
base.withVersion("20");
}
@Test(expectedExceptions=NullPointerException.class)
public void test_withVersion_TzdbFixed_null() {
ZoneId base = ZoneId.of("UTC+01:30");
base.withVersion(null);
}
// isValid()
public void test_isValid() {
ZoneId testId = ZoneId.of("Europe/London");
assertEquals(testId.isValid(), true);
ZoneId testFixed = ZoneId.of("UTC+01:30");
assertEquals(testFixed.isValid(), true);
}
// isValidFor()
public void test_isValidFor() {
OffsetDateTime odt1 = OffsetDateTime.of(2011, 6, 20, 12, 30, ZoneOffset.ofHours(1));
OffsetDateTime odt2 = OffsetDateTime.of(2011, 6, 20, 12, 30, ZoneOffset.ofHoursMinutes(1, 30));
ZoneId testId = ZoneId.of("Europe/London");
assertEquals(testId.isValidFor(odt1), true);
assertEquals(testId.isValidFor(odt2), false);
ZoneId testFixed = ZoneId.of("UTC+01:00");
assertEquals(testFixed.isValidFor(odt1), true);
assertEquals(testFixed.isValidFor(odt2), false);
}
public void test_isValidFor_null() {
ZoneId testId = ZoneId.of("Europe/London");
assertEquals(testId.isValidFor(null), false);
ZoneId testFixed = ZoneId.of("UTC+01:30");
assertEquals(testFixed.isValidFor(null), false);
}
// // toTimeZone()
// public void test_toTimeZone() {
// TimeZone offset = TimeZone.timeZone(1, 2, 3);
// assertEquals(offset.toTimeZone(), TimeZone.timeZone(offset));
// // compareTo()
// public void test_compareTo() {
// TimeZone offset1 = TimeZone.timeZone(1, 2, 3);
// TimeZone offset2 = TimeZone.timeZone(2, 3, 4);
// assertTrue(offset1.compareTo(offset2) > 0);
// assertTrue(offset2.compareTo(offset1) < 0);
// assertTrue(offset1.compareTo(offset1) == 0);
// assertTrue(offset2.compareTo(offset2) == 0);
// equals() / hashCode()
public void test_equals() {
ZoneId test1 = ZoneId.of("Europe/London");
ZoneId test2 = ZoneId.of("Europe/Paris");
ZoneId test2b = ZoneId.of("Europe/Paris");
assertEquals(test1.equals(test2), false);
assertEquals(test2.equals(test1), false);
assertEquals(test1.equals(test1), true);
assertEquals(test2.equals(test2), true);
assertEquals(test2.equals(test2b), true);
assertEquals(test1.hashCode() == test1.hashCode(), true);
assertEquals(test2.hashCode() == test2.hashCode(), true);
assertEquals(test2.hashCode() == test2b.hashCode(), true);
}
public void test_equals_null() {
assertEquals(ZoneId.of("Europe/London").equals(null), false);
}
public void test_equals_notTimeZone() {
assertEquals(ZoneId.of("Europe/London").equals("Europe/London"), false);
}
// toString()
@DataProvider(name="ToString")
Object[][] data_toString() {
return new Object[][] {
{"Europe/London", "Europe/London"},
{"TZDB:Europe/Paris", "Europe/Paris"},
{"TZDB:Europe/Berlin", "Europe/Berlin"},
{"Europe/London#2008i", "Europe/London#2008i"},
{"TZDB:Europe/Paris#2008i", "Europe/Paris#2008i"},
{"TZDB:Europe/Berlin#2008i", "Europe/Berlin#2008i"},
{"UTC", "UTC"},
{"UTC+01:00", "UTC+01:00"},
};
}
@Test(dataProvider="ToString")
public void test_toString(String id, String expected) {
ZoneId test = ZoneId.of(id);
assertEquals(test.toString(), expected);
}
// get(CalendricalRule)
public void test_get_CalendricalRule() {
ZoneId test = ZoneId.of("Europe/London");
assertEquals(test.get(Chronology.rule()), null);
assertEquals(test.get(YEAR), null);
assertEquals(test.get(HOUR_OF_DAY), null);
assertEquals(test.get(LocalDate.rule()), null);
assertEquals(test.get(ZoneOffset.rule()), null);
assertEquals(test.get(ZoneId.rule()), test);
}
public void test_get_CalendricalRule_fixedOffset() {
ZoneId test = ZoneId.of("UTC+03:00");
assertEquals(test.get(Chronology.rule()), null);
assertEquals(test.get(YEAR), null);
assertEquals(test.get(HOUR_OF_DAY), null);
assertEquals(test.get(LocalDate.rule()), null);
assertEquals(test.get(ZoneOffset.rule()), null); // could get ZoneOffset.ofHours(3), but seems like a bad idea
assertEquals(test.get(ZoneId.rule()), test);
}
@Test(expectedExceptions=NullPointerException.class )
public void test_get_CalendricalRule_null() {
ZoneId test = ZoneId.of("Europe/London");
test.get((CalendricalRule<?>) null);
}
public void test_get_unsupported() {
ZoneId test = ZoneId.of("Europe/London");
assertEquals(test.get(MockRuleNoValue.INSTANCE), null);
}
private void checkOffset(ZoneOffsetInfo info, ZoneOffset zoneOffset) {
assertEquals(info.isTransition(), false);
assertEquals(info.getTransition(), null);
assertEquals(info.getOffset(), zoneOffset);
assertEquals(info.getEstimatedOffset(), zoneOffset);
// assertEquals(info.containsOffset(zoneOffset), true);
assertEquals(info.isValidOffset(zoneOffset), true);
}
} |
package de.lessvoid.coregl;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import de.lessvoid.coregl.spi.CoreGL;
/**
* Helper class that represents a shader (actually the combination of a vertex
* and a fragment shader - what GL actually calls a program).
*
* @author void
* @author Brian Groenke (groenke.5@osu.edu)
*/
public class CoreShader {
private final CoreLogger log;
private final int program;
private final Map<String, Integer> parameter = new HashMap<String, Integer>();
private FloatBuffer matBuffer;
private final String[] attributes;
private final CoreGL gl;
/**
* Create a new Shader.
*
* @return the new CoreShader instance
*/
public static CoreShader createShader(final CoreGL gl) {
return new CoreShader(gl);
}
/**
* Create a new Shader with the given vertex attributes automatically bind to
* the generic attribute indices in ascending order beginning with 0. This
* method can be used when you want to control the vertex attribute binding on
* your own.
*
* @param vertexAttributes
* the name of the vertex attribute. The first String gets generic
* attribute index 0. the second String gets generic attribute index
* 1 and so on.
* @return the CoreShader instance
*/
public static CoreShader createShaderWithVertexAttributes(final CoreGL gl, final String... vertexAttributes) {
return new CoreShader(gl, vertexAttributes);
}
CoreShader(final CoreGL gl, final String... vertexAttributes) {
this.gl = gl;
attributes = vertexAttributes;
program = gl.glCreateProgram();
final String progIdStr = "[" + program + "]";
log = CoreLogger.getCoreLogger(getClass().getName() + progIdStr);
log.setLoggingPrefix(progIdStr);
gl.checkGLError("glCreateProgram");
}
public int vertexShader(final String filename) {
return vertexShader(filename, getStream(filename));
}
public int vertexShader(final File file) throws FileNotFoundException {
return vertexShader(file.getName(), getStream(file));
}
public int vertexShader(final String streamName, final InputStream... sources) {
return vertexShaderFromStream(streamName, sources);
}
public void vertexShader(final int shaderId, final String filename) {
vertexShader(shaderId, filename, getStream(filename));
}
public void vertexShader(final int shaderId, final File file) throws FileNotFoundException {
vertexShader(shaderId, file.getName(), getStream(file));
}
public void vertexShader(final int shaderId, final String streamName, final InputStream source) {
prepareShader(shaderId, streamName, source);
}
public void geometryShader(final int shaderId, final String filename) {
geometryShader(shaderId, filename, getStream(filename));
}
public int geometryShader(final String filename) {
return geometryShaderFromStream(filename, getStream(filename));
}
public int geometryShader(final File file) throws FileNotFoundException {
return geometryShader(file.getName(), getStream(file));
}
public int geometryShader(final File file, final InputStream... inputStreams) throws FileNotFoundException {
final InputStream[] sources = new InputStream[inputStreams.length + 1];
System.arraycopy(inputStreams, 0, sources, 0, inputStreams.length);
sources[sources.length - 1] = getStream(file);
return geometryShader(file.getName(), sources);
}
public int geometryShader(final String streamName, final InputStream... inputStreams) throws FileNotFoundException {
return geometryShaderFromStream(streamName, inputStreams);
}
public void geometryShader(final int shaderId, final String streamName, final InputStream source) {
prepareShader(shaderId, streamName, source);
}
public void geometryShader(final int shaderId, final File file) throws FileNotFoundException {
geometryShader(shaderId, file.getName(), getStream(file));
}
public int fragmentShader(final String filename) {
return fragmentShader(filename, getStream(filename));
}
public int fragmentShader(final File file) throws FileNotFoundException {
return fragmentShaderFromStream(file.getName(), getStream(file));
}
public int fragmentShader(final String streamName, final InputStream... inputStreams) {
return fragmentShaderFromStream(streamName, inputStreams);
}
public void fragmentShader(final int shaderId, final String filename) {
fragmentShader(shaderId, filename, getStream(filename));
}
public void fragmentShader(final int shaderId, final File file) throws FileNotFoundException {
fragmentShader(shaderId, file.getName(), getStream(file));
}
public void fragmentShader(final int shaderId, final String streamName, final InputStream source) {
prepareShader(shaderId, streamName, source);
}
private int vertexShaderFromStream(final String streamName, final InputStream... sources) {
final int shaderId = gl.glCreateShader(gl.GL_VERTEX_SHADER());
gl.checkGLError("glCreateShader(GL_VERTEX_SHADER)");
prepareShader(shaderId, streamName, sources);
gl.glAttachShader(program, shaderId);
gl.checkGLError("glAttachShader");
return shaderId;
}
private int geometryShaderFromStream(final String streamName, final InputStream... sources) {
final int shaderId = gl.glCreateShader(gl.GL_GEOMETRY_SHADER());
gl.checkGLError("glCreateShader(GL_GEOMETRY_SHADER)");
prepareShader(shaderId, streamName, sources);
gl.glAttachShader(program, shaderId);
gl.checkGLError("glAttachShader");
return shaderId;
}
private int fragmentShaderFromStream(final String streamName, final InputStream... sources) {
final int shaderId = gl.glCreateShader(gl.GL_FRAGMENT_SHADER());
gl.checkGLError("glCreateShader(GL_FRAGMENT_SHADER)");
prepareShader(shaderId, streamName, sources);
gl.glAttachShader(program, shaderId);
gl.checkGLError("glAttachShader");
return shaderId;
}
public void link() {
for (int i = 0; i < attributes.length; i++) {
gl.glBindAttribLocation(program, i, attributes[i]);
log.checkGLError(gl, "glBindAttribLocation ({})", attributes[i]);
}
gl.glLinkProgram(program);
gl.checkGLError("glLinkProgram");
final IntBuffer params = gl.getUtil().createIntBuffer(1);
gl.glGetProgramiv(program, gl.GL_LINK_STATUS(), params);
if (params.get(0) != gl.GL_TRUE()) {
log.warn("link error: {}", gl.glGetProgramInfoLog(program));
gl.checkGLError("glGetProgramInfoLog");
}
gl.checkGLError("glGetProgram");
}
public void setUniformi(final String name, final int... values) {
final int loc = getLocation(name);
switch (values.length) {
case 1:
gl.glUniform1i(loc, values[0]);
gl.checkGLError("glUniform1i");
break;
case 2:
gl.glUniform2i(loc, values[0], values[1]);
gl.checkGLError("glUniform2i");
break;
case 3:
gl.glUniform3i(loc, values[0], values[1], values[2]);
gl.checkGLError("glUniform3i");
break;
case 4:
gl.glUniform4i(loc, values[0], values[1], values[2], values[3]);
gl.checkGLError("glUniform4i");
break;
default:
throw new IllegalArgumentException(String.format("Unsupported number of value arguments: %d", values.length));
}
}
public void setUniformf(final String name, final float... values) {
final int loc = getLocation(name);
switch (values.length) {
case 1:
gl.glUniform1f(loc, values[0]);
gl.checkGLError("glUniform1f");
break;
case 2:
gl.glUniform2f(loc, values[0], values[1]);
gl.checkGLError("glUniform2f");
break;
case 3:
gl.glUniform3f(loc, values[0], values[1], values[2]);
gl.checkGLError("glUniform3f");
break;
case 4:
gl.glUniform4f(loc, values[0], values[1], values[2], values[3]);
gl.checkGLError("glUniform4f");
break;
default:
throw new IllegalArgumentException("Unsupported number of value arguments: " + values.length);
}
}
public void setUniformiv(final String name, final int componentNum, final int... values) {
final IntBuffer buff = gl.getUtil().createIntBuffer(values.length);
buff.put(values);
buff.flip();
setUniformiv(name, componentNum, buff);
}
public void setUniformiv(final String name, final int componentNum, final IntBuffer values) {
final int loc = getLocation(name);
switch (componentNum) {
case 1:
gl.glUniform1iv(loc, values);
gl.checkGLError("glUniform1iv");
break;
case 2:
gl.glUniform2iv(loc, values);
gl.checkGLError("glUniform2iv");
break;
case 3:
gl.glUniform3iv(loc, values);
gl.checkGLError("glUniform3iv");
break;
case 4:
gl.glUniform4iv(loc, values);
gl.checkGLError("glUniform4iv");
break;
default:
throw new IllegalArgumentException("Unsupported component count value: " + componentNum);
}
}
public void setUniformfv(final String name, final int componentNum, final float... values) {
final FloatBuffer buff = gl.getUtil().createFloatBuffer(values.length);
buff.put(values);
buff.flip();
setUniformfv(name, componentNum, buff);
}
public void setUniformfv(final String name, final int componentNum, final FloatBuffer values) {
final int loc = getLocation(name);
switch (componentNum) {
case 1:
gl.glUniform1fv(loc, values);
gl.checkGLError("glUniform1fv");
break;
case 2:
gl.glUniform2fv(loc, values);
gl.checkGLError("glUniform2fv");
break;
case 3:
gl.glUniform3fv(loc, values);
gl.checkGLError("glUniform3fv");
break;
case 4:
gl.glUniform4fv(loc, values);
gl.checkGLError("glUniform4fv");
break;
default:
throw new IllegalArgumentException("Unsupported component count value: " + componentNum);
}
}
public void setUniformMatrix(final String name, final int componentNum, final float... values) {
if (matBuffer == null) matBuffer = gl.getUtil().createFloatBuffer(16);
matBuffer.clear();
matBuffer.put(values);
matBuffer.flip();
setUniformMatrix(name, componentNum, matBuffer);
}
/**
* Set uniform matrix of dimension 'n x n' where n = componentNum
*
* @param name
* name of the GLSL uniform variable
* @param componentNum
* matrix dimension 'n'
* @param values
*/
public void setUniformMatrix(final String name, final int componentNum, final FloatBuffer values) {
setUniformMatrix(name, componentNum, componentNum, values);
}
/**
* Set a uniform matrix of dimension 'n x m'.
*
* @param name
* name of the GLSL uniform variable
* @param n
* number of columns in the matrix
* @param m
* number of rows in the matrix
* @param values
*/
public void setUniformMatrix(final String name, final int n, final int m, final FloatBuffer values) {
final int loc = getLocation(name);
final UniformMatrixType type = UniformMatrixType.typeFor(n, m);
switch (type) {
case M2x2:
gl.glUniformMatrix2(loc, false, values);
gl.checkGLError("glUniformMatrix2");
break;
case M2x3:
gl.glUniformMatrix2x3(loc, false, values);
gl.checkGLError("glUniformMatrix2x3");
break;
case M2x4:
gl.glUniformMatrix2x4(loc, false, values);
gl.checkGLError("glUniformMatrix2x4");
break;
case M3x2:
gl.glUniformMatrix3x2(loc, false, values);
gl.checkGLError("glUniformMatrix3x2");
break;
case M3x3:
gl.glUniformMatrix3(loc, false, values);
gl.checkGLError("glUniformMatrix3");
break;
case M3x4:
gl.glUniformMatrix3x4(loc, false, values);
gl.checkGLError("glUniformMatrix3x4");
break;
case M4x2:
gl.glUniformMatrix4x2(loc, false, values);
gl.checkGLError("glUniformMatrix4x2");
break;
case M4x3:
gl.glUniformMatrix4x3(loc, false, values);
gl.checkGLError("glUniformMatrix4x3");
break;
case M4x4:
gl.glUniformMatrix4(loc, false, values);
gl.checkGLError("glUniformMatrix4");
break;
default:
throw new IllegalArgumentException(String.format("Unsupported dimension values for uniform matrix: %dx%d", n, m));
}
}
public int getAttribLocation(final String name) {
final int result = gl.glGetAttribLocation(program, name);
gl.checkGLError("glGetAttribLocation");
return result;
}
public void bindAttribLocation(final String name, final int index) {
gl.glBindAttribLocation(program, index, name);
gl.checkGLError("glBindAttribLocation");
}
public Map<String, UniformBlockInfo> getUniformIndices(final String... uniformNames) {
final Map<String, UniformBlockInfo> result = new Hashtable<String, UniformBlockInfo>();
final IntBuffer intBuffer = gl.getUtil().createIntBuffer(uniformNames.length);
gl.glGetUniformIndices(program, uniformNames, intBuffer);
final IntBuffer uniformOffsets = gl.getUtil().createIntBuffer(uniformNames.length);
gl.glGetActiveUniforms(program, uniformNames.length, intBuffer, gl.GL_UNIFORM_OFFSET(), uniformOffsets);
final IntBuffer arrayStrides = gl.getUtil().createIntBuffer(uniformNames.length);
gl.glGetActiveUniforms(program, uniformNames.length, intBuffer, gl.GL_UNIFORM_ARRAY_STRIDE(), arrayStrides);
final IntBuffer matrixStrides = gl.getUtil().createIntBuffer(uniformNames.length);
gl.glGetActiveUniforms(program, uniformNames.length, intBuffer, gl.GL_UNIFORM_MATRIX_STRIDE(), matrixStrides);
gl.checkGLError("getUniformIndices");
for (int i = 0; i < uniformNames.length; i++) {
final UniformBlockInfo blockInfo = new UniformBlockInfo();
blockInfo.name = uniformNames[i];
blockInfo.offset = uniformOffsets.get(i);
blockInfo.arrayStride = arrayStrides.get(i);
blockInfo.matrixStride = matrixStrides.get(i);
result.put(blockInfo.name, blockInfo);
}
return result;
}
public void uniformBlockBinding(final String name, final int uniformBlockBinding) {
final int uniformBlockIndex = gl.glGetUniformBlockIndex(program, name);
gl.checkGLError("glGetUniformBlockIndex");
gl.glUniformBlockBinding(program, uniformBlockIndex, uniformBlockBinding);
gl.checkGLError("glUniformBlockBinding");
}
public void activate() {
gl.glUseProgram(program);
gl.checkGLError("glUseProgram");
}
private int registerParameter(final String name) {
final int location = getUniform(name);
parameter.put(name, location);
return location;
}
private int getLocation(final String name) {
final Integer value = parameter.get(name);
if (value == null) {
return registerParameter(name);
}
return value;
}
private int getUniform(final String uniformName) {
final int result = gl.glGetUniformLocation(program, uniformName);
log.checkGLError(gl, "glGetUniformLocation for [{}] failed", uniformName);
log.fine("glUniformLocation for [{}] = [{}]", uniformName, result);
return result;
}
private void prepareShader(final int shaderId, final String name, final InputStream... sources) {
try {
gl.glShaderSource(shaderId, loadShader(sources));
gl.checkGLError("glShaderSource");
} catch (final IOException e) {
throw new CoreGLException(e);
}
gl.glCompileShader(shaderId);
gl.checkGLError("glCompileShader");
final IntBuffer ret = gl.getUtil().createIntBuffer(1);
gl.glGetShaderiv(shaderId, gl.GL_COMPILE_STATUS(), ret);
if (ret.get(0) == gl.GL_FALSE()) {
log.warn("'{}' compile error: {}", name, gl.glGetShaderInfoLog(shaderId));
}
printLogInfo(shaderId);
gl.checkGLError(String.valueOf(shaderId));
}
private String loadShader(final InputStream... sources) throws IOException {
final StringBuilder srcbuff = new StringBuilder();
for (final InputStream source : sources) {
final InputStreamReader streamReader = new InputStreamReader(source);
final BufferedReader buffReader = new BufferedReader(streamReader);
String nextLine;
while ((nextLine = buffReader.readLine()) != null) {
srcbuff.append(nextLine).append('\n');
}
buffReader.close();
}
return srcbuff.toString();
}
private void printLogInfo(final int obj) {
final String logInfoMsg = gl.glGetShaderInfoLog(obj);
gl.checkGLError("glGetShaderInfoLog");
if (!logInfoMsg.isEmpty()) {
log.info("Info log:\n{}", logInfoMsg);
}
gl.checkGLError("printLogInfo");
}
private InputStream getStream(final File file) throws FileNotFoundException {
log.fine("loading shader file [{}]", file);
return new FileInputStream(file);
}
private InputStream getStream(final String filename) {
return Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
}
/**
* Internal enum for representing the 9 possible GLSL matrix types and mapping
* them to a single key formed from the 'n x m' dimensions.
*
* @author Brian Groenke (groenke.5@osu.edu)
*/
private enum UniformMatrixType {
M2x2(2, 2),
M2x3(2, 3),
M2x4(2, 4),
M3x3(3, 3),
M3x2(3, 2),
M3x4(3, 4),
M4x4(4, 4),
M4x2(4, 2),
M4x3(4, 3),
UNSUPPORTED(0, 0);
private final static UniformMatrixType[] matDimsToType;
final int n, m;
UniformMatrixType(final int n, final int m) {
this.n = n;
this.m = m;
}
static {
matDimsToType = new UniformMatrixType[keyFor(4, 4) + 1];
for (final UniformMatrixType value : values()) {
int key = keyFor(value.n, value.m);
if (key >= 0 && key < matDimsToType.length) {
matDimsToType[key] = value;
}
}
}
private static UniformMatrixType typeFor(final int n, final int m) {
int key = keyFor(n, m);
if (key >= 0 && key < matDimsToType.length) {
return matDimsToType[key];
}
return UNSUPPORTED;
}
private static int keyFor(final int n, final int m) {
return (n - 2) * 3 + m;
}
}
} |
package edu.cuny.citytech.defaultrefactoring.core.refactorings;
import static org.eclipse.jdt.ui.JavaElementLabels.ALL_DEFAULT;
import static org.eclipse.jdt.ui.JavaElementLabels.ALL_FULLY_QUALIFIED;
import static org.eclipse.jdt.ui.JavaElementLabels.getElementLabel;
import static org.eclipse.jdt.ui.JavaElementLabels.getTextLabel;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiFunction;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.jdt.core.Flags;
import org.eclipse.jdt.core.IAnnotatable;
import org.eclipse.jdt.core.IAnnotation;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IField;
import org.eclipse.jdt.core.IInitializer;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.ILocalVariable;
import org.eclipse.jdt.core.IMember;
import org.eclipse.jdt.core.IMemberValuePair;
import org.eclipse.jdt.core.IMethod;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.ITypeHierarchy;
import org.eclipse.jdt.core.ITypeRoot;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.Block;
import org.eclipse.jdt.core.dom.BodyDeclaration;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.IExtendedModifier;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.Modifier;
import org.eclipse.jdt.core.dom.Modifier.ModifierKeyword;
import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jdt.core.dom.rewrite.ListRewrite;
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
import org.eclipse.jdt.internal.corext.refactoring.RefactoringCoreMessages;
import org.eclipse.jdt.internal.corext.refactoring.base.JavaStatusContext;
import org.eclipse.jdt.internal.corext.refactoring.changes.DynamicValidationRefactoringChange;
import org.eclipse.jdt.internal.corext.refactoring.structure.ASTNodeSearchUtil;
import org.eclipse.jdt.internal.corext.refactoring.structure.CompilationUnitRewrite;
import org.eclipse.jdt.internal.corext.refactoring.structure.ReferenceFinderUtil;
import org.eclipse.jdt.internal.corext.refactoring.util.RefactoringASTParser;
import org.eclipse.jdt.internal.corext.refactoring.util.TextEditBasedChangeManager;
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
import org.eclipse.jdt.internal.corext.util.JdtFlags;
import org.eclipse.jdt.internal.ui.JavaPlugin;
import org.eclipse.jdt.ui.JavaElementLabels;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.GroupCategory;
import org.eclipse.ltk.core.refactoring.GroupCategorySet;
import org.eclipse.ltk.core.refactoring.NullChange;
import org.eclipse.ltk.core.refactoring.RefactoringDescriptor;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.RefactoringStatusContext;
import org.eclipse.ltk.core.refactoring.RefactoringStatusEntry;
import org.eclipse.ltk.core.refactoring.TextChange;
import org.eclipse.ltk.core.refactoring.participants.CheckConditionsContext;
import org.eclipse.ltk.core.refactoring.participants.RefactoringParticipant;
import org.eclipse.ltk.core.refactoring.participants.RefactoringProcessor;
import org.eclipse.ltk.core.refactoring.participants.SharableParticipants;
import org.eclipse.text.edits.TextEdit;
import org.osgi.framework.FrameworkUtil;
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import edu.cuny.citytech.defaultrefactoring.core.descriptors.MigrateSkeletalImplementationToInterfaceRefactoringDescriptor;
import edu.cuny.citytech.defaultrefactoring.core.messages.Messages;
import edu.cuny.citytech.defaultrefactoring.core.utils.RefactoringAvailabilityTester;
// TODO: Are we checking the target interface? I think that the target interface should be completely empty for now.
/**
* The activator class controls the plug-in life cycle
*
* @author <a href="mailto:rkhatchadourian@citytech.cuny.edu">Raffi
* Khatchadourian</a>
*/
@SuppressWarnings({ "restriction" })
public class MigrateSkeletalImplementationToInterfaceRefactoringProcessor extends RefactoringProcessor {
private Set<IMethod> sourceMethods = new HashSet<>();
private Set<IMethod> unmigratableMethods = new HashSet<>();
private static final String FUNCTIONAL_INTERFACE_ANNOTATION_NAME = "FunctionalInterface";
private Map<CompilationUnit, ASTRewrite> compilationUnitToASTRewriteMap = new HashMap<>();
private Map<ITypeRoot, CompilationUnit> typeRootToCompilationUnitMap = new HashMap<>();
@SuppressWarnings("unused")
private static final GroupCategorySet SET_MIGRATE_METHOD_IMPLEMENTATION_TO_INTERFACE = new GroupCategorySet(
new GroupCategory("edu.cuny.citytech.defaultrefactoring", //$NON-NLS-1$
Messages.CategoryName, Messages.CategoryDescription));
private Map<IMethod, IMethod> sourceMethodToTargetMethodMap = new HashMap<>();
/** The code generation settings, or <code>null</code> */
protected CodeGenerationSettings settings;
/** Does the refactoring use a working copy layer? */
protected final boolean layer;
private static Table<IMethod, IType, IMethod> sourceMethodTargetInterfaceTargetMethodTable = HashBasedTable
.create();
/**
* Creates a new refactoring with the given methods to refactor.
*
* @param methods
* The methods to refactor.
* @throws JavaModelException
*/
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor(final IMethod[] methods,
final CodeGenerationSettings settings, boolean layer, Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
this.settings = settings;
this.layer = layer;
this.sourceMethods = new HashSet<>(Arrays.asList(methods));
monitor.ifPresent(m -> m.beginTask("Finding target methods ...", this.sourceMethods.size()));
for (IMethod method : this.sourceMethods) {
this.sourceMethodToTargetMethodMap.put(method, getTargetMethod(method, monitor));
monitor.ifPresent(m -> m.worked(1));
}
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor(final IMethod[] methods,
final CodeGenerationSettings settings, Optional<IProgressMonitor> monitor) throws JavaModelException {
this(methods, settings, false, monitor);
}
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor(Optional<IProgressMonitor> monitor)
throws JavaModelException {
this(null, null, false, monitor);
}
public MigrateSkeletalImplementationToInterfaceRefactoringProcessor() throws JavaModelException {
this(null, null, false, Optional.empty());
}
/**
* {@inheritDoc}
*/
@Override
public Object[] getElements() {
Set<IMethod> difference = new HashSet<>(this.getSourceMethods());
difference.removeAll(this.getUnmigratableMethods());
return difference.toArray();
}
@Override
public RefactoringStatus checkInitialConditions(IProgressMonitor pm)
throws CoreException, OperationCanceledException {
try {
if (this.getSourceMethods().isEmpty())
return RefactoringStatus.createFatalErrorStatus(Messages.MethodsNotSpecified);
else {
RefactoringStatus status = new RefactoringStatus();
pm.beginTask(Messages.CheckingPreconditions, this.getSourceMethods().size());
for (IMethod method : this.getSourceMethods()) {
status.merge(checkDeclaringType(method, Optional.of(new SubProgressMonitor(pm, 0))));
status.merge(
checkCandidateDestinationInterfaces(method, Optional.of(new SubProgressMonitor(pm, 0))));
// FIXME: Repeated.
// TODO: Also, does not remove the method if there is an
// error.
status.merge(checkExistence(method, Messages.MethodDoesNotExist));
pm.worked(1);
}
return status;
}
} catch (Exception e) {
JavaPlugin.log(e);
throw e;
} finally {
pm.done();
}
}
protected RefactoringStatus checkDestinationInterfaceTargetMethods(IMethod sourceMethod) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
logInfo("Checking destination interface target methods...");
// Ensure that target methods are not already default methods.
// For each method to move, add a warning if the associated target
// method is already default.
IMethod targetMethod = this.getSourceMethodToTargetMethodMap().get(sourceMethod);
if (targetMethod != null) {
int targetMethodFlags = targetMethod.getFlags();
if (Flags.isDefaultMethod(targetMethodFlags)) {
RefactoringStatusEntry entry = addError(status, Messages.TargetMethodIsAlreadyDefault, targetMethod);
addUnmigratableMethod(sourceMethod, entry);
}
}
return status;
}
protected RefactoringStatus checkDestinationInterfaceOnlyDeclaresTargetMethods(IMethod sourceMethod)
throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
// get the destination interface.
IType destinationInterface = this.getSourceMethodToTargetMethodMap().get(sourceMethod).getDeclaringType();
// get the methods declared by the destination interface.
Set<IMethod> destinationInterfaceMethodsSet = new HashSet<>(Arrays.asList(destinationInterface.getMethods()));
// get the target methods that are declared by the destination
// interface.
Set<IMethod> targetMethodDeclaredByDestinationInterfaceSet = this.getSourceMethodToTargetMethodMap().values()
.parallelStream().filter(Objects::nonNull)
.filter(m -> m.getDeclaringType().equals(destinationInterface)).collect(Collectors.toSet());
// TODO: For now, the target interface must only contain the target
// methods.
if (!destinationInterfaceMethodsSet.equals(targetMethodDeclaredByDestinationInterfaceSet)) {
RefactoringStatusEntry error = addError(status,
Messages.DestinationInterfaceMustOnlyDeclareTheMethodToMigrate, destinationInterface);
addUnmigratableMethod(sourceMethod, error);
}
return status;
}
protected RefactoringStatus checkDestinationInterfaces(Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
RefactoringStatus status = new RefactoringStatus();
monitor.ifPresent(m -> m.beginTask("Checking destination interfaces ...", this.getSourceMethods().size()));
for (IMethod sourceMethod : this.getSourceMethods()) {
// TODO
final Optional<IType> targetInterface = this.getDestinationInterface(sourceMethod);
// Can't be null.
if (!targetInterface.isPresent()) {
RefactoringStatusEntry error = addError(status, Messages.NoDestinationInterface);
addUnmigratableMethod(sourceMethod, error);
return status;
}
// Must be a pure interface.
if (!isPureInterface(targetInterface.get())) {
RefactoringStatusEntry error = addError(status, Messages.DestinationTypeMustBePureInterface,
targetInterface.get());
addUnmigratableMethod(sourceMethod, error);
}
// Make sure it exists.
RefactoringStatus existence = checkExistence(targetInterface.get(),
Messages.DestinationInterfaceDoesNotExist);
status.merge(existence);
if (!existence.isOK())
addUnmigratableMethod(sourceMethod, existence.getEntryWithHighestSeverity());
// Make sure we can write to it.
RefactoringStatus writabilitiy = checkWritabilitiy(targetInterface.get(),
Messages.DestinationInterfaceNotWritable);
status.merge(writabilitiy);
if (!writabilitiy.isOK())
addUnmigratableMethod(sourceMethod, writabilitiy.getEntryWithHighestSeverity());
// Make sure it doesn't have compilation errors.
RefactoringStatus structure = checkStructure(targetInterface.get());
status.merge(structure);
if (!structure.isOK())
addUnmigratableMethod(sourceMethod, structure.getEntryWithHighestSeverity());
// TODO: For now, no annotated target interfaces.
if (targetInterface.get().getAnnotations().length != 0) {
RefactoringStatusEntry error = addError(status, Messages.DestinationInterfaceHasAnnotations,
targetInterface.get());
addUnmigratableMethod(sourceMethod, error);
}
// #35: The target interface should not be a
// @FunctionalInterface.
if (isInterfaceFunctional(targetInterface.get())) {
RefactoringStatusEntry error = addError(status, Messages.DestinationInterfaceIsFunctional,
targetInterface.get());
addUnmigratableMethod(sourceMethod, error);
}
// TODO: For now, only top-level types.
if (targetInterface.get().getDeclaringType() != null) {
RefactoringStatusEntry error = addError(status, Messages.DestinationInterfaceIsNotTopLevel,
targetInterface.get());
addUnmigratableMethod(sourceMethod, error);
}
// TODO: For now, no fields.
if (targetInterface.get().getFields().length != 0) {
RefactoringStatusEntry error = addError(status, Messages.DestinationInterfaceDeclaresFields,
targetInterface.get());
addUnmigratableMethod(sourceMethod, error);
}
// TODO: For now, no super interfaces.
if (targetInterface.get().getSuperInterfaceNames().length != 0) {
RefactoringStatusEntry error = addError(status, Messages.DestinationInterfaceExtendsInterface,
targetInterface.get());
addUnmigratableMethod(sourceMethod, error);
}
// TODO: For now, no type parameters.
if (targetInterface.get().getTypeParameters().length != 0) {
RefactoringStatusEntry error = addError(status, Messages.DestinationInterfaceDeclaresTypeParameters,
targetInterface.get());
addUnmigratableMethod(sourceMethod, error);
}
// TODO: For now, no member types.
if (targetInterface.get().getTypes().length != 0) {
RefactoringStatusEntry error = addError(status, Messages.DestinationInterfaceDeclaresMemberTypes,
targetInterface.get());
addUnmigratableMethod(sourceMethod, error);
}
// TODO: For now, no member interfaces.
if (targetInterface.get().isMember()) {
RefactoringStatusEntry error = addError(status, Messages.DestinationInterfaceIsMember,
targetInterface.get());
addUnmigratableMethod(sourceMethod, error);
}
// Can't be strictfp if all the methods to be migrated aren't
// also strictfp
if (Flags.isStrictfp(targetInterface.get().getFlags())
&& !allMethodsToMoveInTypeAreStrictFP(sourceMethod.getDeclaringType())) {
RefactoringStatusEntry error = addError(status, Messages.DestinationInterfaceIsStrictFP,
targetInterface.get());
addUnmigratableMethod(sourceMethod, error);
}
status.merge(checkDestinationInterfaceHierarchy(sourceMethod,
monitor.map(m -> new SubProgressMonitor(m, 1))));
status.merge(checkDestinationInterfaceTargetMethods(sourceMethod));
monitor.ifPresent(m -> m.worked(1));
}
return status;
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
protected IType[] getTypesReferencedInMovedMembers(IMethod sourceMethod, final Optional<IProgressMonitor> monitor)
throws JavaModelException {
// TODO: Cache this result.
final IType[] types = ReferenceFinderUtil.getTypesReferencedIn(new IJavaElement[] { sourceMethod },
monitor.orElseGet(NullProgressMonitor::new));
final List<IType> result = new ArrayList<IType>(types.length);
final List<IMember> members = Arrays.asList(new IMember[] { sourceMethod });
for (int index = 0; index < types.length; index++) {
if (!members.contains(types[index]) && !types[index].equals(sourceMethod.getDeclaringType()))
result.add(types[index]);
}
return result.toArray(new IType[result.size()]);
}
protected boolean canBeAccessedFrom(IMethod sourceMethod, final IMember member, final IType target,
final ITypeHierarchy hierarchy) throws JavaModelException {
Assert.isTrue(!(member instanceof IInitializer));
if (member.exists()) {
if (target.equals(member.getDeclaringType()))
return true;
if (target.equals(member))
return true;
if (member.getDeclaringType() == null) {
if (!(member instanceof IType))
return false;
if (JdtFlags.isPublic(member))
return true;
if (!JdtFlags.isPackageVisible(member))
return false;
if (JavaModelUtil.isSamePackage(((IType) member).getPackageFragment(), target.getPackageFragment()))
return true;
final IType type = member.getDeclaringType();
if (type != null)
return hierarchy.contains(type);
return false;
}
final IType declaringType = member.getDeclaringType();
if (!canBeAccessedFrom(sourceMethod, declaringType, target, hierarchy))
return false;
if (declaringType.equals(sourceMethod.getDeclaringType()))
return false;
return true;
}
return false;
}
private RefactoringStatus checkAccessedTypes(IMethod sourceMethod, final Optional<IProgressMonitor> monitor,
final ITypeHierarchy hierarchy) throws JavaModelException {
final RefactoringStatus result = new RefactoringStatus();
final IType[] accessedTypes = getTypesReferencedInMovedMembers(sourceMethod, monitor);
final IType destination = getDestinationInterface(sourceMethod).get();
final List<IMember> pulledUpList = Arrays.asList(new IMember[] { sourceMethod });
for (int index = 0; index < accessedTypes.length; index++) {
final IType type = accessedTypes[index];
if (!type.exists())
continue;
if (!canBeAccessedFrom(sourceMethod, type, destination, hierarchy) && !pulledUpList.contains(type)) {
final String message = org.eclipse.jdt.internal.corext.util.Messages
.format(RefactoringCoreMessages.PullUpRefactoring_type_not_accessible,
new String[] { JavaElementLabels.getTextLabel(type,
JavaElementLabels.ALL_FULLY_QUALIFIED),
JavaElementLabels.getTextLabel(destination, JavaElementLabels.ALL_FULLY_QUALIFIED) });
result.addError(message, JavaStatusContext.create(type));
}
}
monitor.ifPresent(IProgressMonitor::done);
return result;
}
// skipped super classes are those declared in the hierarchy between the
// declaring type of the selected members
// and the target type
private Set<IType> getSkippedSuperTypes(IMethod sourceMethod, final Optional<IProgressMonitor> monitor)
throws JavaModelException {
// TODO: Cache this?
Set<IType> skippedSuperTypes = new HashSet<>();
monitor.ifPresent(m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking, 1));
try {
final ITypeHierarchy hierarchy = getDestinationInterfaceHierarchy(sourceMethod,
monitor.map(m -> new SubProgressMonitor(m, 1)));
IType current = hierarchy.getSuperclass(sourceMethod.getDeclaringType());
while (current != null && !current.equals(getDestinationInterface(sourceMethod).get())) {
skippedSuperTypes.add(current);
current = hierarchy.getSuperclass(current);
}
return skippedSuperTypes;
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
private RefactoringStatus checkAccessedFields(IMethod sourceMethod, final Optional<IProgressMonitor> monitor,
final ITypeHierarchy hierarchy) throws JavaModelException {
monitor.ifPresent(m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking_referenced_elements, 2));
final RefactoringStatus result = new RefactoringStatus();
final List<IMember> pulledUpList = Arrays.asList(new IMember[] { sourceMethod });
final IField[] accessedFields = ReferenceFinderUtil.getFieldsReferencedIn(new IJavaElement[] { sourceMethod },
new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), 1));
final IType destination = getDestinationInterface(sourceMethod).get();
for (int i = 0; i < accessedFields.length; i++) {
final IField field = accessedFields[i];
if (!field.exists())
continue;
boolean isAccessible = pulledUpList.contains(field)
|| canBeAccessedFrom(sourceMethod, field, destination, hierarchy) || Flags.isEnum(field.getFlags());
if (!isAccessible) {
final String message = org.eclipse.jdt.internal.corext.util.Messages
.format(RefactoringCoreMessages.PullUpRefactoring_field_not_accessible,
new String[] { JavaElementLabels.getTextLabel(field,
JavaElementLabels.ALL_FULLY_QUALIFIED),
JavaElementLabels.getTextLabel(destination, JavaElementLabels.ALL_FULLY_QUALIFIED) });
result.addError(message, JavaStatusContext.create(field));
} else if (getSkippedSuperTypes(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1)))
.contains(field.getDeclaringType())) {
final String message = org.eclipse.jdt.internal.corext.util.Messages
.format(RefactoringCoreMessages.PullUpRefactoring_field_cannot_be_accessed,
new String[] { JavaElementLabels.getTextLabel(field,
JavaElementLabels.ALL_FULLY_QUALIFIED),
JavaElementLabels.getTextLabel(destination, JavaElementLabels.ALL_FULLY_QUALIFIED) });
result.addError(message, JavaStatusContext.create(field));
}
}
monitor.ifPresent(IProgressMonitor::done);
return result;
}
private RefactoringStatus checkAccessedMethods(IMethod sourceMethod, final Optional<IProgressMonitor> monitor,
final ITypeHierarchy hierarchy) throws JavaModelException {
monitor.ifPresent(m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking_referenced_elements, 2));
final RefactoringStatus result = new RefactoringStatus();
final List<IMember> pulledUpList = Arrays.asList(new IMember[] { sourceMethod });
final IMethod[] accessedMethods = ReferenceFinderUtil.getMethodsReferencedIn(
new IJavaElement[] { sourceMethod },
new SubProgressMonitor(monitor.orElseGet(NullProgressMonitor::new), 1));
final IType destination = getDestinationInterface(sourceMethod).get();
for (int index = 0; index < accessedMethods.length; index++) {
final IMethod method = accessedMethods[index];
if (!method.exists())
continue;
boolean isAccessible = pulledUpList.contains(method)
|| canBeAccessedFrom(sourceMethod, method, destination, hierarchy);
if (!isAccessible) {
final String message = org.eclipse.jdt.internal.corext.util.Messages
.format(RefactoringCoreMessages.PullUpRefactoring_method_not_accessible,
new String[] { JavaElementLabels.getTextLabel(method,
JavaElementLabels.ALL_FULLY_QUALIFIED),
JavaElementLabels.getTextLabel(destination, JavaElementLabels.ALL_FULLY_QUALIFIED) });
result.addError(message, JavaStatusContext.create(method));
} else if (getSkippedSuperTypes(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1)))
.contains(method.getDeclaringType())) {
final String[] keys = { JavaElementLabels.getTextLabel(method, JavaElementLabels.ALL_FULLY_QUALIFIED),
JavaElementLabels.getTextLabel(destination, JavaElementLabels.ALL_FULLY_QUALIFIED) };
final String message = org.eclipse.jdt.internal.corext.util.Messages
.format(RefactoringCoreMessages.PullUpRefactoring_method_cannot_be_accessed, keys);
result.addError(message, JavaStatusContext.create(method));
}
}
monitor.ifPresent(IProgressMonitor::done);
return result;
}
private RefactoringStatus checkAccesses(IMethod sourceMethod, final Optional<IProgressMonitor> monitor)
throws JavaModelException {
final RefactoringStatus result = new RefactoringStatus();
try {
monitor.ifPresent(
m -> m.beginTask(RefactoringCoreMessages.PullUpRefactoring_checking_referenced_elements, 4));
final ITypeHierarchy hierarchy = getSuperTypeHierarchy(getDestinationInterface(sourceMethod).get(),
monitor.map(m -> new SubProgressMonitor(m, 1)));
result.merge(checkAccessedTypes(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1)), hierarchy));
result.merge(checkAccessedFields(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1)), hierarchy));
result.merge(checkAccessedMethods(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1)), hierarchy));
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
return result;
}
private boolean allMethodsToMoveInTypeAreStrictFP(IType type) throws JavaModelException {
for (Iterator<IMethod> iterator = this.getSourceMethods().iterator(); iterator.hasNext();) {
IMethod method = iterator.next();
if (method.getDeclaringType().equals(type) && !Flags.isStrictfp(method.getFlags()))
return false;
}
return true;
}
private static boolean isInterfaceFunctional(final IType anInterface) throws JavaModelException {
// TODO:
return Stream.of(anInterface.getAnnotations()).parallel().map(IAnnotation::getElementName)
.anyMatch(s -> s.contains(FUNCTIONAL_INTERFACE_ANNOTATION_NAME));
}
protected RefactoringStatus checkDestinationInterfaceHierarchy(IMethod sourceMethod,
Optional<IProgressMonitor> monitor) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
monitor.ifPresent(m -> m.subTask("Checking destination interface hierarchy..."));
IType destinationInterface = this.getSourceMethodToTargetMethodMap().get(sourceMethod).getDeclaringType();
final ITypeHierarchy hierarchy = this.getTypeHierarchy(destinationInterface,
monitor.map(m -> new SubProgressMonitor(m, 1)));
status.merge(checkValidClassesInHierarchy(sourceMethod, hierarchy,
Messages.DestinationInterfaceHierarchyContainsInvalidClass));
status.merge(checkValidInterfacesInHierarchy(sourceMethod, hierarchy,
Messages.DestinationInterfaceHierarchyContainsInvalidInterfaces));
status.merge(checkValidSubtypes(sourceMethod, hierarchy));
// TODO: For now, no super interfaces.
if (hierarchy.getAllSuperInterfaces(destinationInterface).length > 0) {
RefactoringStatusEntry error = addError(status,
Messages.DestinationInterfaceHierarchyContainsSuperInterface, destinationInterface);
addUnmigratableMethod(sourceMethod, error);
}
// TODO: For now, no extending interfaces.
if (hierarchy.getExtendingInterfaces(destinationInterface).length > 0) {
RefactoringStatusEntry error = addError(status, Messages.DestinationInterfaceHasExtendingInterface,
destinationInterface);
addUnmigratableMethod(sourceMethod, error);
}
// TODO: For now, the destination interface can only be implemented by
// the source class.
if (!Stream.of(hierarchy.getImplementingClasses(destinationInterface)).parallel().distinct()
.allMatch(c -> c.equals(sourceMethod.getDeclaringType()))) {
RefactoringStatusEntry error = addError(status, Messages.DestinationInterfaceHasInvalidImplementingClass,
destinationInterface);
addUnmigratableMethod(sourceMethod, error);
}
return status;
}
private RefactoringStatus checkValidSubtypes(IMethod sourceMethod, final ITypeHierarchy hierarchy)
throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
// TODO: For now, no subtypes except the declaring type.
// FIXME: Really, it should match the declaring type of the method to be
// migrated.
IType destinationInterface = getSourceMethodToTargetMethodMap().get(sourceMethod).getDeclaringType();
if (!Stream.of(hierarchy.getAllSubtypes(destinationInterface)).distinct()
.allMatch(s -> s.equals(sourceMethod.getDeclaringType())))
addError(status, Messages.DestinationInterfaceHierarchyContainsSubtype, destinationInterface);
return status;
}
private RefactoringStatus checkValidInterfacesInHierarchy(IMethod sourceMethod, final ITypeHierarchy hierarchy,
String errorMessage) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
Optional<IType> destinationInterface = getDestinationInterface(sourceMethod);
// TODO: For now, there should be only one interface in the hierarchy,
// and that is the target interface.
boolean containsOnlyValidInterfaces = Stream.of(hierarchy.getAllInterfaces()).parallel().distinct()
.allMatch(i -> i.equals(destinationInterface.orElse(null)));
if (!containsOnlyValidInterfaces)
addError(status, errorMessage, hierarchy.getType());
return status;
}
private Optional<IType> getDestinationInterface(IMethod sourceMethod) {
return Optional.ofNullable(this.getSourceMethodToTargetMethodMap().get(sourceMethod))
.map(IMethod::getDeclaringType);
}
private RefactoringStatus checkValidClassesInHierarchy(IMethod sourceMethod, final ITypeHierarchy hierarchy,
String errorMessage) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
// TODO: For now, the only class in the hierarchy should be the
// declaring class of the source method and java.lang.Object.
List<IType> allClassesAsList = Arrays.asList(hierarchy.getAllClasses());
// TODO: All the methods to move may not be from the same type. This is
// in regards to getDeclaringType(), which only returns one type.
boolean containsOnlyValidClasses = allClassesAsList.size() == 2
&& allClassesAsList.contains(sourceMethod.getDeclaringType())
&& allClassesAsList.contains(hierarchy.getType().getJavaProject().findType("java.lang.Object"));
if (!containsOnlyValidClasses) {
RefactoringStatusEntry error = addError(status, errorMessage, hierarchy.getType());
addUnmigratableMethod(sourceMethod, error);
}
return status;
}
@SuppressWarnings("unused")
private void addWarning(RefactoringStatus status, String message) {
addWarning(status, message, new IJavaElement[] {});
}
protected RefactoringStatus checkDeclaringType(IMethod sourceMethod, Optional<IProgressMonitor> monitor)
throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
IType type = sourceMethod.getDeclaringType();
if (type.isEnum())
// TODO: For now. It might be okay to have an enum.
addErrorAndMark(status, Messages.NoMethodsInEnums, sourceMethod, type);
if (type.isAnnotation())
addErrorAndMark(status, Messages.NoMethodsInAnnotationTypes, sourceMethod, type);
if (type.isInterface())
addErrorAndMark(status, Messages.NoMethodsInInterfaces, sourceMethod, type);
if (type.isBinary())
addErrorAndMark(status, Messages.NoMethodsInBinaryTypes, sourceMethod, type);
if (type.isReadOnly())
addErrorAndMark(status, Messages.NoMethodsInReadOnlyTypes, sourceMethod, type);
if (type.isAnonymous())
addErrorAndMark(status, Messages.NoMethodsInAnonymousTypes, sourceMethod, type);
if (type.isLambda())
// TODO for now.
addErrorAndMark(status, Messages.NoMethodsInLambdas, sourceMethod, type);
if (type.isLocal())
// TODO for now.
addErrorAndMark(status, Messages.NoMethodsInLocals, sourceMethod, type);
if (type.isMember())
// TODO for now.
addErrorAndMark(status, Messages.NoMethodsInMemberTypes, sourceMethod, type);
if (!type.isClass())
// TODO for now.
addErrorAndMark(status, Messages.MethodsOnlyInClasses, sourceMethod, type);
if (type.getAnnotations().length != 0)
// TODO for now.
addErrorAndMark(status, Messages.NoMethodsInAnnotatedTypes, sourceMethod, type);
if (type.getFields().length != 0)
// TODO for now.
addErrorAndMark(status, Messages.NoMethodsInTypesWithFields, sourceMethod, type);
if (type.getInitializers().length != 0)
// TODO for now.
addErrorAndMark(status, Messages.NoMethodsInTypesWithInitializers, sourceMethod, type);
if (type.getTypeParameters().length != 0)
// TODO for now.
addErrorAndMark(status, Messages.NoMethodsInTypesWithTypeParameters, sourceMethod, type);
if (type.getTypes().length != 0)
// TODO for now.
addErrorAndMark(status, Messages.NoMethodsInTypesWithType, sourceMethod, type);
if (type.getSuperclassName() != null)
// TODO for now.
addErrorAndMark(status, Messages.NoMethodsInTypesWithSuperType, sourceMethod, type);
if (type.getSuperInterfaceNames().length == 0)
// TODO enclosing type must implement an interface, at least for
// now,
// which one of which will become the target interface.
// it is probably possible to still perform the refactoring
// without this condition but I believe that this is
// the particular pattern we are targeting.
addErrorAndMark(status, Messages.NoMethodsInTypesThatDontImplementInterfaces, sourceMethod, type);
if (type.getSuperInterfaceNames().length > 1)
// TODO for now. Let's only deal with a single interface as that
// is part of the targeted pattern.
addErrorAndMark(status, Messages.NoMethodsInTypesThatExtendMultipleInterfaces, sourceMethod, type);
if (!Flags.isAbstract(type.getFlags()))
// TODO for now. This follows the target pattern. Maybe we can
// relax this but that would require checking for
// instantiations.
addErrorAndMark(status, Messages.NoMethodsInConcreteTypes, sourceMethod, type);
if (Flags.isStatic(type.getFlags()))
// TODO no static types for now.
addErrorAndMark(status, Messages.NoMethodsInStaticTypes, sourceMethod, type);
status.merge(checkDeclaringTypeHierarchy(sourceMethod, monitor.map(m -> new SubProgressMonitor(m, 1))));
return status;
}
private void addErrorAndMark(RefactoringStatus status, String message, IMethod sourceMethod, IMember... related) {
RefactoringStatusEntry error = addError(status, message, sourceMethod, related);
addUnmigratableMethod(sourceMethod, error);
}
protected RefactoringStatus checkDeclaringTypeHierarchy(IMethod sourceMethod, Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
RefactoringStatus status = new RefactoringStatus();
monitor.ifPresent(m -> m.subTask("Checking declaring type hierarchy..."));
final ITypeHierarchy hierarchy = this.getDeclaringTypeHierarchy(sourceMethod, monitor);
status.merge(checkValidClassesInHierarchy(sourceMethod, hierarchy,
Messages.DeclaringTypeHierarchyContainsInvalidClass));
status.merge(checkValidInterfacesInHierarchy(sourceMethod, hierarchy,
Messages.DeclaringTypeHierarchyContainsInvalidInterface));
// TODO: For now, the declaring type should have no subtypes.
if (hierarchy.getAllSubtypes(sourceMethod.getDeclaringType()).length != 0) {
RefactoringStatusEntry error = addError(status, Messages.DeclaringTypeContainsSubtype,
sourceMethod.getDeclaringType());
addUnmigratableMethod(sourceMethod, error);
}
// TODO: For now, only java.lang.Object as the super class.
final IType object = hierarchy.getType().getJavaProject().findType("java.lang.Object");
if (!Stream.of(hierarchy.getAllSuperclasses(sourceMethod.getDeclaringType())).parallel().distinct()
.allMatch(t -> t.equals(object))) {
RefactoringStatusEntry error = addError(status, Messages.DeclaringTypeContainsInvalidSupertype,
sourceMethod.getDeclaringType());
addUnmigratableMethod(sourceMethod, error);
}
return status;
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
protected RefactoringStatus checkCandidateDestinationInterfaces(IMethod sourceMethod,
final Optional<IProgressMonitor> monitor) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
IType[] interfaces = getCandidateDestinationInterfaces(sourceMethod,
monitor.map(m -> new SubProgressMonitor(m, 1)));
if (interfaces.length == 0)
addErrorAndMark(status, Messages.NoMethodsInTypesWithNoCandidateTargetTypes, sourceMethod,
sourceMethod.getDeclaringType());
else if (interfaces.length > 1)
// TODO For now, let's make sure there's only one candidate type.
addErrorAndMark(status, Messages.NoMethodsInTypesWithMultipleCandidateTargetTypes, sourceMethod,
sourceMethod.getDeclaringType());
return status;
}
/**
* Returns the possible target interfaces for the migration. NOTE: One
* difference here between this refactoring and pull up is that we can have
* a much more complex type hierarchy due to multiple interface inheritance
* in Java.
* <p>
* TODO: It should be possible to pull up a method into an interface (i.e.,
* "Pull Up Method To Interface") that is not implemented explicitly. For
* example, there may be a skeletal implementation class that implements all
* the target interface's methods without explicitly declaring so.
*
* @param monitor
* A progress monitor.
* @return The possible target interfaces for the migration.
* @throws JavaModelException
* upon Java model problems.
*/
public static IType[] getCandidateDestinationInterfaces(IMethod method, final Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
monitor.ifPresent(m -> m.beginTask("Retrieving candidate types...", IProgressMonitor.UNKNOWN));
IType[] superInterfaces = getSuperInterfaces(method.getDeclaringType(),
monitor.map(m -> new SubProgressMonitor(m, 1)));
return Stream.of(superInterfaces).parallel().filter(Objects::nonNull).filter(IJavaElement::exists)
.filter(t -> !t.isReadOnly()).filter(t -> !t.isBinary()).filter(t -> {
IMethod[] methods = t.findMethods(method);
return methods != null && methods.length > 0;
}).toArray(IType[]::new);
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
private static IType[] getSuperInterfaces(IType type, final Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
monitor.ifPresent(m -> m.beginTask("Retrieving type super interfaces...", IProgressMonitor.UNKNOWN));
return getSuperTypeHierarchy(type, monitor.map(m -> new SubProgressMonitor(m, 1)))
.getAllSuperInterfaces(type);
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
private ITypeHierarchy getDeclaringTypeHierarchy(IMethod sourceMethod, final Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
monitor.ifPresent(m -> m.subTask("Retrieving declaring type hierarchy..."));
IType declaringType = sourceMethod.getDeclaringType();
return this.getTypeHierarchy(declaringType, monitor);
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
private ITypeHierarchy getDestinationInterfaceHierarchy(IMethod sourceMethod,
final Optional<IProgressMonitor> monitor) throws JavaModelException {
try {
monitor.ifPresent(m -> m.subTask("Retrieving destination type hierarchy..."));
IType destinationInterface = getDestinationInterface(sourceMethod).get();
return this.getTypeHierarchy(destinationInterface, monitor);
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
private static Map<IType, ITypeHierarchy> typeToSuperTypeHierarchyMap = new HashMap<>();
private static Map<IType, ITypeHierarchy> getTypeToSuperTypeHierarchyMap() {
return typeToSuperTypeHierarchyMap;
}
private static ITypeHierarchy getSuperTypeHierarchy(IType type, final Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
monitor.ifPresent(m -> m.subTask("Retrieving declaring super type hierarchy..."));
if (getTypeToSuperTypeHierarchyMap().containsKey(type))
return getTypeToSuperTypeHierarchyMap().get(type);
else {
ITypeHierarchy newSupertypeHierarchy = type
.newSupertypeHierarchy(monitor.orElseGet(NullProgressMonitor::new));
getTypeToSuperTypeHierarchyMap().put(type, newSupertypeHierarchy);
return newSupertypeHierarchy;
}
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
protected RefactoringStatus checkSourceMethods(Optional<IProgressMonitor> pm) throws JavaModelException {
try {
RefactoringStatus status = new RefactoringStatus();
pm.ifPresent(m -> m.beginTask(Messages.CheckingPreconditions, this.getSourceMethods().size()));
for (IMethod sourceMethod : this.getSourceMethods()) {
// FIXME: Repeated.
RefactoringStatus existenceStatus = checkExistence(sourceMethod, Messages.MethodDoesNotExist);
if (!existenceStatus.isOK()) {
status.merge(existenceStatus);
addUnmigratableMethod(sourceMethod, existenceStatus.getEntryWithHighestSeverity());
}
RefactoringStatus writabilityStatus = checkWritabilitiy(sourceMethod, Messages.CantChangeMethod);
if (!writabilityStatus.isOK()) {
status.merge(writabilityStatus);
addUnmigratableMethod(sourceMethod, writabilityStatus.getEntryWithHighestSeverity());
}
RefactoringStatus structureStatus = checkStructure(sourceMethod);
if (!structureStatus.isOK()) {
status.merge(structureStatus);
addUnmigratableMethod(sourceMethod, structureStatus.getEntryWithHighestSeverity());
}
if (sourceMethod.isConstructor()) {
RefactoringStatusEntry entry = addError(status, Messages.NoConstructors, sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
status.merge(checkAnnotations(sourceMethod));
// synchronized methods aren't allowed in interfaces (even
// if they're default).
if (Flags.isSynchronized(sourceMethod.getFlags())) {
RefactoringStatusEntry entry = addError(status, Messages.NoSynchronizedMethods, sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
if (Flags.isStatic(sourceMethod.getFlags())) {
RefactoringStatusEntry entry = addError(status, Messages.NoStaticMethods, sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
if (Flags.isAbstract(sourceMethod.getFlags())) {
RefactoringStatusEntry entry = addError(status, Messages.NoAbstractMethods, sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
// final methods aren't allowed in interfaces.
if (Flags.isFinal(sourceMethod.getFlags())) {
RefactoringStatusEntry entry = addError(status, Messages.NoFinalMethods, sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
// native methods don't have bodies. As such, they can't
// be skeletal implementors.
if (JdtFlags.isNative(sourceMethod)) {
RefactoringStatusEntry entry = addError(status, Messages.NoNativeMethods, sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
if (sourceMethod.isLambdaMethod()) {
RefactoringStatusEntry entry = addError(status, Messages.NoLambdaMethods, sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
status.merge(checkExceptions(sourceMethod));
status.merge(checkParameters(sourceMethod));
if (!sourceMethod.getReturnType().equals(Signature.SIG_VOID)) {
// return type must be void.
// TODO for now. Can't remove this until we allow at
// least
// one statement.
RefactoringStatusEntry entry = addError(status, Messages.NoMethodsWithReturnTypes, sourceMethod);
addUnmigratableMethod(sourceMethod, entry);
}
// ensure that the method has a target.
if (this.getSourceMethodToTargetMethodMap().get(sourceMethod) == null)
addErrorAndMark(status, Messages.SourceMethodHasNoTargetMethod, sourceMethod);
else // otherwise, check accesses in the source method.
status.merge(checkAccesses(sourceMethod, pm.map(m -> new SubProgressMonitor(m, 1))));
pm.ifPresent(m -> m.worked(1));
}
return status;
} finally {
pm.ifPresent(IProgressMonitor::done);
}
}
/**
* Annotations between source and target methods must be consistent. Related
* to #45.
*
* @param sourceMethod
* The method to check annotations.
* @return The resulting {@link RefactoringStatus}.
* @throws JavaModelException
* If the {@link IAnnotation}s cannot be retrieved.
*/
private RefactoringStatus checkAnnotations(IMethod sourceMethod) throws JavaModelException {
IMethod targetMethod = this.getSourceMethodToTargetMethodMap().get(sourceMethod);
if (targetMethod != null && !checkAnnotations(sourceMethod, targetMethod).isOK()) {
RefactoringStatus status = RefactoringStatus.createErrorStatus(
formatMessage(Messages.AnnotationMismatch, sourceMethod, targetMethod),
JavaStatusContext.create(sourceMethod));
addUnmigratableMethod(sourceMethod, status.getEntryWithHighestSeverity());
return status;
}
return new RefactoringStatus();
}
private void addUnmigratableMethod(IMethod method, Object reason) {
this.getUnmigratableMethods().add(method);
this.logInfo(
"Method " + getElementLabel(method, ALL_FULLY_QUALIFIED) + " is not migratable because: " + reason);
}
private RefactoringStatus checkAnnotations(IAnnotatable source, IAnnotatable target) throws JavaModelException {
// a set of annotations from the source method.
Set<IAnnotation> sourceAnnotationSet = new HashSet<>(Arrays.asList(source.getAnnotations()));
// remove any annotations to not consider.
removeSpecialAnnotations(sourceAnnotationSet);
// a set of source method annotation names.
Set<String> sourceMethodAnnotationElementNames = sourceAnnotationSet.parallelStream()
.map(IAnnotation::getElementName).collect(Collectors.toSet());
// a set of target method annotation names.
Set<String> targetAnnotationElementNames = getAnnotationElementNames(target);
// if the source method annotation names don't match the target method
// annotation names.
if (!sourceMethodAnnotationElementNames.equals(targetAnnotationElementNames))
return RefactoringStatus.createErrorStatus(Messages.AnnotationNameMismatch, new RefactoringStatusContext() {
@Override
public Object getCorrespondingElement() {
return source;
}
});
else { // otherwise, we have the same annotations names. Check the
// values.
for (IAnnotation sourceAnnotation : sourceAnnotationSet) {
IMemberValuePair[] sourcePairs = sourceAnnotation.getMemberValuePairs();
IAnnotation targetAnnotation = target.getAnnotation(sourceAnnotation.getElementName());
IMemberValuePair[] targetPairs = targetAnnotation.getMemberValuePairs();
// sanity check.
Assert.isTrue(sourcePairs.length == targetPairs.length, "Source and target pairs differ.");
Arrays.parallelSort(sourcePairs, Comparator.comparing(IMemberValuePair::getMemberName));
Arrays.parallelSort(targetPairs, Comparator.comparing(IMemberValuePair::getMemberName));
for (int i = 0; i < sourcePairs.length; i++)
if (!sourcePairs[i].getMemberName().equals(targetPairs[i].getMemberName())
|| sourcePairs[i].getValueKind() != targetPairs[i].getValueKind()
|| !(sourcePairs[i].getValue().equals(targetPairs[i].getValue())))
return RefactoringStatus.createErrorStatus(
formatMessage(Messages.AnnotationValueMismatch, sourceAnnotation, targetAnnotation),
JavaStatusContext.create(findEnclosingMember(sourceAnnotation)));
}
}
return new RefactoringStatus();
}
/**
* Remove any annotations that we don't want considered.
*
* @param annotationSet
* The set of annotations to work with.
*/
protected void removeSpecialAnnotations(Set<IAnnotation> annotationSet) {
// Special case: don't consider the @Override annotation in the source
// (the target will never have this)
annotationSet.removeIf(a -> a.getElementName().equals(Override.class.getName()));
annotationSet.removeIf(a -> a.getElementName().equals(Override.class.getSimpleName()));
}
private static IMember findEnclosingMember(IJavaElement element) {
if (element == null)
return null;
else if (element instanceof IMember)
return (IMember) element;
else
return findEnclosingMember(element.getParent());
}
private Set<String> getAnnotationElementNames(IAnnotatable annotatable) throws JavaModelException {
return Arrays.stream(annotatable.getAnnotations()).parallel().map(IAnnotation::getElementName)
.collect(Collectors.toSet());
}
/**
* #44: Ensure that exception types between the source and target methods
* match.
*
* @param sourceMethod
* The source method.
* @return The corresponding {@link RefactoringStatus}.
* @throws JavaModelException
* If there is trouble retrieving exception types from
* sourceMethod.
*/
private RefactoringStatus checkExceptions(IMethod sourceMethod) throws JavaModelException {
RefactoringStatus status = new RefactoringStatus();
IMethod targetMethod = this.getSourceMethodToTargetMethodMap().get(sourceMethod);
if (targetMethod != null) {
Set<String> sourceMethodExceptionTypeSet = getExceptionTypeSet(sourceMethod);
Set<String> targetMethodExceptionTypeSet = getExceptionTypeSet(targetMethod);
if (!sourceMethodExceptionTypeSet.equals(targetMethodExceptionTypeSet)) {
RefactoringStatusEntry entry = addError(status, Messages.ExceptionTypeMismatch, sourceMethod,
targetMethod);
addUnmigratableMethod(sourceMethod, entry);
}
}
return status;
}
private static Set<String> getExceptionTypeSet(IMethod method) throws JavaModelException {
return Stream.of(method.getExceptionTypes()).parallel().collect(Collectors.toSet());
}
/**
* Check that the annotations in the parameters are consistent between the
* source and target.
*
* FIXME: What if the annotation type is not available in the target?
*
* @param sourceMethod
* The method to check.
* @return {@link RefactoringStatus} indicating the result of the check.
* @throws JavaModelException
*/
private RefactoringStatus checkParameters(IMethod sourceMethod) throws JavaModelException {
IMethod targetMethod = this.getSourceMethodToTargetMethodMap().get(sourceMethod);
// for each parameter.
for (int i = 0; i < sourceMethod.getParameters().length; i++) {
ILocalVariable sourceParameter = sourceMethod.getParameters()[i];
// get the corresponding target parameter.
ILocalVariable targetParameter = targetMethod.getParameters()[i];
if (!checkAnnotations(sourceParameter, targetParameter).isOK()) {
RefactoringStatus status = RefactoringStatus
.createErrorStatus(formatMessage(Messages.MethodContainsInconsistentParameterAnnotations,
sourceMethod, targetMethod), JavaStatusContext.create(sourceMethod));
addUnmigratableMethod(sourceMethod, status.getEntryWithHighestSeverity());
}
}
return new RefactoringStatus();
}
private RefactoringStatus checkStructure(IMember member) throws JavaModelException {
if (!member.isStructureKnown()) {
return RefactoringStatus.createErrorStatus(
MessageFormat.format(Messages.CUContainsCompileErrors, getElementLabel(member, ALL_FULLY_QUALIFIED),
getElementLabel(member.getCompilationUnit(), ALL_FULLY_QUALIFIED)),
JavaStatusContext.create(member.getCompilationUnit()));
}
return new RefactoringStatus();
}
private static RefactoringStatusEntry getLastRefactoringStatusEntry(RefactoringStatus status) {
return status.getEntryAt(status.getEntries().length - 1);
}
private RefactoringStatus checkWritabilitiy(IMember member, String message) {
if (member.isBinary() || member.isReadOnly()) {
return createError(message, member);
}
return new RefactoringStatus();
}
private RefactoringStatus checkExistence(IMember member, String message) {
if (member == null || !member.exists()) {
return createError(message, member);
}
return new RefactoringStatus();
}
protected Set<IMethod> getSourceMethods() {
return this.sourceMethods;
}
protected Set<IMethod> getUnmigratableMethods() {
return this.unmigratableMethods;
}
protected RefactoringStatus checkSourceMethodBodies(IProgressMonitor pm) throws JavaModelException {
try {
RefactoringStatus status = new RefactoringStatus();
Iterator<IMethod> it = this.getSourceMethods().iterator();
while (it.hasNext()) {
IMethod method = it.next();
ITypeRoot root = method.getCompilationUnit();
CompilationUnit unit = this.getCompilationUnit(root, new SubProgressMonitor(pm, 1));
MethodDeclaration declaration = ASTNodeSearchUtil.getMethodDeclarationNode(method, unit);
if (declaration != null) {
Block body = declaration.getBody();
if (body != null) {
@SuppressWarnings("rawtypes")
List statements = body.statements();
if (!statements.isEmpty()) {
// TODO for now.
RefactoringStatusEntry entry = addError(status, Messages.NoMethodsWithStatements, method);
addUnmigratableMethod(method, entry);
}
}
}
pm.worked(1);
}
return status;
} finally {
pm.done();
}
}
private static void addWarning(RefactoringStatus status, String message, IJavaElement... relatedElementCollection) {
addEntry(status, RefactoringStatus.WARNING, message, relatedElementCollection);
}
private static RefactoringStatusEntry addError(RefactoringStatus status, String message,
IJavaElement... relatedElementCollection) {
addEntry(status, RefactoringStatus.ERROR, message, relatedElementCollection);
return getLastRefactoringStatusEntry(status);
}
private static void addEntry(RefactoringStatus status, int severity, String message,
IJavaElement... relatedElementCollection) {
message = formatMessage(message, relatedElementCollection);
// add the first element as the context if appropriate.
if (relatedElementCollection.length > 0 && relatedElementCollection[0] instanceof IMember) {
IMember member = (IMember) relatedElementCollection[0];
RefactoringStatusContext context = JavaStatusContext.create(member);
status.addEntry(new RefactoringStatusEntry(severity, message, context));
} else // otherwise, just add the message.
status.addEntry(new RefactoringStatusEntry(severity, message));
}
private static String formatMessage(String message, IJavaElement... relatedElementCollection) {
Object[] elementNames = Arrays.stream(relatedElementCollection).parallel().filter(Objects::nonNull)
.map(re -> getElementLabel(re, ALL_FULLY_QUALIFIED)).toArray();
message = MessageFormat.format(message, elementNames);
return message;
}
private static RefactoringStatusEntry addError(RefactoringStatus status, String message, IMember member,
IMember... more) {
List<String> elementNames = new ArrayList<>();
elementNames.add(getElementLabel(member, ALL_FULLY_QUALIFIED));
Stream<String> stream = Arrays.asList(more).parallelStream().map(m -> getElementLabel(m, ALL_FULLY_QUALIFIED));
Stream<String> concat = Stream.concat(elementNames.stream(), stream);
List<String> collect = concat.collect(Collectors.toList());
status.addError(MessageFormat.format(message, collect.toArray()), JavaStatusContext.create(member));
return getLastRefactoringStatusEntry(status);
}
protected static RefactoringStatus createWarning(String message, IMember member) {
return createRefactoringStatus(message, member, RefactoringStatus::createWarningStatus);
}
private RefactoringStatus createError(String message, IMember member) {
return createRefactoringStatus(message, member, RefactoringStatus::createErrorStatus);
}
protected static RefactoringStatus createFatalError(String message, IMember member) {
return createRefactoringStatus(message, member, RefactoringStatus::createFatalErrorStatus);
}
private static RefactoringStatus createRefactoringStatus(String message, IMember member,
BiFunction<String, RefactoringStatusContext, RefactoringStatus> function) {
String elementName = getElementLabel(member, ALL_FULLY_QUALIFIED);
return function.apply(MessageFormat.format(message, elementName), JavaStatusContext.create(member));
}
/**
* Creates a working copy layer if necessary.
*
* @param monitor
* the progress monitor to use
* @return a status describing the outcome of the operation
*/
protected RefactoringStatus createWorkingCopyLayer(IProgressMonitor monitor) {
try {
monitor.beginTask(Messages.CheckingPreconditions, 1);
// TODO ICompilationUnit unit =
// getDeclaringType().getCompilationUnit();
// if (fLayer)
// unit = unit.findWorkingCopy(fOwner);
// resetWorkingCopies(unit);
return new RefactoringStatus();
} finally {
monitor.done();
}
}
@Override
public RefactoringStatus checkFinalConditions(final IProgressMonitor monitor, final CheckConditionsContext context)
throws CoreException, OperationCanceledException {
try {
monitor.beginTask(Messages.CheckingPreconditions, 12);
// TODO: clearCaches();
final RefactoringStatus status = new RefactoringStatus();
if (!this.getSourceMethods().isEmpty())
status.merge(createWorkingCopyLayer(new SubProgressMonitor(monitor, 4)));
if (status.hasFatalError())
return status;
if (monitor.isCanceled())
throw new OperationCanceledException();
status.merge(checkSourceMethods(Optional.of(new SubProgressMonitor(monitor, 1))));
if (status.hasFatalError())
return status;
if (monitor.isCanceled())
throw new OperationCanceledException();
// TODO: Should this be a separate method?
status.merge(checkDestinationInterfaces(Optional.of(new SubProgressMonitor(monitor, 1))));
if (status.hasFatalError())
return status;
// if (fMembersToMove.length > 0)
// TODO: Check project compliance.
// status.merge(checkProjectCompliance(
// getCompilationUnitRewrite(compilationUnitRewrites,
// getDeclaringType().getCompilationUnit()),
// getDestinationType(), fMembersToMove));
// TODO: More checks, perhaps resembling those in
// org.eclipse.jdt.internal.corext.refactoring.structure.PullUpRefactoringProcessor.checkFinalConditions(IProgressMonitor,
// CheckConditionsContext).
// check if there are any methods left to migrate.
if (this.getUnmigratableMethods().containsAll(this.getSourceMethods()))
// if not, we have a fatal error.
status.addFatalError(Messages.NoMethodsHavePassedThePreconditions);
return status;
} catch (Exception e) {
JavaPlugin.log(e);
throw e;
} finally {
monitor.done();
}
}
protected static RefactoringStatus checkProjectCompliance(CompilationUnitRewrite sourceRewriter, IType destination,
IMember[] members) {
RefactoringStatus status = new RefactoringStatus();
if (!JavaModelUtil.is50OrHigher(destination.getJavaProject())) {
for (int index = 0; index < members.length; index++) {
try {
BodyDeclaration decl = ASTNodeSearchUtil.getBodyDeclarationNode(members[index],
sourceRewriter.getRoot());
if (decl != null) {
for (@SuppressWarnings("unchecked")
final Iterator<IExtendedModifier> iterator = decl.modifiers().iterator(); iterator.hasNext();) {
boolean reported = false;
final IExtendedModifier modifier = iterator.next();
if (!reported && modifier.isAnnotation()) {
status.merge(
RefactoringStatus
.createErrorStatus(
MessageFormat
.format(RefactoringCoreMessages.PullUpRefactoring_incompatible_langauge_constructs,
getTextLabel(members[index],
ALL_FULLY_QUALIFIED),
getTextLabel(destination, ALL_DEFAULT)),
JavaStatusContext.create(members[index])));
reported = true;
}
}
}
} catch (JavaModelException exception) {
JavaPlugin.log(exception);
}
if (members[index] instanceof IMethod) {
final IMethod method = (IMethod) members[index];
try {
if (Flags.isVarargs(method.getFlags()))
status.merge(RefactoringStatus.createErrorStatus(
MessageFormat.format(
RefactoringCoreMessages.PullUpRefactoring_incompatible_language_constructs1,
getTextLabel(members[index], ALL_FULLY_QUALIFIED),
getTextLabel(destination, ALL_DEFAULT)),
JavaStatusContext.create(members[index])));
} catch (JavaModelException exception) {
JavaPlugin.log(exception);
}
}
}
}
if (!JavaModelUtil.is18OrHigher(destination.getJavaProject())) {
Arrays.asList(members).stream().filter(e -> e instanceof IMethod).map(IMethod.class::cast)
.filter(IMethod::isLambdaMethod)
.forEach(m -> addError(status, Messages.IncompatibleLanguageConstruct, m, destination));
}
return status;
}
@Override
public Change createChange(IProgressMonitor pm) throws CoreException, OperationCanceledException {
try {
pm.beginTask(Messages.CreatingChange, 1);
final TextEditBasedChangeManager manager = new TextEditBasedChangeManager();
// the input methods as a set.
Set<IMethod> methods = new HashSet<>(this.getSourceMethods().parallelStream()
.filter(m -> m instanceof IMethod).map(m -> m).collect(Collectors.toSet()));
// remove all the unmigratable methods.
methods.removeAll(this.unmigratableMethods);
if (methods.isEmpty())
return new NullChange(Messages.NoMethodsToMigrate);
for (IMethod sourceMethod : methods) {
IType destinationInterface = getSourceMethodToTargetMethodMap().get(sourceMethod).getDeclaringType();
logInfo("Migrating method: " + getElementLabel(sourceMethod, ALL_FULLY_QUALIFIED) + " to interface: "
+ destinationInterface.getFullyQualifiedName());
CompilationUnit destinationCompilationUnit = this.getCompilationUnit(destinationInterface.getTypeRoot(),
pm);
ASTRewrite destinationRewrite = getASTRewrite(destinationCompilationUnit);
CompilationUnit sourceCompilationUnit = getCompilationUnit(sourceMethod.getTypeRoot(), pm);
MethodDeclaration sourceMethodDeclaration = ASTNodeSearchUtil.getMethodDeclarationNode(sourceMethod,
sourceCompilationUnit);
logInfo("Source method declaration: " + sourceMethodDeclaration);
// Find the target method.
IMethod targetMethod = getSourceMethodToTargetMethodMap().get(sourceMethod);
MethodDeclaration targetMethodDeclaration = ASTNodeSearchUtil.getMethodDeclarationNode(targetMethod,
destinationCompilationUnit);
// tack on the source method body to the target method.
copyMethodBody(sourceMethodDeclaration, targetMethodDeclaration, destinationRewrite);
// Change the target method to default.
convertToDefault(targetMethodDeclaration, destinationRewrite);
// TODO: Do we need to worry about preserving ordering of the
// modifiers?
// TODO: Should I be using JdtFlags instead of Flags?
// if the source method is strictfp.
// FIXME: Actually, I think we need to check that, in the
// case the target method isn't already strictfp, that the other
// methods in the hierarchy are.
if ((Flags.isStrictfp(sourceMethod.getFlags())
|| Flags.isStrictfp(sourceMethod.getDeclaringType().getFlags()))
&& !Flags.isStrictfp(targetMethod.getFlags()))
// change the target method to strictfp.
convertToStrictFP(targetMethodDeclaration, destinationRewrite);
// Remove the source method.
ASTRewrite sourceRewrite = getASTRewrite(sourceCompilationUnit);
removeMethod(sourceMethodDeclaration, sourceRewrite);
}
// TODO: Need to deal with imports
// save the source changes.
ICompilationUnit[] units = this.typeRootToCompilationUnitMap.keySet().parallelStream()
.filter(t -> t instanceof ICompilationUnit).map(t -> (ICompilationUnit) t)
.filter(cu -> !manager.containsChangesIn(cu)).toArray(ICompilationUnit[]::new);
for (ICompilationUnit cu : units)
manageCompilationUnit(manager, cu, getASTRewrite(getCompilationUnit(cu, pm)));
final Map<String, String> arguments = new HashMap<>();
int flags = RefactoringDescriptor.STRUCTURAL_CHANGE | RefactoringDescriptor.MULTI_CHANGE;
// TODO: Fill in description.
MigrateSkeletalImplementationToInterfaceRefactoringDescriptor descriptor = new MigrateSkeletalImplementationToInterfaceRefactoringDescriptor(
null, "TODO", null, arguments, flags);
return new DynamicValidationRefactoringChange(descriptor, getProcessorName(), manager.getAllChanges());
} finally {
pm.done();
}
}
private CompilationUnit getCompilationUnit(ITypeRoot root, IProgressMonitor pm) {
CompilationUnit compilationUnit = this.typeRootToCompilationUnitMap.get(root);
if (compilationUnit == null) {
compilationUnit = RefactoringASTParser.parseWithASTProvider(root, false, pm);
this.typeRootToCompilationUnitMap.put(root, compilationUnit);
}
return compilationUnit;
}
private ASTRewrite getASTRewrite(CompilationUnit compilationUnit) {
ASTRewrite rewrite = this.compilationUnitToASTRewriteMap.get(compilationUnit);
if (rewrite == null) {
rewrite = ASTRewrite.create(compilationUnit.getAST());
this.compilationUnitToASTRewriteMap.put(compilationUnit, rewrite);
}
return rewrite;
}
private void manageCompilationUnit(final TextEditBasedChangeManager manager, ICompilationUnit compilationUnit,
ASTRewrite rewrite) throws JavaModelException {
TextEdit edit = rewrite.rewriteAST();
TextChange change = (TextChange) manager.get(compilationUnit);
change.setTextType("java");
if (change.getEdit() == null)
change.setEdit(edit);
else
change.addEdit(edit);
manager.manage(compilationUnit, change);
}
private void copyMethodBody(MethodDeclaration sourceMethodDeclaration, MethodDeclaration targetMethodDeclaration,
ASTRewrite destinationRewrite) {
Block sourceMethodBody = sourceMethodDeclaration.getBody();
Assert.isNotNull(sourceMethodBody, "Source method has a null body.");
ASTNode sourceMethodBodyCopy = ASTNode.copySubtree(destinationRewrite.getAST(), sourceMethodBody);
destinationRewrite.set(targetMethodDeclaration, MethodDeclaration.BODY_PROPERTY, sourceMethodBodyCopy, null);
}
private void removeMethod(MethodDeclaration methodDeclaration, ASTRewrite rewrite) {
// TODO: Do I need an edit group??
rewrite.remove(methodDeclaration, null);
}
private void convertToDefault(MethodDeclaration methodDeclaration, ASTRewrite rewrite) {
addModifierKeyword(methodDeclaration, ModifierKeyword.DEFAULT_KEYWORD, rewrite);
}
private void convertToStrictFP(MethodDeclaration methodDeclaration, ASTRewrite rewrite) {
addModifierKeyword(methodDeclaration, ModifierKeyword.STRICTFP_KEYWORD, rewrite);
}
private void addModifierKeyword(MethodDeclaration methodDeclaration, ModifierKeyword modifierKeyword,
ASTRewrite rewrite) {
Modifier modifier = rewrite.getAST().newModifier(modifierKeyword);
ListRewrite listRewrite = rewrite.getListRewrite(methodDeclaration, methodDeclaration.getModifiersProperty());
listRewrite.insertLast(modifier, null);
}
protected Map<IMethod, IMethod> getSourceMethodToTargetMethodMap() {
return sourceMethodToTargetMethodMap;
}
/**
* Finds the target (interface) method declaration in the destination
* interface for the given source method.
*
* TODO: Something is very wrong here. There can be multiple targets for a
* given source method because it can be declared in multiple interfaces up
* and down the hierarchy. What this method right now is really doing is
* finding the target method for the given source method in the destination
* interface. As such, we should be sure what the destination is prior to
* this call.
*
* @param sourceMethod
* The method that will be migrated to the target interface.
* @return The target method that will be manipulated or null if not found.
* @throws JavaModelException
*/
public static IMethod getTargetMethod(IMethod sourceMethod, Optional<IProgressMonitor> monitor)
throws JavaModelException {
IType destinationInterface = getDestinationInterface(sourceMethod, monitor);
if (sourceMethodTargetInterfaceTargetMethodTable.contains(sourceMethod, destinationInterface))
return sourceMethodTargetInterfaceTargetMethodTable.get(sourceMethod, destinationInterface);
else {
if (destinationInterface == null)
return null; // no target method in null destination interfaces.
else {
IMethod targetMethod = getTargetMethod(sourceMethod, destinationInterface);
sourceMethodTargetInterfaceTargetMethodTable.put(sourceMethod, destinationInterface, targetMethod);
return targetMethod;
}
}
}
private static IType getDestinationInterface(IMethod sourceMethod, Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
IType[] candidateDestinationInterfaces = getCandidateDestinationInterfaces(sourceMethod,
monitor.map(m -> new SubProgressMonitor(m, 1)));
// FIXME: Really just returning the first match here
return Arrays.stream(candidateDestinationInterfaces).findFirst().orElse(null);
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
/**
* Finds the target (interface) method declaration in the given type for the
* given source method.
*
* @param sourceMethod
* The method that will be migrated to the target interface.
* @param
* @return The target method that will be manipulated or null if not found.
*/
private static IMethod getTargetMethod(IMethod sourceMethod, IType targetInterface) {
if (targetInterface == null)
return null; // not found.
IMethod[] methods = targetInterface.findMethods(sourceMethod);
if (methods == null)
return null; // not found.
Assert.isTrue(methods.length <= 1,
"Found multiple target methods for method: " + sourceMethod.getElementName());
if (methods.length == 1)
return methods[0];
else
return null; // not found.
}
private void log(int severity, String message) {
String name = FrameworkUtil.getBundle(this.getClass()).getSymbolicName();
IStatus status = new Status(severity, name, message);
JavaPlugin.log(status);
}
private void logInfo(String message) {
log(IStatus.INFO, message);
}
@SuppressWarnings("unused")
private void logWarning(String message) {
log(IStatus.WARNING, message);
}
@Override
public String getIdentifier() {
return MigrateSkeletalImplementationToInterfaceRefactoringDescriptor.REFACTORING_ID;
}
@Override
public String getProcessorName() {
return Messages.Name;
}
@Override
public boolean isApplicable() throws CoreException {
return RefactoringAvailabilityTester.isInterfaceMigrationAvailable(getSourceMethods().parallelStream()
.filter(m -> !this.unmigratableMethods.contains(m)).toArray(IMethod[]::new), Optional.empty());
}
/**
* Returns true if the given type is a pure interface, i.e., it is an
* interface but not an annotation.
*
* @param type
* The type to check.
* @return True if the given type is a pure interface and false otherwise.
* @throws JavaModelException
*/
private static boolean isPureInterface(IType type) throws JavaModelException {
return type != null && type.isInterface() && !type.isAnnotation();
}
private Map<IType, ITypeHierarchy> typeToTypeHierarchyMap = new HashMap<>();
protected Map<IType, ITypeHierarchy> getTypeToTypeHierarchyMap() {
return typeToTypeHierarchyMap;
}
protected ITypeHierarchy getTypeHierarchy(IType type, Optional<IProgressMonitor> monitor)
throws JavaModelException {
try {
ITypeHierarchy ret = this.getTypeToTypeHierarchyMap().get(type);
if (ret == null) {
ret = type.newTypeHierarchy(monitor.orElseGet(NullProgressMonitor::new));
this.getTypeToTypeHierarchyMap().put(type, ret);
}
return ret;
} finally {
monitor.ifPresent(IProgressMonitor::done);
}
}
@Override
public RefactoringParticipant[] loadParticipants(RefactoringStatus status, SharableParticipants sharedParticipants)
throws CoreException {
return new RefactoringParticipant[0];
}
} |
package org.op4j;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import junit.framework.TestCase;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.time.DateUtils;
import org.javaruntype.type.Types;
import org.junit.Test;
import org.op4j.functions.Call;
import org.op4j.functions.DecimalPoint;
import org.op4j.functions.FnCalendar;
import org.op4j.functions.FnFunc;
import org.op4j.functions.FnList;
import org.op4j.functions.FnNumber;
import org.op4j.functions.FnString;
public class RecipesTests extends TestCase {
@Test
public void testOP4J_001() throws Exception {
// Creating a list from its elements
List<String> result = Arrays.asList(new String[] {"hello", "hola", "ola", "ol"});
List<String> stringList =
Op.onListFor("hello", "hola", "ola", "ol").get();
assertEquals(result, stringList);
}
@Test
public void testOP4J_002() throws Exception {
// Creating a set from its elements
final User user1 = new User();
final User user2 = new User();
final User user3 = new User();
Set<User> result = new LinkedHashSet<User>(Arrays.asList(new User[] {user1, user2, user3}));
Set<User> users =
Op.onSetFor(user1, user2, user3).get();
assertEquals(result, users);
}
@Test
@SuppressWarnings("boxing")
public void testOP4J_003() throws Exception {
// Creating maps by zipping keys and values
Map<String,Integer> result = new LinkedHashMap<String,Integer>();
result.put("John", Integer.valueOf(27));
result.put("Mary", Integer.valueOf(49));
result.put("Derek", Integer.valueOf(19));
{
Map<String,Integer> agesByName =
Op.onListFor("John", "Mary", "Derek").zipValues(27, 49, 19).get();
assertEquals(result, agesByName);
}
{
Map<String,Integer> agesByName =
Op.onListFor(27, 49, 19).zipKeys("John", "Mary", "Derek").get();
assertEquals(result, agesByName);
}
}
@Test
public void testOP4J_004() throws Exception {
// Creating maps by coupling elements
Map<String,String> result = new LinkedHashMap<String,String>();
result.put("Spain", "Madrid");
result.put("United Kingdom", "London");
result.put("France", "Paris");
Map<String,String> capitals =
Op.onListFor("Spain", "Madrid", "United Kingdom", "London", "France", "Paris").couple().get();
assertEquals(result, capitals);
}
@Test
public void testOP4J_005() throws Exception {
// Converting a String into a Calendar (using a pattern)
Calendar result = Calendar.getInstance();
result = DateUtils.truncate(result, Calendar.YEAR);
result.set(Calendar.YEAR, 1978);
result.set(Calendar.MONTH, 11);
result.set(Calendar.DAY_OF_MONTH, 6);
String date = "06/12/1978";
Calendar cal =
Op.on(date).exec(FnString.toCalendar("dd/MM/yyyy")).get();
assertEquals(result.getTimeInMillis(), cal.getTimeInMillis());
}
@Test
public void testOP4J_006() throws Exception {
// Converting a list of Strings into a list of Calendars (using a pattern and a locale)
Calendar resCal1 = Calendar.getInstance();
resCal1 = DateUtils.truncate(resCal1, Calendar.YEAR);
resCal1.set(Calendar.YEAR, 1492);
resCal1.set(Calendar.MONTH, 9);
resCal1.set(Calendar.DAY_OF_MONTH, 12);
Calendar resCal2 = Calendar.getInstance();
resCal2 = DateUtils.truncate(resCal2, Calendar.YEAR);
resCal2.set(Calendar.YEAR, 1978);
resCal2.set(Calendar.MONTH, 11);
resCal2.set(Calendar.DAY_OF_MONTH, 6);
List<Calendar> result = Arrays.asList(new Calendar[] { resCal1, resCal2 });
List<String> dates =
Arrays.asList(new String[] { "12 de octubre, 1492", "06 de diciembre, 1978" });
{
List<Calendar> cals =
Op.on(dates).map(FnString.toCalendar("dd 'de' MMMM, yyyy", "es")).get();
for (int i = 0; i < cals.size(); i++) {
assertEquals(result.get(i).getTimeInMillis(), cals.get(i).getTimeInMillis());
}
}
{
List<Calendar> cals =
Op.on(dates).forEach().exec(FnString.toCalendar("dd 'de' MMMM, yyyy", "es")).get();
for (int i = 0; i < cals.size(); i++) {
assertEquals(result.get(i).getTimeInMillis(), cals.get(i).getTimeInMillis());
}
}
}
@Test
@SuppressWarnings("boxing")
public void testOP4J_007() throws Exception {
// Filtering nulls from an array
final Integer[] result = new Integer[] {12, 43, 92, 34 };
final Integer[] values = new Integer[] {null, 12, 43, 92, null, 34 };
Integer[] filteredValues =
Op.on(values).removeAllNull().get();
assertEquals(Integer[].class, filteredValues.getClass());
assertEquals(Arrays.asList(result), Arrays.asList(filteredValues));
}
@Test
public void testOP4J_008() throws Exception {
// Parsing a String decimal number into a Double (using locale)
final Double result = Double.valueOf(34.59);
final String strValue = "34,59";
Double value =
Op.on(strValue).exec(FnString.toDouble("fr")).get();
assertEquals(result, value);
}
@Test
public void testOP4J_009() throws Exception {
// Parsing a String number into a BigDecimal (no matter the decimal separator)
final Double result1 = Double.valueOf(871.21);
final Double result2 = Double.valueOf(421.441);
final String strValue1 = "871,21";
final String strValue2 = "421.441";
Double value1 =
Op.on(strValue1).exec(FnString.toDouble(DecimalPoint.CAN_BE_POINT_OR_COMMA)).get();
Double value2 =
Op.on(strValue2).exec(FnString.toDouble(DecimalPoint.CAN_BE_POINT_OR_COMMA)).get();
assertEquals(result1, value1);
assertEquals(result2, value2);
}
@Test
@SuppressWarnings("boxing")
public void testOP4J_010() throws Exception {
// Converting an array of Strings into a null-free array of Integers
final Integer[] result = new Integer[] { 431, 94, 398 };
final String[] strArray = new String[] { "431", null, "94", "398" };
{
Integer[] values =
Op.on(strArray).map(Types.INTEGER, FnString.toInteger()).removeAllNull().get();
assertEquals(Integer[].class, values.getClass());
assertEquals(Arrays.asList(result), Arrays.asList(values));
}
{
Integer[] values =
Op.on(strArray).forEach().exec(Types.INTEGER, FnString.toInteger()).endFor().removeAllNull().get();
assertEquals(Integer[].class, values.getClass());
assertEquals(Arrays.asList(result), Arrays.asList(values));
}
{
List<Integer> valuesList = new ArrayList<Integer>();
for (String element : strArray) {
if (element != null) {
valuesList.add(Integer.parseInt(element));
}
}
Integer[] values = valuesList.toArray(new Integer[valuesList.size()]);
assertEquals(Arrays.asList(result), Arrays.asList(values));
}
}
@Test
@SuppressWarnings("boxing")
public void testOP4J_011() throws Exception {
// Filtering numbers greater than a value out of a list
final List<Integer> result = Arrays.asList(new Integer[] { 53, 430 });
List<Integer> values = Arrays.asList(new Integer[] { 6641, 53, 430, 1245 });
final List<Integer> originalValues = values;
{
values =
Op.on(values).removeAllTrue(FnNumber.greaterThan(500)).get();
assertEquals(result, values);
}
values = originalValues;
{
List<Integer> valuesAux = new ArrayList<Integer>();
for (Integer value : values) {
if (value.longValue() <= 500) {
valuesAux.add(value);
}
}
values = valuesAux;
assertEquals(result, values);
}
}
@Test
public void testOP4J_012() throws Exception {
// Converting a list into an array
final String[] result = new String[] { "earth", "air", "fire", "water" };
List<String> elementList = Arrays.asList(new String[] { "earth", "air", "fire", "water" });
{
String[] elementArray =
Op.on(elementList).toArrayOf(Types.STRING).get();
assertEquals(String[].class, elementArray.getClass());
assertEquals(Arrays.asList(result), Arrays.asList(elementArray));
}
{
Set<String> elementSet =
Op.on(elementList).toSet().get();
assertEquals(Arrays.asList(result), new ArrayList<String>(elementSet));
}
{
String[] elementArray =
elementList.toArray(new String[elementList.size()]);
assertEquals(String[].class, elementArray.getClass());
assertEquals(Arrays.asList(result), Arrays.asList(elementArray));
}
}
@Test
public void testOP4J_013() throws Exception {
// Removing duplicates from an array (or list)
final String[] result = new String[] { "Lisboa", "Madrid", "Paris", "Bruxelles" };
String[] capitals = new String[] { "Lisboa", "Madrid", "Paris", "Lisboa", "Bruxelles" };
String[] originalCapitals = (String[]) ArrayUtils.clone(capitals);
{
capitals = Op.on(capitals).distinct().get();
assertEquals(String[].class, capitals.getClass());
assertEquals(Arrays.asList(result), Arrays.asList(capitals));
}
{
List<String> capitalList = Arrays.asList(originalCapitals);
// capitalList == LIST [ "Lisboa", "Madrid", "Paris", "Lisboa", "Bruxelles" ]
capitalList = Op.on(capitalList).distinct().get();
assertEquals(Arrays.asList(result), capitalList);
}
{
Set<String> capitalSet = new LinkedHashSet<String>();
for (String capital : capitals) {
capitalSet.add(capital);
}
capitals = capitalSet.toArray(new String[capitalSet.size()]);
assertEquals(String[].class, capitals.getClass());
assertEquals(Arrays.asList(result), Arrays.asList(capitals));
}
}
@Test
public void testOP4J_014() throws Exception {
// Sorting an array
final String[] result = new String[] { "Arctic", "Atlantic", "Indian", "Pacific", "Southern" };
String[] oceans = new String[] { "Pacific", "Atlantic", "Indian", "Arctic", "Southern" };
String[] originalOceans = (String[]) ArrayUtils.clone(oceans);
{
oceans = Op.on(oceans).sort().get();
assertEquals(String[].class, oceans.getClass());
assertEquals(Arrays.asList(result), Arrays.asList(oceans));
}
oceans = (String[]) ArrayUtils.clone(originalOceans);
{
List<String> oceansList = Arrays.asList(oceans);
Collections.sort(oceansList);
oceans = oceansList.toArray(new String[oceansList.size()]);
assertEquals(String[].class, oceans.getClass());
assertEquals(Arrays.asList(result), Arrays.asList(oceans));
}
}
@Test
public void testOP4J_015() throws Exception {
// Adding an element to an array
final String[] result = new String[] { "Lettuce", "Tomato", "Onion", "Olive Oil" };
String[] ingredients = new String[] { "Lettuce", "Tomato", "Onion" };
String[] originalIngredients = (String[]) ArrayUtils.clone(ingredients);
{
ingredients = Op.on(ingredients).add("Olive Oil").get();
assertEquals(String[].class, ingredients.getClass());
assertEquals(Arrays.asList(result), Arrays.asList(ingredients));
}
ingredients = (String[]) ArrayUtils.clone(originalIngredients);
{
final String[] result2 = new String[] { "Lettuce", "Tomato", "Onion", "Olive Oil", "Balsamic Vinegar" };
ingredients = Op.on(ingredients).addAll("Olive Oil", "Balsamic Vinegar").get();
assertEquals(String[].class, ingredients.getClass());
assertEquals(Arrays.asList(result2), Arrays.asList(ingredients));
}
ingredients = (String[]) ArrayUtils.clone(originalIngredients);
{
ingredients = Arrays.copyOf(ingredients, ingredients.length + 1);
ingredients[ingredients.length - 1] = "Olive Oil";
assertEquals(String[].class, ingredients.getClass());
assertEquals(Arrays.asList(result), Arrays.asList(ingredients));
}
}
@Test
public void testOP4J_016() throws Exception {
// Adding an element to an array at a specific position
final String[] result = new String[] { "Talc", "Fluorite", "Quartz", "Diamond" };
String[] minerals = new String[] { "Talc", "Quartz", "Diamond" };
String[] originalMinerals = (String[]) ArrayUtils.clone(minerals);
{
minerals = Op.on(minerals).insert(1 ,"Fluorite").get();
assertEquals(String[].class, minerals.getClass());
assertEquals(Arrays.asList(result), Arrays.asList(minerals));
}
minerals = (String[]) ArrayUtils.clone(originalMinerals);
{
final String[] result2 = new String[] { "Talc", "Fluorite", "Apatite", "Quartz", "Diamond" };
minerals = Op.on(minerals).insertAll(1, "Fluorite", "Apatite").get();
assertEquals(String[].class, minerals.getClass());
assertEquals(Arrays.asList(result2), Arrays.asList(minerals));
}
minerals = (String[]) ArrayUtils.clone(originalMinerals);
{
minerals = Arrays.copyOf(minerals, minerals.length + 1);
for (int i = (minerals.length - 1), z = 1; i > z; i
minerals[i] = minerals[i - 1];
}
minerals[1] = "Fluorite";
assertEquals(String[].class, minerals.getClass());
assertEquals(Arrays.asList(result), Arrays.asList(minerals));
}
}
@Test
public void testOP4J_017() throws Exception {
// Removing all accents (and other diacritics) from a String
String[] conts =
new String[] { "\u00C1frica", "Am\u00E9rica", "Ant\u00E1rtida", "Asia", "Europa", "Ocean\u00EDa" };
final String[] originalConts = conts.clone();
String[] result =
new String[] { "Africa", "America", "Antartida", "Asia", "Europa", "Oceania" };
String[] capsResult =
new String[] { "AFRICA", "AMERICA", "ANTARTIDA", "ASIA", "EUROPA", "OCEANIA" };
{
conts = Op.on(conts).map(FnString.asciify()).get();
assertEquals(String[].class, conts.getClass());
assertEquals(Arrays.asList(result), Arrays.asList(conts));
}
conts = originalConts.clone();
{
conts = Op.on(conts).forEach().exec(FnString.asciify()).exec(FnString.toUpperCase()).get();
assertEquals(String[].class, conts.getClass());
assertEquals(Arrays.asList(capsResult), Arrays.asList(conts));
}
conts = originalConts.clone();
{
conts = Op.on(conts).map(FnFunc.chain(FnString.asciify(), FnString.toUpperCase())).get();
assertEquals(String[].class, conts.getClass());
assertEquals(Arrays.asList(capsResult), Arrays.asList(conts));
}
}
@Test
@SuppressWarnings("boxing")
public void testOP4J_018() throws Exception {
// Creating a Calendar from day, month and year
{
Calendar result = Calendar.getInstance();
result.clear();
result.set(Calendar.DAY_OF_MONTH, 12);
result.set(Calendar.MONTH, Calendar.OCTOBER);
result.set(Calendar.YEAR, 1492);
Calendar date = Op.onListFor(1492, 10, 12).exec(FnCalendar.fieldIntegerListToCalendar()).get();
assertEquals(result.getTimeInMillis(), date.getTimeInMillis());
}
{
Calendar result = Calendar.getInstance();
result.clear();
result.set(Calendar.DAY_OF_MONTH, 12);
result.set(Calendar.MONTH, Calendar.OCTOBER);
result.set(Calendar.YEAR, 1492);
result.set(Calendar.HOUR_OF_DAY, 2);
result.set(Calendar.MINUTE, 34);
Calendar date = Op.onListFor(1492, 10, 12, 2, 34).exec(FnCalendar.fieldIntegerListToCalendar()).get();
assertEquals(result.getTimeInMillis(), date.getTimeInMillis());
}
}
@Test
public void testOP4J_019() throws Exception {
// Extract some text from a String using a regular expression
final String[] books =
new String[] {"Title=The Origin of Species; Price=24.90EUR",
"Title=Odyssey; Price=13.50EUR",
"Title=A Midsummer Night's Dream; Price=18.20EUR" };
final String[] resultTitles =
new String[] {"The Origin of Species",
"Odyssey",
"A Midsummer Night's Dream" };
{
final String regex = "Title=(.*?); Price(.*)";
String[] titles = Op.on(books).forEach().exec(FnString.matchAndExtract(regex, 1)).get();
assertEquals(String[].class, titles.getClass());
assertEquals(Arrays.asList(resultTitles), Arrays.asList(titles));
}
{
final String regex = "Title=(.*?); Price(.*)";
String[] titles = Op.on(books).map(FnString.matchAndExtract(regex, 1)).get();
assertEquals(String[].class, titles.getClass());
assertEquals(Arrays.asList(resultTitles), Arrays.asList(titles));
}
{
final String regex = "(.*?)=(.*?); (.*?)=(.*?)";
List<Map<String,String>> bookInfo =
Op.on(books).toList().forEach().
exec(FnString.matchAndExtractAll(regex, 1,2,3,4)).
exec(FnList.ofString().couple()).get();
assertEquals(3, bookInfo.size());
assertEquals("Title", bookInfo.get(0).entrySet().iterator().next().getKey());
assertEquals(resultTitles[0], bookInfo.get(0).get("Title"));
assertEquals("24.90EUR", bookInfo.get(0).get("Price"));
}
}
@Test
@SuppressWarnings("boxing")
public void testOP4J_020() throws Exception {
// Creating a map from its elements
Map<String,String> result = new LinkedHashMap<String, String>();
result.put("James Cheddar", "Finance");
result.put("Richard Stilton", "Engineering");
result.put("Bernard Brie", "Marketing");
result.put("Antonio Cabrales", "Sales");
{
Map<String,String> peopleDept =
Op.onMapFor("James Cheddar", "Finance").
and("Richard Stilton", "Engineering").
and("Bernard Brie", "Marketing").
and("Antonio Cabrales", "Sales").get();
assertEquals(result, peopleDept);
}
{
Map<String,String> peopleDept =
Op.onListFor(
"James Cheddar", "Finance", "Richard Stilton", "Engineering",
"Bernard Brie", "Marketing", "Antonio Cabrales", "Sales").
couple().get();
assertEquals(result, peopleDept);
}
{
Map<String,Integer> peopleYearsInCoRes = new LinkedHashMap<String, Integer>();
peopleYearsInCoRes.put("James Cheddar", 12);
peopleYearsInCoRes.put("Richard Stilton", 2);
peopleYearsInCoRes.put("Bernard Brie", 7);
peopleYearsInCoRes.put("Antonio Cabrales", 9);
Map<String,Integer> peopleYearsInCo =
Op.onMapFor("James Cheddar", 12).
and("Richard Stilton", 2).
and("Bernard Brie", 7).
and("Antonio Cabrales", 9).get();
assertEquals(peopleYearsInCoRes, peopleYearsInCo);
}
}
@Test
public void testOP4J_021() throws Exception {
// Creating a grouped map from a set of objects
Set<City> cities = new LinkedHashSet<City>();
City city1 = new City("Spain", "Santiago");
cities.add(city1);
City city2 = new City("Spain", "Barcelona");
cities.add(city2);
City city3 = new City("France", "Marseille");
cities.add(city3);
City city4 = new City("Portugal", "Porto");
cities.add(city4);
City city5 = new City("Portugal", "Lisboa");
cities.add(city5);
City city6 = new City("Portugal", "Viseu");
cities.add(city6);
Map<String,Set<String>> result = new LinkedHashMap<String,Set<String>>();
result.put("Spain",
new LinkedHashSet<String>(
Arrays.asList(new String[] {"Santiago", "Barcelona"})));
result.put("France",
new LinkedHashSet<String>(
Arrays.asList(new String[] {"Marseille"})));
result.put("Portugal",
new LinkedHashSet<String>(
Arrays.asList(new String[] {"Porto", "Lisboa", "Viseu"})));
{
Map<String,Set<String>> cityNamesByCountry =
Op.on(cities).toGroupMap(
Call.asString("getCountry"),Call.asString("getName")).get();
assertEquals(result, cityNamesByCountry);
}
{
Map<String,Set<String>> cityNamesByCountry =
new LinkedHashMap<String, Set<String>>();
for (City city : cities) {
Set<String> cityNamesForCountry =
cityNamesByCountry.get(city.getCountry());
if (cityNamesForCountry == null) {
cityNamesForCountry = new LinkedHashSet<String>();
cityNamesByCountry.put(city.getCountry(), cityNamesForCountry);
}
cityNamesForCountry.add(city.getName());
}
assertEquals(result, cityNamesByCountry);
}
}
/*
*
* ++++++++++++++++++++++++++++++++++++++++++++++++++++
* AUXILIARY CLASSES
* ++++++++++++++++++++++++++++++++++++++++++++++++++++
*
*/
protected static class User {
// empty
}
public static class City {
private final String country;
private final String name;
public City(String country, String name) {
super();
this.country = country;
this.name = name;
}
public String getCountry() {
return this.country;
}
public String getName() {
return this.name;
}
}
} |
package com.kryptnostic.rhizome.mappers;
import com.kryptnostic.rhizome.mapstores.MappingException;
public interface KeyMapper<K> {
public static final String ID_ATTRIBUTE = "id";
public static final String DEFAULT_SEPARATOR = ":";
/**
* @param key
* @return Object or String that can be serialized from key
* @throws MappingException
*/
String fromKey( K key ) throws MappingException;
K toKey( String value ) throws MappingException;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.