answer stringlengths 17 10.2M |
|---|
package gov.nih.nci.calab.dto.workflow;
import gov.nih.nci.calab.service.util.CalabConstants;
import gov.nih.nci.calab.service.util.PropertyReader;
import java.io.File;
import java.util.Date;
/**
* @author zengje
*
*/
public class FileBean {
private String id = "";
private String path = "";
private String filename = "";
private String createDateStr = "";
private String fileSubmitter = "";
private String fileMaskStatus = "";
private Date createdDate;
private String shortFilename = "";
private String inoutType = "";
public FileBean() {
super();
// TODO Auto-generated constructor stub
}
// used in WorkflowResultBean
public FileBean(String path, String fileSubmissionDate,
String fileSubmitter, String fileMaskStatus, String inoutType) {
this.path = path;
this.createDateStr = fileSubmissionDate;
this.fileSubmitter = fileSubmitter;
this.fileMaskStatus = fileMaskStatus;
this.filename = getFileName(path);
this.inoutType = inoutType;
}
public FileBean(String id, String path) {
super();
// TODO Auto-generated constructor stub
this.id = id;
this.path = path;
this.filename = getFileName(path);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
this.filename = getFileName(path);
}
public String getFilename() {
return filename;
}
// public void setFilename(String filename) {
// this.filename = filename;
private String getFileName(String path) {
String[] tokens = path.split("/");
return tokens[tokens.length-1];
}
public String getFileMaskStatus() {
return fileMaskStatus;
}
public void setFileMaskStatus(String fileMaskStatus) {
this.fileMaskStatus = fileMaskStatus;
}
public String getCreateDateStr() {
return createDateStr;
}
public void setCreateDateStr(String fileSubmissionDate) {
this.createDateStr = fileSubmissionDate;
}
public String getFileSubmitter() {
return fileSubmitter;
}
public void setFileSubmitter(String fileSubmitter) {
this.fileSubmitter = fileSubmitter;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getShortFilename() {
return shortFilename;
}
public void setShortFilename(String shortFileName) {
this.shortFilename = shortFileName;
}
public String getInoutType() {
return inoutType;
}
public void setInoutType(String inoutType) {
this.inoutType = inoutType;
}
} |
// Parameter.java
package imagej.ext.plugin;
import imagej.ext.module.ItemVisibility;
import imagej.ext.module.ui.WidgetStyle;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* An annotation for indicating a field is an input or output parameter. This
* annotation is a useful way for plugins to declare their inputs and outputs
* simply.
*
* @author Johannes Schindelin
* @author Grant Harris
* @author Curtis Rueden
* @see PluginModuleInfo
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Parameter {
/** Defines a label for the parameter. */
String label() default "";
/** Defines a description for the parameter. */
String description() default "";
/** Defines if the parameter is an output. */
boolean output() default false;
/**
* Defines the "visibility" of the parameter.
* <p>
* Choices are:
* <ul>
* <li>NORMAL: parameter is included in the history for purposes of data
* provenance, and included as a parameter when recording scripts.</li>
* <li>TRANSIENT: parameter is excluded from the history for the purposes of
* data provenance, but still included as a parameter when recording scripts.</li>
* <li>INVISIBLE: parameter is excluded from the history for the purposes of
* data provenance, and also excluded as a parameter when recording scripts.
* This option should only be used for parameters with no effect on the final
* output, such as a "verbose" flag.</li>
* <li>MESSAGE: parameter value is intended as a message only, not editable by
* the user nor included as an input or output parameter.</li>
* </ul>
*/
// NB: We use the fully qualified name to work around a javac bug:
// See:
ItemVisibility visibility() default imagej.ext.module.ItemVisibility.NORMAL;
/** Defines whether the parameter value must be specified (i.e., no default). */
boolean required() default false;
/** Defines whether to remember the most recent value of the parameter. */
boolean persist() default true;
/** Defines a key to use for saving the value persistently. */
String persistKey() default "";
/**
* Defines a function that is called whenever this parameter changes.
* <p>
* This mechanism enables interdependent parameters of various types. For
* example, two int parameters "width" and "height" could update each other
* when another boolean "Preserve aspect ratio" flag is set.
* </p>
*/
String callback() default "";
/** Defines the preferred widget style. */
// NB: We use the fully qualified name to work around a javac bug:
// See:
WidgetStyle style() default imagej.ext.module.ui.WidgetStyle.DEFAULT;
/** Defines the minimum allowed value (numeric parameters only). */
String min() default "";
/** Defines the maximum allowed value (numeric parameters only). */
String max() default "";
/** Defines the step size to use (numeric parameters only). */
String stepSize() default "";
/**
* Defines the width of the input field in characters (text field parameters
* only).
*/
int columns() default 6;
/** Defines the list of possible values (multiple choice text fields only). */
String[] choices() default {};
} |
package imagej.legacy;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import javassist.CannotCompileException;
import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewMethod;
import javassist.LoaderClassPath;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.expr.ConstructorCall;
import javassist.expr.ExprEditor;
import javassist.expr.MethodCall;
import javassist.expr.NewExpr;
/**
* The code hacker provides a mechanism for altering the behavior of classes
* before they are loaded, for the purpose of injecting new methods and/or
* altering existing ones.
* <p>
* In ImageJ, this mechanism is used to provide new seams into legacy ImageJ1
* code, so that (e.g.) the modern UI is aware of legacy ImageJ events as they
* occur.
* </p>
*
* @author Curtis Rueden
* @author Rick Lentz
* @author Johannes Schindelin
*/
public class CodeHacker {
private static final String PATCH_PKG = "imagej.legacy.patches";
private static final String PATCH_SUFFIX = "Methods";
private final ClassPool pool;
protected final ClassLoader classLoader;
private final Set<CtClass> handledClasses = new LinkedHashSet<CtClass>();
public CodeHacker(final ClassLoader classLoader, final ClassPool classPool) {
this.classLoader = classLoader;
pool = classPool != null ? classPool : ClassPool.getDefault();
pool.appendClassPath(new ClassClassPath(getClass()));
pool.appendClassPath(new LoaderClassPath(classLoader));
// the CodeHacker offers the LegacyService instance, therefore it needs to add that field here
insertPrivateStaticField("ij.IJ", LegacyService.class, "_legacyService");
insertNewMethod("ij.IJ",
"public static imagej.legacy.LegacyService getLegacyService()",
"return _legacyService;");
}
public CodeHacker(ClassLoader classLoader) {
this(classLoader, null);
}
/**
* Modifies a class by injecting additional code at the end of the specified
* method's body.
* <p>
* The extra code is defined in the imagej.legacy.patches package, as
* described in the documentation for {@link #insertNewMethod(String, String)}.
* </p>
*
* @param fullClass Fully qualified name of the class to modify.
* @param methodSig Method signature of the method to modify; e.g.,
* "public void updateAndDraw()"
*/
public void
insertAtBottomOfMethod(final String fullClass, final String methodSig)
{
insertAtBottomOfMethod(fullClass, methodSig, newCode(fullClass, methodSig));
}
/**
* Modifies a class by injecting the provided code string at the end of the
* specified method's body.
*
* @param fullClass Fully qualified name of the class to modify.
* @param methodSig Method signature of the method to modify; e.g.,
* "public void updateAndDraw()"
* @param newCode The string of code to add; e.g., System.out.println(\"Hello
* World!\");
*/
public void insertAtBottomOfMethod(final String fullClass,
final String methodSig, final String newCode)
{
try {
getMethod(fullClass, methodSig).insertAfter(expand(newCode));
}
catch (final CannotCompileException e) {
throw new IllegalArgumentException("Cannot modify method: " + methodSig,
e);
}
}
/**
* Modifies a class by injecting additional code at the start of the specified
* method's body.
* <p>
* The extra code is defined in the imagej.legacy.patches package, as
* described in the documentation for {@link #insertNewMethod(String, String)}.
* </p>
*
* @param fullClass Fully qualified name of the class to override.
* @param methodSig Method signature of the method to override; e.g.,
* "public void updateAndDraw()"
*/
public void
insertAtTopOfMethod(final String fullClass, final String methodSig)
{
insertAtTopOfMethod(fullClass, methodSig, newCode(fullClass, methodSig));
}
/**
* Modifies a class by injecting the provided code string at the start of the
* specified method's body.
*
* @param fullClass Fully qualified name of the class to override.
* @param methodSig Method signature of the method to override; e.g.,
* "public void updateAndDraw()"
* @param newCode The string of code to add; e.g., System.out.println(\"Hello
* World!\");
*/
public void insertAtTopOfMethod(final String fullClass,
final String methodSig, final String newCode)
{
try {
getMethod(fullClass, methodSig).insertBefore(expand(newCode));
}
catch (final CannotCompileException e) {
throw new IllegalArgumentException("Cannot modify method: " + methodSig,
e);
}
}
/**
* Modifies a class by injecting a new method.
* <p>
* The body of the method is defined in the imagej.legacy.patches package, as
* described in the {@link #insertNewMethod(String, String)} method
* documentation.
* <p>
* The new method implementation should be declared in the
* imagej.legacy.patches package, with the same name as the original class
* plus "Methods"; e.g., overridden ij.gui.ImageWindow methods should be
* placed in the imagej.legacy.patches.ImageWindowMethods class.
* </p>
* <p>
* New method implementations must be public static, with an additional first
* parameter: the instance of the class on which to operate.
* </p>
*
* @param fullClass Fully qualified name of the class to override.
* @param methodSig Method signature of the method to override; e.g.,
* "public void setVisible(boolean vis)"
*/
public void insertNewMethod(final String fullClass, final String methodSig) {
insertNewMethod(fullClass, methodSig, newCode(fullClass, methodSig));
}
/**
* Modifies a class by injecting the provided code string as a new method.
*
* @param fullClass Fully qualified name of the class to override.
* @param methodSig Method signature of the method to override; e.g.,
* "public void updateAndDraw()"
* @param newCode The string of code to add; e.g., System.out.println(\"Hello
* World!\");
*/
public void insertNewMethod(final String fullClass, final String methodSig,
final String newCode)
{
final CtClass classRef = getClass(fullClass);
final String methodBody = methodSig + " { " + expand(newCode) + " } ";
try {
final CtMethod methodRef = CtNewMethod.make(methodBody, classRef);
classRef.addMethod(methodRef);
}
catch (final CannotCompileException e) {
throw new IllegalArgumentException("Cannot add method: " + methodSig, e);
}
}
/*
* Works around a bug where the horizontal scroll wheel of the mighty mouse is mistaken for a popup trigger.
*/
public void handleMightyMousePressed(final String fullClass) {
ExprEditor editor = new ExprEditor() {
@Override
public void edit(MethodCall call) throws CannotCompileException {
if (call.getMethodName().equals("isPopupTrigger"))
call.replace("$_ = $0.isPopupTrigger() && $0.getButton() != 0;");
}
};
final CtClass classRef = getClass(fullClass);
for (final String methodName : new String[] { "mousePressed", "mouseDragged" }) try {
final CtMethod method = classRef.getMethod(methodName, "(Ljava/awt/event/MouseEvent;)V");
method.instrument(editor);
} catch (NotFoundException e) {
/* ignore */
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Cannot instrument method: " + methodName, e);
}
}
public void insertPrivateStaticField(final String fullClass,
final Class<?> clazz, final String name) {
final CtClass classRef = getClass(fullClass);
try {
final CtField field = new CtField(pool.get(clazz.getName()), name,
classRef);
field.setModifiers(Modifier.PRIVATE | Modifier.STATIC);
classRef.addField(field);
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Cannot add field " + name
+ " to " + fullClass, e);
} catch (NotFoundException e) {
throw new IllegalArgumentException("Cannot add field " + name
+ " to " + fullClass, e);
}
}
/**
* Replaces the given methods with stub methods.
*
* @param fullClass the class to patch
* @param methodNames the names of the methods to replace
* @throws NotFoundException
* @throws CannotCompileException
*/
public void replaceWithStubMethods(final String fullClass, final String... methodNames) {
final CtClass clazz = getClass(fullClass);
final Set<String> override = new HashSet<String>(Arrays.asList(methodNames));
for (final CtMethod method : clazz.getMethods())
if (override.contains(method.getName())) try {
final CtMethod stub = makeStubMethod(clazz, method);
method.setBody(stub, null);
} catch (NotFoundException e) {
// ignore
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Cannot instrument method: " + method.getName(), e);
}
}
/**
* Replaces the superclass.
*
* @param fullClass
* @param fullNewSuperclass
* @throws NotFoundException
*/
public void replaceSuperclass(String fullClass, String fullNewSuperclass) {
final CtClass clazz = getClass(fullClass);
try {
CtClass originalSuperclass = clazz.getSuperclass();
clazz.setSuperclass(getClass(fullNewSuperclass));
for (final CtConstructor ctor : clazz.getConstructors())
ctor.instrument(new ExprEditor() {
@Override
public void edit(final ConstructorCall call) throws CannotCompileException {
if (call.getMethodName().equals("super"))
call.replace("super();");
}
});
letSuperclassMethodsOverride(clazz);
addMissingMethods(clazz, originalSuperclass);
} catch (NotFoundException e) {
throw new IllegalArgumentException("Could not replace superclass of " + fullClass + " with " + fullNewSuperclass, e);
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Could not replace superclass of " + fullClass + " with " + fullNewSuperclass, e);
}
}
/**
* Replaces all instantiations of a subset of AWT classes with nulls.
*
* This is used by the partial headless support of legacy code.
*
* @param fullClass
* @throws CannotCompileException
* @throws NotFoundException
*/
public void skipAWTInstantiations(String fullClass) {
try {
skipAWTInstantiations(getClass(fullClass));
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Could not skip AWT class instantiations in " + fullClass, e);
} catch (NotFoundException e) {
throw new IllegalArgumentException("Could not skip AWT class instantiations in " + fullClass, e);
}
}
/**
* Loads the given, possibly modified, class.
* <p>
* This method must be called to confirm any changes made with
* {@link #insertAfterMethod}, {@link #insertBeforeMethod},
* or {@link #insertMethod}.
* </p>
*
* @param fullClass Fully qualified class name to load.
* @return the loaded class
*/
public Class<?> loadClass(final String fullClass) {
final CtClass classRef = getClass(fullClass);
return loadClass(classRef);
}
/**
* Loads the given, possibly modified, class.
* <p>
* This method must be called to confirm any changes made with
* {@link #insertAfterMethod}, {@link #insertBeforeMethod},
* or {@link #insertMethod}.
* </p>
*
* @param classRef class to load.
* @return the loaded class
*/
public Class<?> loadClass(final CtClass classRef) {
try {
return classRef.toClass(classLoader, null);
}
catch (final CannotCompileException e) {
// Cannot use LogService; it will not be initialized by the time the DefaultLegacyService
// class is loaded, which is when the CodeHacker is run
System.err.println("Warning: Cannot load class: " + classRef.getName());
e.printStackTrace();
return null;
} finally {
classRef.freeze();
}
}
public void loadClasses() {
final Iterator<CtClass> iter = handledClasses.iterator();
while (iter.hasNext()) {
final CtClass classRef = iter.next();
if (!classRef.isFrozen() && classRef.isModified()) {
loadClass(classRef);
}
iter.remove();
}
}
/** Gets the Javassist class object corresponding to the given class name. */
private CtClass getClass(final String fullClass) {
try {
final CtClass classRef = pool.get(fullClass);
if (classRef.getClassPool() == pool) handledClasses.add(classRef);
return classRef;
}
catch (final NotFoundException e) {
throw new IllegalArgumentException("No such class: " + fullClass, e);
}
}
/**
* Gets the Javassist method object corresponding to the given method
* signature of the specified class name.
*/
private CtMethod getMethod(final String fullClass, final String methodSig) {
final CtClass cc = getClass(fullClass);
final String name = getMethodName(methodSig);
final String[] argTypes = getMethodArgTypes(methodSig);
final CtClass[] params = new CtClass[argTypes.length];
for (int i = 0; i < params.length; i++) {
params[i] = getClass(argTypes[i]);
}
try {
return cc.getDeclaredMethod(name, params);
}
catch (final NotFoundException e) {
throw new IllegalArgumentException("No such method: " + methodSig, e);
}
}
/**
* Generates a new line of code calling the {@link imagej.legacy.patches}
* class and method corresponding to the given method signature.
*/
private String newCode(final String fullClass, final String methodSig) {
final int dotIndex = fullClass.lastIndexOf(".");
final String className = fullClass.substring(dotIndex + 1);
final String methodName = getMethodName(methodSig);
final boolean isStatic = isStatic(methodSig);
final boolean isVoid = isVoid(methodSig);
final String patchClass = PATCH_PKG + "." + className + PATCH_SUFFIX;
for (final CtMethod method : getClass(patchClass).getMethods()) try {
if ((method.getModifiers() & Modifier.STATIC) == 0) continue;
final CtClass[] types = method.getParameterTypes();
if (types.length == 0 || !types[0].getName().equals("imagej.legacy.LegacyService")) {
throw new UnsupportedOperationException("Method " + method + " of class " + patchClass + " has wrong type!");
}
} catch (NotFoundException e) {
e.printStackTrace();
}
final StringBuilder newCode =
new StringBuilder((isVoid ? "" : "return ") + patchClass + "." + methodName + "(");
newCode.append("$service");
if (!isStatic) {
newCode.append(", this");
}
final int argCount = getMethodArgTypes(methodSig).length;
for (int i = 1; i <= argCount; i++) {
newCode.append(", $" + i);
}
newCode.append(");");
return newCode.toString();
}
/** Patches in the current legacy service for '$service' */
private String expand(final String code) {
return code
.replace("$isLegacyMode()", "$service.isLegacyMode()")
.replace("$service", "ij.IJ.getLegacyService()");
}
/** Extracts the method name from the given method signature. */
private String getMethodName(final String methodSig) {
final int parenIndex = methodSig.indexOf("(");
final int spaceIndex = methodSig.lastIndexOf(" ", parenIndex);
return methodSig.substring(spaceIndex + 1, parenIndex);
}
private String[] getMethodArgTypes(final String methodSig) {
final int parenIndex = methodSig.indexOf("(");
final String methodArgs =
methodSig.substring(parenIndex + 1, methodSig.length() - 1);
final String[] args =
methodArgs.equals("") ? new String[0] : methodArgs.split(",");
for (int i = 0; i < args.length; i++) {
args[i] = args[i].trim().split(" ")[0];
}
return args;
}
/** Returns true if the given method signature is static. */
private boolean isStatic(final String methodSig) {
final int parenIndex = methodSig.indexOf("(");
final String methodPrefix = methodSig.substring(0, parenIndex);
for (final String token : methodPrefix.split(" ")) {
if (token.equals("static")) return true;
}
return false;
}
/** Returns true if the given method signature returns void. */
private boolean isVoid(final String methodSig) {
final int parenIndex = methodSig.indexOf("(");
final String methodPrefix = methodSig.substring(0, parenIndex);
return methodPrefix.startsWith("void ") ||
methodPrefix.indexOf(" void ") > 0;
}
private static int verboseLevel = 0;
private static CtMethod makeStubMethod(CtClass clazz, CtMethod original) throws CannotCompileException, NotFoundException {
// add a stub
String prefix = "";
if (verboseLevel > 0) {
prefix = "System.err.println(\"Called " + original.getLongName() + "\\n\"";
if (verboseLevel > 1) {
prefix += "+ \"\\t(\" + fiji.Headless.toString($args) + \")\\n\"";
}
prefix += ");";
}
CtClass type = original.getReturnType();
String body = "{" +
prefix +
(type == CtClass.voidType ? "" : "return " + defaultReturnValue(type) + ";") +
"}";
CtClass[] types = original.getParameterTypes();
return CtNewMethod.make(type, original.getName(), types, new CtClass[0], body, clazz);
}
private static String defaultReturnValue(CtClass type) {
return (type == CtClass.booleanType ? "false" :
(type == CtClass.byteType ? "(byte)0" :
(type == CtClass.charType ? "'\0'" :
(type == CtClass.doubleType ? "0.0" :
(type == CtClass.floatType ? "0.0f" :
(type == CtClass.intType ? "0" :
(type == CtClass.longType ? "0l" :
(type == CtClass.shortType ? "(short)0" : "null"))))))));
}
private void addMissingMethods(CtClass fakeClass, CtClass originalClass) throws CannotCompileException, NotFoundException {
if (verboseLevel > 0)
System.err.println("adding missing methods from " + originalClass.getName() + " to " + fakeClass.getName());
Set<String> available = new HashSet<String>();
for (CtMethod method : fakeClass.getMethods())
available.add(stripPackage(method.getLongName()));
for (CtMethod original : originalClass.getDeclaredMethods()) {
if (available.contains(stripPackage(original.getLongName()))) {
if (verboseLevel > 1)
System.err.println("Skipping available method " + original);
continue;
}
CtMethod method = makeStubMethod(fakeClass, original);
fakeClass.addMethod(method);
if (verboseLevel > 1)
System.err.println("adding missing method " + method);
}
// interfaces
Set<CtClass> availableInterfaces = new HashSet<CtClass>();
for (CtClass iface : fakeClass.getInterfaces())
availableInterfaces.add(iface);
for (CtClass iface : originalClass.getInterfaces())
if (!availableInterfaces.contains(iface))
fakeClass.addInterface(iface);
CtClass superClass = originalClass.getSuperclass();
if (superClass != null && !superClass.getName().equals("java.lang.Object"))
addMissingMethods(fakeClass, superClass);
}
private void letSuperclassMethodsOverride(CtClass clazz) throws CannotCompileException, NotFoundException {
for (CtMethod method : clazz.getSuperclass().getDeclaredMethods()) {
CtMethod method2 = clazz.getMethod(method.getName(), method.getSignature());
if (method2.getDeclaringClass().equals(clazz)) {
method2.setBody(method, null); // make sure no calls/accesses to GUI components are remaining
method2.setName("narf" + method.getName());
}
}
}
private static String stripPackage(String className) {
int lastDot = -1;
for (int i = 0; ; i++) {
if (i >= className.length())
return className.substring(lastDot + 1);
char c = className.charAt(i);
if (c == '.' || c == '$')
lastDot = i;
else if (c >= 'A' && c <= 'Z')
; // continue
else if (c >= 'a' && c <= 'z')
; // continue
else if (i > lastDot + 1 && c >= '0' && c <= '9')
; // continue
else
return className.substring(lastDot + 1);
}
}
private void skipAWTInstantiations(CtClass clazz) throws CannotCompileException, NotFoundException {
clazz.instrument(new ExprEditor() {
@Override
public void edit(NewExpr expr) throws CannotCompileException {
String name = expr.getClassName();
if (name.startsWith("java.awt.Menu") || name.equals("java.awt.PopupMenu") ||
name.startsWith("java.awt.Checkbox") || name.equals("java.awt.Frame")) {
expr.replace("$_ = null;");
} else if (expr.getClassName().equals("ij.gui.StackWindow")) {
expr.replace("$1.show(); $_ = null;");
}
}
@Override
public void edit(MethodCall call) throws CannotCompileException {
final String className = call.getClassName();
final String methodName = call.getMethodName();
if (className.startsWith("java.awt.Menu") || className.equals("java.awt.PopupMenu") ||
className.startsWith("java.awt.Checkbox")) try {
CtClass type = call.getMethod().getReturnType();
if (type == CtClass.voidType) {
call.replace("");
} else {
call.replace("$_ = " + defaultReturnValue(type) + ";");
}
} catch (NotFoundException e) {
e.printStackTrace();
} else if (methodName.equals("put") && className.equals("java.util.Properties")) {
call.replace("if ($1 != null && $2 != null) $_ = $0.put($1, $2); else $_ = null;");
} else if (methodName.equals("get") && className.equals("java.util.Properties")) {
call.replace("$_ = $1 != null ? $0.get($1) : null;");
} else if (className.equals("java.lang.Integer") && methodName.equals("intValue")) {
call.replace("$_ = $0 == null ? 0 : $0.intValue();");
} else if (methodName.equals("addTextListener")) {
call.replace("");
} else if (methodName.equals("elementAt")) {
call.replace("$_ = $0 == null ? null : $0.elementAt($$);");
}
}
});
}
} |
package imagej.legacy;
import java.net.URL;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import org.scijava.util.ClassUtils;
import javassist.CannotCompileException;
import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtBehavior;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewConstructor;
import javassist.CtNewMethod;
import javassist.LoaderClassPath;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.expr.ConstructorCall;
import javassist.expr.ExprEditor;
import javassist.expr.MethodCall;
import javassist.expr.NewExpr;
/**
* The code hacker provides a mechanism for altering the behavior of classes
* before they are loaded, for the purpose of injecting new methods and/or
* altering existing ones.
* <p>
* In ImageJ, this mechanism is used to provide new seams into legacy ImageJ1
* code, so that (e.g.) the modern UI is aware of legacy ImageJ events as they
* occur.
* </p>
*
* @author Curtis Rueden
* @author Rick Lentz
* @author Johannes Schindelin
*/
public class CodeHacker {
private static final String PATCH_PKG = "imagej.legacy.patches";
private static final String PATCH_SUFFIX = "Methods";
private final ClassPool pool;
protected final ClassLoader classLoader;
private final Set<CtClass> handledClasses = new LinkedHashSet<CtClass>();
public CodeHacker(final ClassLoader classLoader, final ClassPool classPool) {
this.classLoader = classLoader;
pool = classPool != null ? classPool : ClassPool.getDefault();
pool.appendClassPath(new ClassClassPath(getClass()));
pool.appendClassPath(new LoaderClassPath(classLoader));
// the CodeHacker offers the LegacyService instance, therefore it needs to add that field here
if (!hasField("ij.IJ", "_legacyService")) {
insertPrivateStaticField("ij.IJ", LegacyService.class, "_legacyService");
insertNewMethod("ij.IJ",
"public static imagej.legacy.LegacyService getLegacyService()",
"return _legacyService;");
}
}
public CodeHacker(ClassLoader classLoader) {
this(classLoader, null);
}
/**
* Modifies a class by injecting additional code at the end of the specified
* method's body.
* <p>
* The extra code is defined in the imagej.legacy.patches package, as
* described in the documentation for {@link #insertNewMethod(String, String)}.
* </p>
*
* @param fullClass Fully qualified name of the class to modify.
* @param methodSig Method signature of the method to modify; e.g.,
* "public void updateAndDraw()"
*/
public void
insertAtBottomOfMethod(final String fullClass, final String methodSig)
{
insertAtBottomOfMethod(fullClass, methodSig, newCode(fullClass, methodSig));
}
/**
* Modifies a class by injecting the provided code string at the end of the
* specified method's body.
*
* @param fullClass Fully qualified name of the class to modify.
* @param methodSig Method signature of the method to modify; e.g.,
* "public void updateAndDraw()"
* @param newCode The string of code to add; e.g., System.out.println(\"Hello
* World!\");
*/
public void insertAtBottomOfMethod(final String fullClass,
final String methodSig, final String newCode)
{
try {
getMethod(fullClass, methodSig).insertAfter(expand(newCode));
}
catch (final CannotCompileException e) {
throw new IllegalArgumentException("Cannot modify method: " + methodSig,
e);
}
}
/**
* Modifies a class by injecting additional code at the start of the specified
* method's body.
* <p>
* The extra code is defined in the imagej.legacy.patches package, as
* described in the documentation for {@link #insertNewMethod(String, String)}.
* </p>
*
* @param fullClass Fully qualified name of the class to override.
* @param methodSig Method signature of the method to override; e.g.,
* "public void updateAndDraw()"
*/
public void
insertAtTopOfMethod(final String fullClass, final String methodSig)
{
insertAtTopOfMethod(fullClass, methodSig, newCode(fullClass, methodSig));
}
/**
* Modifies a class by injecting the provided code string at the start of the
* specified method's body.
*
* @param fullClass Fully qualified name of the class to override.
* @param methodSig Method signature of the method to override; e.g.,
* "public void updateAndDraw()"
* @param newCode The string of code to add; e.g., System.out.println(\"Hello
* World!\");
*/
public void insertAtTopOfMethod(final String fullClass,
final String methodSig, final String newCode)
{
try {
getMethod(fullClass, methodSig).insertBefore(expand(newCode));
}
catch (final CannotCompileException e) {
throw new IllegalArgumentException("Cannot modify method: " + methodSig,
e);
}
}
/**
* Modifies a class by injecting a new method.
* <p>
* The body of the method is defined in the imagej.legacy.patches package, as
* described in the {@link #insertNewMethod(String, String)} method
* documentation.
* <p>
* The new method implementation should be declared in the
* imagej.legacy.patches package, with the same name as the original class
* plus "Methods"; e.g., overridden ij.gui.ImageWindow methods should be
* placed in the imagej.legacy.patches.ImageWindowMethods class.
* </p>
* <p>
* New method implementations must be public static, with an additional first
* parameter: the instance of the class on which to operate.
* </p>
*
* @param fullClass Fully qualified name of the class to override.
* @param methodSig Method signature of the method to override; e.g.,
* "public void setVisible(boolean vis)"
*/
public void insertNewMethod(final String fullClass, final String methodSig) {
insertNewMethod(fullClass, methodSig, newCode(fullClass, methodSig));
}
/**
* Modifies a class by injecting the provided code string as a new method.
*
* @param fullClass Fully qualified name of the class to override.
* @param methodSig Method signature of the method to override; e.g.,
* "public void updateAndDraw()"
* @param newCode The string of code to add; e.g., System.out.println(\"Hello
* World!\");
*/
public void insertNewMethod(final String fullClass, final String methodSig,
final String newCode)
{
final CtClass classRef = getClass(fullClass);
final String methodBody = methodSig + " { " + expand(newCode) + " } ";
try {
final CtMethod methodRef = CtNewMethod.make(methodBody, classRef);
classRef.addMethod(methodRef);
}
catch (final CannotCompileException e) {
throw new IllegalArgumentException("Cannot add method: " + methodSig, e);
}
}
/*
* Works around a bug where the horizontal scroll wheel of the mighty mouse is mistaken for a popup trigger.
*/
public void handleMightyMousePressed(final String fullClass) {
ExprEditor editor = new ExprEditor() {
@Override
public void edit(MethodCall call) throws CannotCompileException {
if (call.getMethodName().equals("isPopupTrigger"))
call.replace("$_ = $0.isPopupTrigger() && $0.getButton() != 0;");
}
};
final CtClass classRef = getClass(fullClass);
for (final String methodName : new String[] { "mousePressed", "mouseDragged" }) try {
final CtMethod method = classRef.getMethod(methodName, "(Ljava/awt/event/MouseEvent;)V");
method.instrument(editor);
} catch (NotFoundException e) {
/* ignore */
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Cannot instrument method: " + methodName, e);
}
}
public void insertPrivateStaticField(final String fullClass,
final Class<?> clazz, final String name) {
insertStaticField(fullClass, Modifier.PRIVATE, clazz, name, null);
}
public void insertPublicStaticField(final String fullClass,
final Class<?> clazz, final String name, final String initializer) {
insertStaticField(fullClass, Modifier.PUBLIC, clazz, name, initializer);
}
public void insertStaticField(final String fullClass, int modifiers,
final Class<?> clazz, final String name, final String initializer) {
final CtClass classRef = getClass(fullClass);
try {
final CtField field = new CtField(pool.get(clazz.getName()), name,
classRef);
field.setModifiers(modifiers | Modifier.STATIC);
classRef.addField(field);
if (initializer != null) {
addToClassInitializer(fullClass, name + " = " + initializer + ";");
}
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Cannot add field " + name
+ " to " + fullClass, e);
} catch (NotFoundException e) {
throw new IllegalArgumentException("Cannot add field " + name
+ " to " + fullClass, e);
}
}
public void addToClassInitializer(final String fullClass, final String code) {
final CtClass classRef = getClass(fullClass);
try {
CtConstructor method = classRef.getClassInitializer();
if (method != null) {
method.insertAfter(code);
} else {
method = CtNewConstructor.make(new CtClass[0], new CtClass[0], code, classRef);
method.getMethodInfo().setName("<clinit>");
method.setModifiers(Modifier.STATIC);
classRef.addConstructor(method);
}
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Cannot add " + code
+ " to class initializer of " + fullClass, e);
}
}
/**
* Replaces the application name in the given method in the given parameter
* to the given constructor call.
*
* Fails silently if the specified method does not exist (e.g.
* CommandFinder's export() function just went away in 1.47i).
*
* @param fullClass
* Fully qualified name of the class to override.
* @param methodSig
* Method signature of the method to override; e.g.,
* "public void showMessage(String title, String message)"
* @param newClassName
* the name of the class which is to be constructed by the new
* operator
* @param parameterIndex
* the index of the parameter containing the application name
* @param replacement
* the code to use instead of the specified parameter
* @throws CannotCompileException
*/
private void replaceParameterInNew(final String fullClass,
final String methodSig, final String newClassName,
final int parameterIndex, final String replacement) {
try {
final CtMethod method = getMethod(fullClass, methodSig);
method.instrument(new ExprEditor() {
@Override
public void edit(NewExpr expr) throws CannotCompileException {
if (expr.getClassName().equals(newClassName))
try {
final CtClass[] parameterTypes = expr
.getConstructor().getParameterTypes();
if (parameterTypes[parameterIndex] != CodeHacker.this
.getClass("java.lang.String")) {
throw new IllegalArgumentException("Parameter "
+ parameterIndex + " of "
+ expr.getConstructor() + " is not a String!");
}
final String replace = replaceParameter(
parameterIndex, parameterTypes.length, replacement);
expr.replace("$_ = new " + newClassName + replace
+ ";");
} catch (NotFoundException e) {
throw new IllegalArgumentException(
"Cannot find the parameters of the constructor of "
+ newClassName, e);
}
}
});
} catch (IllegalArgumentException e) {
// ignore: the method was not found
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Cannot handle app name in " + fullClass
+ "'s " + methodSig, e);
}
}
/**
* Replaces the application name in the given method in the given parameter
* to the given method call.
*
* Fails silently if the specified method does not exist (e.g.
* CommandFinder's export() function just went away in 1.47i).
*
* @param fullClass
* Fully qualified name of the class to override.
* @param methodSig
* Method signature of the method to override; e.g.,
* "public void showMessage(String title, String message)"
* @param calledMethodName
* the name of the method to which the application name is passed
* @param parameterIndex
* the index of the parameter containing the application name
* @param replacement
* the code to use instead of the specified parameter
* @throws CannotCompileException
*/
private void replaceParameterInCall(final String fullClass,
final String methodSig, final String calledMethodName,
final int parameterIndex, final String replacement) {
try {
final CtBehavior method;
if (methodSig.indexOf("<init>") < 0) {
method = getMethod(fullClass, methodSig);
} else {
method = getConstructor(fullClass, methodSig);
}
method.instrument(new ExprEditor() {
@Override
public void edit(MethodCall call) throws CannotCompileException {
if (call.getMethodName().equals(calledMethodName)) try {
final CtClass[] parameterTypes = call.getMethod().getParameterTypes();
if (parameterTypes.length < parameterIndex) {
throw new IllegalArgumentException("Index " + parameterIndex + " is outside of " + call.getMethod() + "'s parameter list!");
}
if (parameterTypes[parameterIndex - 1] != CodeHacker.this.getClass("java.lang.String")) {
throw new IllegalArgumentException("Parameter " + parameterIndex + " of "
+ call.getMethod() + " is not a String!");
}
final String replace = replaceParameter(
parameterIndex, parameterTypes.length, replacement);
call.replace("$0." + calledMethodName + replace + ";");
} catch (NotFoundException e) {
throw new IllegalArgumentException(
"Cannot find the parameters of the method "
+ calledMethodName, e);
}
}
});
} catch (IllegalArgumentException e) {
// ignore: the method was not found
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Cannot handle app name in " + fullClass
+ "'s " + methodSig, e);
}
}
private String replaceParameter(final int parameterIndex, final int parameterCount, final String replacement) {
final StringBuilder builder = new StringBuilder();
builder.append("(");
for (int i = 1; i <= parameterCount; i++) {
if (i > 1) {
builder.append(", ");
}
builder.append("$").append(i);
if (i == parameterIndex) {
builder.append(".replace(\"ImageJ\", " + replacement + ")");
}
}
builder.append(")");
return builder.toString();
}
/**
* Replaces the given methods with stub methods.
*
* @param fullClass the class to patch
* @param methodNames the names of the methods to replace
* @throws NotFoundException
* @throws CannotCompileException
*/
public void replaceWithStubMethods(final String fullClass, final String... methodNames) {
final CtClass clazz = getClass(fullClass);
final Set<String> override = new HashSet<String>(Arrays.asList(methodNames));
for (final CtMethod method : clazz.getMethods())
if (override.contains(method.getName())) try {
final CtMethod stub = makeStubMethod(clazz, method);
method.setBody(stub, null);
} catch (NotFoundException e) {
// ignore
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Cannot instrument method: " + method.getName(), e);
}
}
/**
* Replaces the superclass.
*
* @param fullClass
* @param fullNewSuperclass
* @throws NotFoundException
*/
public void replaceSuperclass(String fullClass, String fullNewSuperclass) {
final CtClass clazz = getClass(fullClass);
try {
CtClass originalSuperclass = clazz.getSuperclass();
clazz.setSuperclass(getClass(fullNewSuperclass));
for (final CtConstructor ctor : clazz.getConstructors())
ctor.instrument(new ExprEditor() {
@Override
public void edit(final ConstructorCall call) throws CannotCompileException {
if (call.getMethodName().equals("super"))
call.replace("super();");
}
});
letSuperclassMethodsOverride(clazz);
addMissingMethods(clazz, originalSuperclass);
} catch (NotFoundException e) {
throw new IllegalArgumentException("Could not replace superclass of " + fullClass + " with " + fullNewSuperclass, e);
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Could not replace superclass of " + fullClass + " with " + fullNewSuperclass, e);
}
}
/**
* Replaces all instantiations of a subset of AWT classes with nulls.
*
* This is used by the partial headless support of legacy code.
*
* @param fullClass
* @throws CannotCompileException
* @throws NotFoundException
*/
public void skipAWTInstantiations(String fullClass) {
try {
skipAWTInstantiations(getClass(fullClass));
} catch (CannotCompileException e) {
throw new IllegalArgumentException("Could not skip AWT class instantiations in " + fullClass, e);
} catch (NotFoundException e) {
throw new IllegalArgumentException("Could not skip AWT class instantiations in " + fullClass, e);
}
}
/**
* Loads the given, possibly modified, class.
* <p>
* This method must be called to confirm any changes made with
* {@link #insertAfterMethod}, {@link #insertBeforeMethod},
* or {@link #insertMethod}.
* </p>
*
* @param fullClass Fully qualified class name to load.
* @return the loaded class
*/
public Class<?> loadClass(final String fullClass) {
final CtClass classRef = getClass(fullClass);
return loadClass(classRef);
}
/**
* Loads the given, possibly modified, class.
* <p>
* This method must be called to confirm any changes made with
* {@link #insertAfterMethod}, {@link #insertBeforeMethod},
* or {@link #insertMethod}.
* </p>
*
* @param classRef class to load.
* @return the loaded class
*/
public Class<?> loadClass(final CtClass classRef) {
try {
return classRef.toClass(classLoader, null);
}
catch (final CannotCompileException e) {
// Cannot use LogService; it will not be initialized by the time the DefaultLegacyService
// class is loaded, which is when the CodeHacker is run
if (e.getCause() != null && e.getCause() instanceof LinkageError) {
final URL url = ClassUtils.getLocation(LegacyJavaAgent.class);
final String path = url != null && "file".equals(url.getProtocol()) && url.getPath().endsWith(".jar")?
url.getPath() : "/path/to/ij-legacy.jar";
throw new RuntimeException("Cannot load class: " + classRef.getName() + "\n"
+ "It appears that this class was already defined in the class loader!\n"
+ "Please make sure that you initialize the LegacyService before using\n"
+ "any ImageJ 1.x class. You can do that by adding this static initializer:\n\n"
+ "\tstatic {\n"
+ "\t\tDefaultLegacyService.preinit();\n"
+ "\t}\n\n"
+ "To debug this issue, start the JVM with the option:\n\n"
+ "\t-javaagent:" + path + "\n\n"
+ "To enforce pre-initialization, start the JVM with the option:\n\n"
+ "\t-javaagent:" + path + "=init\n", e.getCause());
}
System.err.println("Warning: Cannot load class: " + classRef.getName() + " into " + classLoader);
e.printStackTrace();
return null;
} finally {
classRef.freeze();
}
}
public void loadClasses() {
final Iterator<CtClass> iter = handledClasses.iterator();
while (iter.hasNext()) {
final CtClass classRef = iter.next();
if (!classRef.isFrozen() && classRef.isModified()) {
loadClass(classRef);
}
iter.remove();
}
}
/** Gets the Javassist class object corresponding to the given class name. */
private CtClass getClass(final String fullClass) {
try {
final CtClass classRef = pool.get(fullClass);
if (classRef.getClassPool() == pool) handledClasses.add(classRef);
return classRef;
}
catch (final NotFoundException e) {
throw new IllegalArgumentException("No such class: " + fullClass, e);
}
}
/**
* Gets the Javassist method object corresponding to the given method
* signature of the specified class name.
*/
private CtMethod getMethod(final String fullClass, final String methodSig) {
final CtClass cc = getClass(fullClass);
final String name = getMethodName(methodSig);
final String[] argTypes = getMethodArgTypes(methodSig);
final CtClass[] params = new CtClass[argTypes.length];
for (int i = 0; i < params.length; i++) {
params[i] = getClass(argTypes[i]);
}
try {
return cc.getDeclaredMethod(name, params);
}
catch (final NotFoundException e) {
throw new IllegalArgumentException("No such method: " + methodSig, e);
}
}
/**
* Gets the Javassist constructor object corresponding to the given constructor
* signature of the specified class name.
*/
private CtConstructor getConstructor(final String fullClass, final String constructorSig) {
final CtClass cc = getClass(fullClass);
final String[] argTypes = getMethodArgTypes(constructorSig);
final CtClass[] params = new CtClass[argTypes.length];
for (int i = 0; i < params.length; i++) {
params[i] = getClass(argTypes[i]);
}
try {
return cc.getDeclaredConstructor(params);
}
catch (final NotFoundException e) {
throw new IllegalArgumentException("No such method: " + constructorSig, e);
}
}
/**
* Generates a new line of code calling the {@link imagej.legacy.patches}
* class and method corresponding to the given method signature.
*/
private String newCode(final String fullClass, final String methodSig) {
final int dotIndex = fullClass.lastIndexOf(".");
final String className = fullClass.substring(dotIndex + 1);
final String methodName = getMethodName(methodSig);
final boolean isStatic = isStatic(methodSig);
final boolean isVoid = isVoid(methodSig);
final String patchClass = PATCH_PKG + "." + className + PATCH_SUFFIX;
for (final CtMethod method : getClass(patchClass).getMethods()) try {
if ((method.getModifiers() & Modifier.STATIC) == 0) continue;
final CtClass[] types = method.getParameterTypes();
if (types.length == 0 || !types[0].getName().equals("imagej.legacy.LegacyService")) {
throw new UnsupportedOperationException("Method " + method + " of class " + patchClass + " has wrong type!");
}
} catch (NotFoundException e) {
e.printStackTrace();
}
final StringBuilder newCode =
new StringBuilder((isVoid ? "" : "return ") + patchClass + "." + methodName + "(");
newCode.append("$service");
if (!isStatic) {
newCode.append(", this");
}
final int argCount = getMethodArgTypes(methodSig).length;
for (int i = 1; i <= argCount; i++) {
newCode.append(", $" + i);
}
newCode.append(");");
return newCode.toString();
}
/** Patches in the current legacy service for '$service' */
private String expand(final String code) {
return code
.replace("$isLegacyMode()", "$service.isLegacyMode()")
.replace("$service", "ij.IJ.getLegacyService()");
}
/** Extracts the method name from the given method signature. */
private String getMethodName(final String methodSig) {
final int parenIndex = methodSig.indexOf("(");
final int spaceIndex = methodSig.lastIndexOf(" ", parenIndex);
return methodSig.substring(spaceIndex + 1, parenIndex);
}
private String[] getMethodArgTypes(final String methodSig) {
final int parenIndex = methodSig.indexOf("(");
final String methodArgs =
methodSig.substring(parenIndex + 1, methodSig.length() - 1);
final String[] args =
methodArgs.equals("") ? new String[0] : methodArgs.split(",");
for (int i = 0; i < args.length; i++) {
args[i] = args[i].trim().split(" ")[0];
}
return args;
}
/** Returns true if the given method signature is static. */
private boolean isStatic(final String methodSig) {
final int parenIndex = methodSig.indexOf("(");
final String methodPrefix = methodSig.substring(0, parenIndex);
for (final String token : methodPrefix.split(" ")) {
if (token.equals("static")) return true;
}
return false;
}
/** Returns true if the given method signature returns void. */
private boolean isVoid(final String methodSig) {
final int parenIndex = methodSig.indexOf("(");
final String methodPrefix = methodSig.substring(0, parenIndex);
return methodPrefix.startsWith("void ") ||
methodPrefix.indexOf(" void ") > 0;
}
/**
* Determines whether the specified class has the specified field.
*
* @param fullName the class name
* @param fieldName the field name
* @return whether the field exists
*/
public boolean hasField(final String fullName, final String fieldName) {
final CtClass clazz = getClass(fullName);
try {
return clazz.getField(fieldName) != null;
} catch (NotFoundException e) {
return false;
}
}
private static int verboseLevel = 0;
private static CtMethod makeStubMethod(CtClass clazz, CtMethod original) throws CannotCompileException, NotFoundException {
// add a stub
String prefix = "";
if (verboseLevel > 0) {
prefix = "System.err.println(\"Called " + original.getLongName() + "\\n\"";
if (verboseLevel > 1) {
prefix += "+ \"\\t(\" + fiji.Headless.toString($args) + \")\\n\"";
}
prefix += ");";
}
CtClass type = original.getReturnType();
String body = "{" +
prefix +
(type == CtClass.voidType ? "" : "return " + defaultReturnValue(type) + ";") +
"}";
CtClass[] types = original.getParameterTypes();
return CtNewMethod.make(type, original.getName(), types, new CtClass[0], body, clazz);
}
private static String defaultReturnValue(CtClass type) {
return (type == CtClass.booleanType ? "false" :
(type == CtClass.byteType ? "(byte)0" :
(type == CtClass.charType ? "'\0'" :
(type == CtClass.doubleType ? "0.0" :
(type == CtClass.floatType ? "0.0f" :
(type == CtClass.intType ? "0" :
(type == CtClass.longType ? "0l" :
(type == CtClass.shortType ? "(short)0" : "null"))))))));
}
private void addMissingMethods(CtClass fakeClass, CtClass originalClass) throws CannotCompileException, NotFoundException {
if (verboseLevel > 0)
System.err.println("adding missing methods from " + originalClass.getName() + " to " + fakeClass.getName());
Set<String> available = new HashSet<String>();
for (CtMethod method : fakeClass.getMethods())
available.add(stripPackage(method.getLongName()));
for (CtMethod original : originalClass.getDeclaredMethods()) {
if (available.contains(stripPackage(original.getLongName()))) {
if (verboseLevel > 1)
System.err.println("Skipping available method " + original);
continue;
}
CtMethod method = makeStubMethod(fakeClass, original);
fakeClass.addMethod(method);
if (verboseLevel > 1)
System.err.println("adding missing method " + method);
}
// interfaces
Set<CtClass> availableInterfaces = new HashSet<CtClass>();
for (CtClass iface : fakeClass.getInterfaces())
availableInterfaces.add(iface);
for (CtClass iface : originalClass.getInterfaces())
if (!availableInterfaces.contains(iface))
fakeClass.addInterface(iface);
CtClass superClass = originalClass.getSuperclass();
if (superClass != null && !superClass.getName().equals("java.lang.Object"))
addMissingMethods(fakeClass, superClass);
}
private void letSuperclassMethodsOverride(CtClass clazz) throws CannotCompileException, NotFoundException {
for (CtMethod method : clazz.getSuperclass().getDeclaredMethods()) {
CtMethod method2 = clazz.getMethod(method.getName(), method.getSignature());
if (method2.getDeclaringClass().equals(clazz)) {
method2.setBody(method, null); // make sure no calls/accesses to GUI components are remaining
method2.setName("narf" + method.getName());
}
}
}
private static String stripPackage(String className) {
int lastDot = -1;
for (int i = 0; ; i++) {
if (i >= className.length())
return className.substring(lastDot + 1);
char c = className.charAt(i);
if (c == '.' || c == '$')
lastDot = i;
else if (c >= 'A' && c <= 'Z')
; // continue
else if (c >= 'a' && c <= 'z')
; // continue
else if (i > lastDot + 1 && c >= '0' && c <= '9')
; // continue
else
return className.substring(lastDot + 1);
}
}
private void skipAWTInstantiations(CtClass clazz) throws CannotCompileException, NotFoundException {
clazz.instrument(new ExprEditor() {
@Override
public void edit(NewExpr expr) throws CannotCompileException {
String name = expr.getClassName();
if (name.startsWith("java.awt.Menu") || name.equals("java.awt.PopupMenu") ||
name.startsWith("java.awt.Checkbox") || name.equals("java.awt.Frame")) {
expr.replace("$_ = null;");
} else if (expr.getClassName().equals("ij.gui.StackWindow")) {
expr.replace("$1.show(); $_ = null;");
}
}
@Override
public void edit(MethodCall call) throws CannotCompileException {
final String className = call.getClassName();
final String methodName = call.getMethodName();
if (className.startsWith("java.awt.Menu") || className.equals("java.awt.PopupMenu") ||
className.startsWith("java.awt.Checkbox")) try {
CtClass type = call.getMethod().getReturnType();
if (type == CtClass.voidType) {
call.replace("");
} else {
call.replace("$_ = " + defaultReturnValue(type) + ";");
}
} catch (NotFoundException e) {
e.printStackTrace();
} else if (methodName.equals("put") && className.equals("java.util.Properties")) {
call.replace("if ($1 != null && $2 != null) $_ = $0.put($1, $2); else $_ = null;");
} else if (methodName.equals("get") && className.equals("java.util.Properties")) {
call.replace("$_ = $1 != null ? $0.get($1) : null;");
} else if (className.equals("java.lang.Integer") && methodName.equals("intValue")) {
call.replace("$_ = $0 == null ? 0 : $0.intValue();");
} else if (methodName.equals("addTextListener")) {
call.replace("");
} else if (methodName.equals("elementAt")) {
call.replace("$_ = $0 == null ? null : $0.elementAt($$);");
}
}
});
}
} |
package com.draga.spaceTravels3.screen;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.scenes.scene2d.Actor;
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.draga.spaceTravels3.Constants;
import com.draga.spaceTravels3.SpaceTravels3;
import com.draga.spaceTravels3.manager.ScoreManager;
import com.draga.spaceTravels3.manager.SettingsManager;
import com.draga.spaceTravels3.manager.UIManager;
import com.draga.spaceTravels3.manager.level.LevelManager;
import com.draga.spaceTravels3.manager.level.serialisableEntities.SerialisableLevel;
import com.draga.spaceTravels3.ui.BeepingTextButton;
public class MenuScreen implements Screen
{
private Stage stage;
private ButtonGroup<TextButton> buttonGroup;
public MenuScreen()
{
}
@Override
public void show()
{
stage = new Stage();
Gdx.input.setInputProcessor(stage);
Table table = UIManager.addDefaultTableToStage(stage);
// Header label.
Label headerLabel = getHeaderLabel();
table
.add(headerLabel)
.top();
// Add a row with an expanded cell to fill the gap.
table.row();
table
.add()
.expand();
// Level list.
table.row();
ScrollPane levelsScrollPane = getLevelList();
table.add(levelsScrollPane);
// Add a row with an expanded cell to fill the gap.
table.row();
table
.add()
.expand();
// Debug button.
if (Constants.General.IS_DEBUGGING)
{
Actor debugButton = getDebugButton();
table.row();
table
.add(debugButton)
.bottom();
}
// Setting button.
table.row();
TextButton settingsTextButton = getSettingsTextButton();
table
.add(settingsTextButton)
.bottom();
// Play button.
TextButton playButton = getPlayButton();
table.row();
table
.add(playButton)
.bottom();
stage.setDebugAll(SettingsManager.getDebugSettings().debugDraw);
}
public Label getHeaderLabel()
{
Label headerLabel = new Label("Space Travels 3", UIManager.skin);
return headerLabel;
}
public TextButton getPlayButton()
{
TextButton playButton = new BeepingTextButton("Play", UIManager.skin);
playButton.addListener(
new ClickListener()
{
@Override
public void clicked(InputEvent event, float x, float y)
{
StartGameScreen();
}
});
return playButton;
}
private ScrollPane getLevelList()
{
java.util.List<SerialisableLevel> levels = LevelManager.getSerialisableLevels();
buttonGroup = new ButtonGroup<>();
buttonGroup.setMaxCheckCount(1);
buttonGroup.setMinCheckCount(1);
buttonGroup.setUncheckLast(true);
Table table = UIManager.getDefaultTable();
for (SerialisableLevel level : levels)
{
String buttonText = level.name + " (" + ScoreManager.getScore(level.name) + ")";
TextButton textButton =
new BeepingTextButton(buttonText, UIManager.skin);
textButton.setName(level.id);
buttonGroup.add(textButton);
table.add(textButton);
table.row();
}
ScrollPane scrollPane = new ScrollPane(table);
return scrollPane;
}
public Actor getDebugButton()
{
TextButton debugButton = new BeepingTextButton("Debug", UIManager.skin);
debugButton.addListener(
new ClickListener()
{
@Override
public void clicked(InputEvent event, float x, float y)
{
SpaceTravels3.getGame().setScreen(new DebugMenuScreen());
}
});
return debugButton;
}
private TextButton getSettingsTextButton()
{
TextButton settingsTextButton = new BeepingTextButton("Settings", UIManager.skin);
settingsTextButton.addListener(
new ClickListener()
{
@Override
public void clicked(InputEvent event, float x, float y)
{
super.clicked(event, x, y);
SpaceTravels3.getGame().setScreen(new SettingsMenuScreen());
}
});
return settingsTextButton;
}
private void StartGameScreen()
{
String levelId = buttonGroup.getChecked().getName();
LoadingScreen loadingScreen = new LoadingScreen(levelId);
SpaceTravels3.getGame().setScreen(loadingScreen);
}
@Override
public void render(float deltaTime)
{
if (Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE)
|| Gdx.input.isKeyJustPressed(Input.Keys.BACK))
{
Gdx.app.exit();
}
if (Gdx.input.isKeyJustPressed(Input.Keys.ENTER))
{
StartGameScreen();
}
stage.act(deltaTime);
stage.draw();
}
@Override
public void resize(int width, int height)
{
stage.getViewport().update(width, height);
}
@Override
public void pause()
{
}
@Override
public void resume()
{
}
@Override
public void hide()
{
this.dispose();
}
@Override
public void dispose()
{
stage.dispose();
}
} |
package de.otto.jlineup.browser;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.gson.annotations.SerializedName;
import de.otto.jlineup.RunStepConfig;
import de.otto.jlineup.Utils;
import de.otto.jlineup.config.Cookie;
import de.otto.jlineup.config.JobConfig;
import de.otto.jlineup.file.FileService;
import de.otto.jlineup.image.ImageService;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.*;
import org.openqa.selenium.Point;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static de.otto.jlineup.browser.BrowserUtils.buildUrl;
import static de.otto.jlineup.file.FileService.AFTER;
import static de.otto.jlineup.file.FileService.BEFORE;
import static java.util.stream.Collectors.groupingBy;
public class Browser implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(Browser.class);
public static final int THREADPOOL_SUBMIT_SHUFFLE_TIME_IN_MS = 233;
public static final int DEFAULT_SLEEP_AFTER_SCROLL_MILLIS = 50;
public static final int DEFAULT_IMPLICIT_WAIT_TIME_IN_SECONDS = 60;
public enum Type {
@SerializedName(value = "Firefox", alternate = {"firefox", "FIREFOX"})
@JsonProperty(value = "Firefox")
FIREFOX,
@SerializedName(value = "Firefox-Headless", alternate = {"firefox-headless", "FIREFOX_HEADLESS"})
@JsonProperty(value = "Firefox-Headless")
FIREFOX_HEADLESS,
@SerializedName(value = "Chrome", alternate = {"chrome", "CHROME"})
@JsonProperty(value = "Chrome")
CHROME,
@SerializedName(value = "Chrome-Headless", alternate = {"chrome-headless", "CHROME_HEADLESS"})
@JsonProperty(value = "Chrome-Headless")
CHROME_HEADLESS,
@SerializedName(value = "PhantomJS", alternate = {"phantomjs", "PHANTOMJS"})
@JsonProperty(value = "PhantomJS")
PHANTOMJS;
public boolean isFirefox() {
return this == FIREFOX || this == FIREFOX_HEADLESS;
}
public boolean isChrome() {
return this == CHROME || this == CHROME_HEADLESS;
}
public boolean isPhantomJS() {
return this == PHANTOMJS;
}
public boolean isHeadlessRealBrowser() {
return this == FIREFOX_HEADLESS || this == CHROME_HEADLESS;
}
public boolean isHeadless() {
return isHeadlessRealBrowser() || isPhantomJS();
}
@JsonCreator
public static Type forValue(String value) {
String browserNameEnum = value
.toUpperCase()
.replace("-", "_");
return Browser.Type.valueOf(browserNameEnum);
}
}
static final String JS_DOCUMENT_HEIGHT_CALL = "return Math.max( document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight );";
static final String JS_CLIENT_VIEWPORT_HEIGHT_CALL = "return document.documentElement.clientHeight";
static final String JS_SET_LOCAL_STORAGE_CALL = "localStorage.setItem('%s','%s')";
static final String JS_SET_SESSION_STORAGE_CALL = "sessionStorage.setItem('%s','%s')";
static final String JS_SCROLL_CALL = "window.scrollBy(0,%d)";
static final String JS_SCROLL_TO_TOP_CALL = "window.scrollTo(0, 0);";
static final String JS_RETURN_DOCUMENT_FONTS_SIZE_CALL = "return document.fonts.size;";
static final String JS_RETURN_DOCUMENT_FONTS_STATUS_LOADED_CALL = "return document.fonts.status === 'loaded';";
static final String JS_GET_USER_AGENT = "return navigator.userAgent;";
private final JobConfig jobConfig;
private final FileService fileService;
private final BrowserUtils browserUtils;
private final RunStepConfig runStepConfig;
private final LogErrorChecker logErrorChecker;
/* Every thread has it's own WebDriver and cache warmup marks, this is manually managed through concurrent maps */
private ExecutorService threadPool;
private final ConcurrentHashMap<String, WebDriver> webDrivers = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, Set<String>> cacheWarmupMarksMap = new ConcurrentHashMap<>();
private final AtomicBoolean shutdownCalled = new AtomicBoolean(false);
public Browser(RunStepConfig runStepConfig, JobConfig jobConfig, FileService fileService, BrowserUtils browserUtils) {
this.runStepConfig = runStepConfig;
this.jobConfig = jobConfig;
this.fileService = fileService;
this.browserUtils = browserUtils;
this.threadPool = Utils.createThreadPool(jobConfig.threads, "BrowserThread");
this.logErrorChecker = new LogErrorChecker();
}
@Override
public void close() {
LOG.debug("Closing webdrivers.");
shutdownCalled.getAndSet(true);
synchronized (webDrivers) {
LOG.debug("Setting shutdown called to true");
webDrivers.forEach((key, value) -> {
LOG.debug("Removing webdriver for thread {} ({})", key, value.getClass().getCanonicalName());
value.quit();
});
webDrivers.clear();
//grepChromedrivers();
}
LOG.debug("Closing webdrivers done.");
}
public void takeScreenshots() throws Exception {
List<ScreenshotContext> screenshotContextList = BrowserUtils.buildScreenshotContextListFromConfigAndState(runStepConfig, jobConfig);
if (screenshotContextList.size() > 0) {
takeScreenshots(screenshotContextList);
}
}
void takeScreenshots(final List<ScreenshotContext> screenshotContextList) throws Exception {
Map<ScreenshotContext, Future> screenshotResults = new HashMap<>();
for (final ScreenshotContext screenshotContext : screenshotContextList) {
final Future<?> takeScreenshotsResult = threadPool.submit(() -> {
try {
tryToTakeScreenshotsForContextNTimes(screenshotContext, jobConfig.screenshotRetries);
} catch (Exception e) {
//There was an error, prevent pool from taking more tasks and let run fail
LOG.error("Exception in Browser thread while taking screenshot.", e);
threadPool.shutdownNow();
throw new WebDriverException("Exception in Browser thread", e);
}
});
screenshotResults.put(screenshotContext, takeScreenshotsResult);
//submit screenshots to the browser with a slight delay, so not all instances open up in complete sync
Thread.sleep(THREADPOOL_SUBMIT_SHUFFLE_TIME_IN_MS);
}
LOG.debug("Shutting down threadpool.");
threadPool.shutdown();
LOG.debug("Threadpool shutdown finished. Awaiting termination.");
boolean notRanIntoTimeout = threadPool.awaitTermination(jobConfig.globalTimeout, TimeUnit.SECONDS);
if (!notRanIntoTimeout) {
LOG.error("Threadpool ran into timeout.");
throw new TimeoutException("Global timeout of " + jobConfig.globalTimeout + " seconds was reached.");
} else {
LOG.debug("Threadpool terminated.");
}
//Get and propagate possible exceptions
for (Map.Entry<ScreenshotContext, Future> screenshotResult : screenshotResults.entrySet()) {
try {
screenshotResult.getValue().get(10, TimeUnit.SECONDS);
} catch (TimeoutException e) {
LOG.error("Timeout while getting screenshot result for {} with width {}.", screenshotResult.getKey().url, screenshotResult.getKey().windowWidth);
throw e;
}
}
}
private void tryToTakeScreenshotsForContextNTimes(ScreenshotContext screenshotContext, int maxRetries) throws Exception {
int retries = 0;
while (retries <= maxRetries) {
try {
takeScreenshotsForContext(screenshotContext);
return;
} catch (Exception e) {
if (retries < maxRetries) {
LOG.warn("try '{}' to take screen failed", retries, e);
} else {
throw e;
}
}
retries++;
}
}
private AtomicBoolean printVersion = new AtomicBoolean(true);
private void takeScreenshotsForContext(final ScreenshotContext screenshotContext) throws Exception {
boolean headlessRealBrowser = jobConfig.browser.isHeadlessRealBrowser();
final WebDriver localDriver;
if (headlessRealBrowser) {
localDriver = initializeWebDriver(screenshotContext.windowWidth);
} else localDriver = initializeWebDriver();
if (printVersion.getAndSet(false)) {
System.out.println(
"\n\n" +
"====================================================\n" +
"User agent: " + getBrowserAndVersion() + "\n" +
"====================================================\n" +
"\n");
}
//No need to move the mouse out of the way for headless browsers, but this avoids hovering links in other browsers
if (!jobConfig.browser.isHeadless()) {
moveMouseToZeroZero();
}
if (!headlessRealBrowser) {
localDriver.manage().window().setPosition(new Point(0, 0));
resizeBrowser(localDriver, screenshotContext.windowWidth, jobConfig.windowHeight);
}
final String url = buildUrl(screenshotContext.url, screenshotContext.urlSubPath, screenshotContext.urlConfig.envMapping);
final String rootUrl = buildUrl(screenshotContext.url, "/", screenshotContext.urlConfig.envMapping);
if (areThereCookies(screenshotContext)) {
//set cookies and local storage
setCookies(screenshotContext, localDriver);
}
if (isThereStorage(screenshotContext)) {
//get root page from url to be able to set cookies afterwards
//if you set cookies before getting the page once, it will fail
LOG.info(String.format("Getting root url: %s to set cookies, local and session storage", rootUrl));
localDriver.get(rootUrl);
logErrorChecker.checkForErrors(localDriver, jobConfig);
setLocalStorage(screenshotContext);
setSessionStorage(screenshotContext);
}
if (headlessRealBrowser) {
browserCacheWarmupForHeadless(screenshotContext, url, localDriver);
} else {
checkBrowserCacheWarmup(screenshotContext, url, localDriver);
}
//now get the real page
LOG.info(String.format("Browsing to %s with window size %dx%d", url, screenshotContext.windowWidth, jobConfig.windowHeight));
//Selenium's get() method blocks until the browser/page fires an onload event (files and images referenced in the html have been loaded,
//but there might be JS calls that load more stuff dynamically afterwards).
localDriver.get(url);
logErrorChecker.checkForErrors(localDriver, jobConfig);
Long pageHeight = getPageHeight();
final Long viewportHeight = getViewportHeight();
if (screenshotContext.urlConfig.waitAfterPageLoad > 0) {
try {
LOG.debug(String.format("Waiting for %d seconds (wait-after-page-load)", screenshotContext.urlConfig.waitAfterPageLoad));
Thread.sleep(screenshotContext.urlConfig.waitAfterPageLoad * 1000);
} catch (InterruptedException e) {
LOG.error(e.getMessage(), e);
}
}
if (jobConfig.globalWaitAfterPageLoad > 0) {
LOG.debug(String.format("Waiting for %s seconds (global wait-after-page-load)", jobConfig.globalWaitAfterPageLoad));
Thread.sleep(Math.round(jobConfig.globalWaitAfterPageLoad * 1000));
}
LOG.debug("Page height before scrolling: {}", pageHeight);
LOG.debug("Viewport height of browser window: {}", viewportHeight);
scrollToTop();
//Execute custom javascript if existing
executeJavaScript(screenshotContext.urlConfig.javaScript);
//Wait for fonts
if (screenshotContext.urlConfig.waitForFontsTime > 0) {
if (!jobConfig.browser.isPhantomJS()) {
WebDriverWait wait = new WebDriverWait(getWebDriver(), screenshotContext.urlConfig.waitForFontsTime);
wait.until(fontsLoaded);
} else {
LOG.warn("WARNING: 'wait-for-fonts-time' is ignored because PhantomJS doesn't support this feature.");
}
}
for (int yPosition = 0; yPosition < pageHeight && yPosition <= screenshotContext.urlConfig.maxScrollHeight; yPosition += viewportHeight) {
BufferedImage currentScreenshot = takeScreenshot();
currentScreenshot = waitForNoAnimation(screenshotContext, currentScreenshot);
fileService.writeScreenshot(currentScreenshot, screenshotContext.url,
screenshotContext.urlSubPath, screenshotContext.windowWidth, yPosition, screenshotContext.before ? BEFORE : AFTER);
//PhantomJS (until now) always makes full page screenshots, so no scrolling and multi-screenshooting
//This is subject to change because W3C standard wants viewport screenshots
if (jobConfig.browser.isPhantomJS()) {
break;
}
LOG.debug("topOfViewport: {}, pageHeight: {}", yPosition, pageHeight);
scrollBy(viewportHeight.intValue());
LOG.debug("Scroll by {} done", viewportHeight.intValue());
if (screenshotContext.urlConfig.waitAfterScroll > 0) {
LOG.debug("Waiting for {} seconds (wait after scroll).", screenshotContext.urlConfig.waitAfterScroll);
TimeUnit.SECONDS.sleep(screenshotContext.urlConfig.waitAfterScroll);
}
//Refresh to check if page grows during scrolling
pageHeight = getPageHeight();
LOG.debug("Page height is {}", pageHeight);
}
}
private void resizeBrowser(WebDriver driver, int width, int height) {
LOG.debug("Resize browser window to {}x{}", width, height);
driver.manage().window().setSize(new Dimension(width, height));
}
private Set<String> initializeCacheWarmupMarks() {
return new HashSet<>();
}
private boolean areThereCookies(ScreenshotContext screenshotContext) {
return (screenshotContext.urlConfig.cookies != null && !screenshotContext.urlConfig.cookies.isEmpty());
}
private boolean isThereStorage(ScreenshotContext screenshotContext) {
return ((screenshotContext.urlConfig.localStorage != null && screenshotContext.urlConfig.localStorage.size() > 0)
|| (screenshotContext.urlConfig.sessionStorage != null && screenshotContext.urlConfig.sessionStorage.size() > 0));
}
private void setCookies(ScreenshotContext screenshotContext, WebDriver localDriver) {
//First: Set cookies on different domains which are explicitly set
Map<String, List<Cookie>> cookiesByDomainDifferentFromDomainToScreenshot = screenshotContext.urlConfig.cookies
.stream()
.filter(cookie -> cookie.domain != null)
.collect(groupingBy(cookie -> cookie.domain));
cookiesByDomainDifferentFromDomainToScreenshot.forEach((domain, cookies) -> {
setCookiesForDomain(localDriver, domain, cookies);
});
//Second: Set my cookies on same domain
List<Cookie> cookiesForSameDomain = screenshotContext.urlConfig.cookies.stream().filter(cookie -> cookie.domain == null).collect(Collectors.toList());
setCookiesForDomain(localDriver, screenshotContext.url, cookiesForSameDomain);
}
private void setCookiesForDomain(WebDriver localDriver, String domain, List<Cookie> cookies) {
boolean secure = cookies.stream().anyMatch(cookie -> cookie.secure);
String urlToSetCookie = domain;
if (!urlToSetCookie.startsWith("http")) {
if (urlToSetCookie.startsWith(".")) {
urlToSetCookie = urlToSetCookie.substring(1);
}
urlToSetCookie = (secure ? "https:
}
localDriver.get(urlToSetCookie);
logErrorChecker.checkForErrors(localDriver, jobConfig);
//Set cookies
if (jobConfig.browser.isPhantomJS()) {
//current phantomjs driver has a bug that prevents selenium's normal way of setting cookies
LOG.debug("Setting cookies for PhantomJS");
setCookiesPhantomJS(cookies);
} else {
LOG.debug("Setting cookies");
setCookies(cookies);
}
}
private void checkBrowserCacheWarmup(ScreenshotContext screenshotContext, String url, WebDriver driver) {
int warmupTime = screenshotContext.urlConfig.warmupBrowserCacheTime;
if (warmupTime > JobConfig.DEFAULT_WARMUP_BROWSER_CACHE_TIME) {
final Set<String> browserCacheWarmupMarks = cacheWarmupMarksMap.computeIfAbsent(Thread.currentThread().getName(), k -> initializeCacheWarmupMarks());
if (!browserCacheWarmupMarks.contains(url)) {
final Integer maxWidth = screenshotContext.urlConfig.windowWidths.stream().max(Integer::compareTo).get();
LOG.info(String.format("Browsing to %s with window size %dx%d for cache warmup", url, maxWidth, jobConfig.windowHeight));
resizeBrowser(driver, maxWidth, jobConfig.windowHeight);
LOG.debug("Getting url: {}", url);
driver.get(url);
logErrorChecker.checkForErrors(driver, jobConfig);
LOG.debug(String.format("First call of %s - waiting %d seconds for cache warmup", url, warmupTime));
browserCacheWarmupMarks.add(url);
try {
LOG.debug("Sleeping for {} seconds", warmupTime);
Thread.sleep(warmupTime * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
resizeBrowser(driver, screenshotContext.windowWidth, jobConfig.windowHeight);
LOG.debug("Cache warmup time is over. Getting " + url + " again.");
}
}
}
private void browserCacheWarmupForHeadless(ScreenshotContext screenshotContext, String url, WebDriver driver) throws Exception {
int warmupTime = screenshotContext.urlConfig.warmupBrowserCacheTime;
if (warmupTime > JobConfig.DEFAULT_WARMUP_BROWSER_CACHE_TIME) {
LOG.info(String.format("Browsing to %s with window size %dx%d for cache warmup", url, screenshotContext.windowWidth, jobConfig.windowHeight));
LOG.debug("Getting url: {}", url);
driver.get(url);
logErrorChecker.checkForErrors(driver, jobConfig);
LOG.debug(String.format("First call of %s - waiting %d seconds for cache warmup", url, warmupTime));
LOG.debug("Sleeping for {} seconds", warmupTime);
Thread.sleep(warmupTime * 1000);
LOG.debug("Cache warmup time is over. Getting " + url + " again.");
}
}
private BufferedImage takeScreenshot() throws IOException {
File screenshot = ((TakesScreenshot) getWebDriver()).getScreenshotAs(OutputType.FILE);
return ImageIO.read(screenshot);
}
private BufferedImage waitForNoAnimation(ScreenshotContext screenshotContext, BufferedImage currentScreenshot) throws IOException {
File screenshot;
float waitForNoAnimation = screenshotContext.urlConfig.waitForNoAnimationAfterScroll;
if (waitForNoAnimation > 0f) {
final long beginTime = System.currentTimeMillis();
int sameCounter = 0;
while (sameCounter < 10 && !timeIsOver(beginTime, waitForNoAnimation)) {
screenshot = ((TakesScreenshot) getWebDriver()).getScreenshotAs(OutputType.FILE);
BufferedImage newScreenshot = ImageIO.read(screenshot);
if (ImageService.bufferedImagesEqualQuick(newScreenshot, currentScreenshot)) {
sameCounter++;
}
currentScreenshot = newScreenshot;
}
}
return currentScreenshot;
}
private boolean timeIsOver(long beginTime, float waitForNoAnimation) {
boolean over = beginTime + (long) (waitForNoAnimation * 1000L) < System.currentTimeMillis();
if (over) LOG.debug("Time is over");
return over;
}
private Long getPageHeight() {
LOG.debug("Getting page height.");
JavascriptExecutor jse = (JavascriptExecutor) getWebDriver();
return (Long) (jse.executeScript(JS_DOCUMENT_HEIGHT_CALL));
}
private Long getViewportHeight() {
LOG.debug("Getting viewport height.");
JavascriptExecutor jse = (JavascriptExecutor) getWebDriver();
return (Long) (jse.executeScript(JS_CLIENT_VIEWPORT_HEIGHT_CALL));
}
private void executeJavaScript(String javaScript) throws InterruptedException {
if (javaScript == null) {
return;
}
LOG.debug("Executing JavaScript: {}", javaScript);
JavascriptExecutor jse = (JavascriptExecutor) getWebDriver();
jse.executeScript(javaScript);
Thread.sleep(50);
}
private String getBrowserAndVersion() {
LOG.debug("Getting browser user agent.");
JavascriptExecutor jse = (JavascriptExecutor) getWebDriver();
return (String) jse.executeScript(JS_GET_USER_AGENT);
}
void scrollBy(int viewportHeight) throws InterruptedException {
LOG.debug("Scroll by {}", viewportHeight);
JavascriptExecutor jse = (JavascriptExecutor) getWebDriver();
jse.executeScript(String.format(JS_SCROLL_CALL, viewportHeight));
//Sleep some milliseconds to give scrolling time before the next screenshot happens
Thread.sleep(DEFAULT_SLEEP_AFTER_SCROLL_MILLIS);
}
private void scrollToTop() throws InterruptedException {
LOG.debug("Scroll to top");
JavascriptExecutor jse = (JavascriptExecutor) getWebDriver();
jse.executeScript(JS_SCROLL_TO_TOP_CALL);
//Sleep some milliseconds to give scrolling time before the next screenshot happens
Thread.sleep(50);
}
private void setLocalStorage(ScreenshotContext screenshotContext) {
setLocalStorage(screenshotContext.urlConfig.localStorage);
}
private void setSessionStorage(ScreenshotContext screenshotContext) {
setSessionStorage(screenshotContext.urlConfig.sessionStorage);
}
void setLocalStorage(Map<String, String> localStorage) {
if (localStorage == null) return;
JavascriptExecutor jse = (JavascriptExecutor) getWebDriver();
for (Map.Entry<String, String> localStorageEntry : localStorage.entrySet()) {
final String entry = localStorageEntry.getValue().replace("'", "\"");
String jsCall = String.format(JS_SET_LOCAL_STORAGE_CALL, localStorageEntry.getKey(), entry);
jse.executeScript(jsCall);
LOG.debug("LocalStorage call: {}", jsCall);
}
}
void setSessionStorage(Map<String, String> sessionStorage) {
if (sessionStorage == null) return;
JavascriptExecutor jse = (JavascriptExecutor) getWebDriver();
for (Map.Entry<String, String> sessionStorageEntry : sessionStorage.entrySet()) {
final String entry = sessionStorageEntry.getValue().replace("'", "\"");
String jsCall = String.format(JS_SET_SESSION_STORAGE_CALL, sessionStorageEntry.getKey(), entry);
jse.executeScript(jsCall);
LOG.debug("SessionStorage call: {}", jsCall);
}
}
void setCookies(List<Cookie> cookies) {
if (cookies == null) return;
for (Cookie cookie : cookies) {
org.openqa.selenium.Cookie.Builder cookieBuilder = new org.openqa.selenium.Cookie.Builder(cookie.name, cookie.value);
if (cookie.domain != null) cookieBuilder.domain(cookie.domain);
if (cookie.path != null) cookieBuilder.path(cookie.path);
if (cookie.expiry != null) cookieBuilder.expiresOn(cookie.expiry);
cookieBuilder.isSecure(cookie.secure);
getWebDriver().manage().addCookie(cookieBuilder.build());
}
}
void setCookiesPhantomJS(List<Cookie> cookies) {
if (cookies == null) return;
for (Cookie cookie : cookies) {
StringBuilder cookieCallBuilder = new StringBuilder(String.format("document.cookie = '%s=%s;", cookie.name, cookie.value));
if (cookie.path != null) {
cookieCallBuilder.append("path=");
cookieCallBuilder.append(cookie.path);
cookieCallBuilder.append(";");
}
if (cookie.domain != null) {
cookieCallBuilder.append("domain=");
cookieCallBuilder.append(cookie.domain);
cookieCallBuilder.append(";");
}
if (cookie.secure) {
cookieCallBuilder.append("secure;");
}
if (cookie.expiry != null) {
cookieCallBuilder.append("expires=");
SimpleDateFormat df = new SimpleDateFormat("dd MMM yyyy HH:mm:ss", Locale.US);
df.setTimeZone(TimeZone.getTimeZone("GMT"));
String asGmt = df.format(cookie.expiry.getTime()) + " GMT";
cookieCallBuilder.append(asGmt);
cookieCallBuilder.append(";");
}
cookieCallBuilder.append("'");
((JavascriptExecutor) getWebDriver()).executeScript(cookieCallBuilder.toString());
}
}
WebDriver initializeWebDriver(int width) {
if (shutdownCalled.get()) return null;
synchronized (webDrivers) {
String currentThreadName = Thread.currentThread().getName();
if (webDrivers.containsKey(currentThreadName)) {
WebDriver oldDriver = webDrivers.get(currentThreadName);
LOG.debug("Removing webdriver for thread {} ({})", currentThreadName, oldDriver.getClass().getCanonicalName());
oldDriver.quit();
}
WebDriver driver = createDriverWithWidth(width);
webDrivers.put(currentThreadName, driver);
return driver;
}
}
WebDriver initializeWebDriver() {
if (shutdownCalled.get()) return null;
synchronized (webDrivers) {
if (shutdownCalled.get()) return null;
String currentThreadName = Thread.currentThread().getName();
if (webDrivers.containsKey(currentThreadName)) {
return webDrivers.get(currentThreadName);
}
WebDriver driver = createDriver();
webDrivers.put(currentThreadName, driver);
return driver;
}
}
private WebDriver createDriver() {
shutdownCalled.get();
final WebDriver driver = browserUtils.getWebDriverByConfig(jobConfig, runStepConfig);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
LOG.debug("Adding webdriver for thread {} ({})", Thread.currentThread().getName(), driver.getClass().getCanonicalName());
return driver;
}
private WebDriver createDriverWithWidth(int width) {
final WebDriver driver = browserUtils.getWebDriverByConfig(jobConfig, runStepConfig, width);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
LOG.debug("Adding webdriver for thread {} with width {} ({})", Thread.currentThread().getName(), width, driver.getClass().getCanonicalName());
return driver;
}
private WebDriver getWebDriver() {
return webDrivers.get(Thread.currentThread().getName());
}
private void moveMouseToZeroZero() {
Robot robot;
try {
robot = new Robot();
robot.mouseMove(0, 0);
} catch (AWTException e) {
LOG.error("Can't move mouse to 0,0", e);
}
}
// wait for fonts to load
private ExpectedCondition<Boolean> fontsLoaded = driver -> {
final JavascriptExecutor javascriptExecutor = (JavascriptExecutor) getWebDriver();
final Long fontsLoadedCount = (Long) javascriptExecutor.executeScript(JS_RETURN_DOCUMENT_FONTS_SIZE_CALL);
final Boolean fontsLoaded = (Boolean) javascriptExecutor.executeScript(JS_RETURN_DOCUMENT_FONTS_STATUS_LOADED_CALL);
LOG.debug("Amount of fonts in document: {}", fontsLoadedCount);
LOG.debug("Fonts loaded: {} ", fontsLoaded);
return fontsLoaded;
};
void grepChromedrivers() throws IOException {
ProcessBuilder pb = new ProcessBuilder();
Process process = pb.command("/bin/sh", "-c", "ps -eaf | grep chromedriver").start();
new BufferedReader(new InputStreamReader(process.getInputStream())).lines().forEach(System.err::println);
}
} |
package hudson.util;
import groovy.lang.GroovyShell;
import hudson.Functions;
import hudson.model.Hudson;
import hudson.remoting.Callable;
import hudson.remoting.VirtualChannel;
import hudson.remoting.DelegatingCallable;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.management.ThreadInfo;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
/**
* Various remoting operations related to diagnostics.
*
* <p>
* These code are useful whereever {@link VirtualChannel} is used, such as master, slaves, Maven JVMs, etc.
*
* @author Kohsuke Kawaguchi
* @since 1.175
*/
public final class RemotingDiagnostics {
public static Map<Object,Object> getSystemProperties(VirtualChannel channel) throws IOException, InterruptedException {
if(channel==null)
return Collections.<Object,Object>singletonMap("N/A","N/A");
return channel.call(new GetSystemProperties());
}
private static final class GetSystemProperties implements Callable<Map<Object,Object>,RuntimeException> {
public Map<Object,Object> call() {
return new TreeMap<Object,Object>(System.getProperties());
}
private static final long serialVersionUID = 1L;
}
public static Map<String,String> getThreadDump(VirtualChannel channel) throws IOException, InterruptedException {
if(channel==null)
return Collections.singletonMap("N/A","N/A");
return channel.call(new GetThreadDump());
}
private static final class GetThreadDump implements Callable<Map<String,String>,RuntimeException> {
public Map<String,String> call() {
Map<String,String> r = new LinkedHashMap<String,String>();
try {
for (ThreadInfo ti : Functions.getThreadInfos())
r.put(ti.getThreadName(),Functions.dumpThreadInfo(ti));
} catch (LinkageError _) {
// not in JDK6. fall back to JDK5
r.clear();
for (Map.Entry<Thread,StackTraceElement[]> t : Thread.getAllStackTraces().entrySet()) {
StringBuffer buf = new StringBuffer();
for (StackTraceElement e : t.getValue())
buf.append(e).append('\n');
r.put(t.getKey().getName(),buf.toString());
}
}
return r;
}
private static final long serialVersionUID = 1L;
}
/**
* Executes Groovy script remotely.
*/
public static String executeGroovy(String script, VirtualChannel channel) throws IOException, InterruptedException {
return channel.call(new Script(script));
}
private static final class Script implements DelegatingCallable<String,RuntimeException> {
private final String script;
private transient ClassLoader cl;
private Script(String script) {
this.script = script;
cl = getClassLoader();
}
public ClassLoader getClassLoader() {
return Hudson.getInstance().getPluginManager().uberClassLoader;
}
public String call() throws RuntimeException {
// if we run locally, cl!=null. Otherwise the delegating classloader will be available as context classloader.
if (cl==null) cl = Thread.currentThread().getContextClassLoader();
GroovyShell shell = new GroovyShell(cl);
StringWriter out = new StringWriter();
PrintWriter pw = new PrintWriter(out);
shell.setVariable("out", pw);
try {
Object output = shell.evaluate(script);
if(output!=null)
pw.println("Result: "+output);
} catch (Throwable t) {
t.printStackTrace(pw);
}
return out.toString();
}
}
} |
package lucee.runtime.net.mail;
import java.io.UnsupportedEncodingException;
import java.net.IDN;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
import lucee.commons.io.SystemUtil;
import lucee.commons.lang.StringUtil;
import lucee.runtime.config.Config;
import lucee.runtime.engine.ThreadLocalPageContext;
import lucee.runtime.exp.PageException;
import lucee.runtime.net.http.sni.SSLConnectionSocketFactoryImpl;
import lucee.runtime.op.Caster;
import lucee.runtime.op.Decision;
import lucee.runtime.type.Array;
import lucee.runtime.type.Struct;
import lucee.runtime.type.util.ListUtil;
public final class MailUtil {
public static final String SYSTEM_PROP_MAIL_SSL_PROTOCOLS = "mail.smtp.ssl.protocols";
public static String encode(String text, String encoding) throws UnsupportedEncodingException {
// print.ln(StringUtil.changeCharset(text,encoding));
return MimeUtility.encodeText(text, encoding, "Q");
}
public static String decode(String text) throws UnsupportedEncodingException {
return MimeUtility.decodeText(text);
}
public static InternetAddress toInternetAddress(Object emails) throws MailException, UnsupportedEncodingException, PageException {
if (emails instanceof String) {
return parseEmail(emails, null);
}
InternetAddress[] addresses = toInternetAddresses(emails);
if (addresses != null && addresses.length > 0) return addresses[0];
throw new MailException("invalid email address definition");// should never come to this!
}
public static InternetAddress[] toInternetAddresses(Object emails) throws MailException, UnsupportedEncodingException, PageException {
if (emails instanceof InternetAddress[]) return (InternetAddress[]) emails;
else if (emails instanceof String) return fromList((String) emails);
else if (Decision.isArray(emails)) return fromArray(Caster.toArray(emails));
else if (Decision.isStruct(emails)) return new InternetAddress[] { fromStruct(Caster.toStruct(emails)) };
else throw new MailException("e-mail definitions must be one of the following types [string,array,struct], not [" + emails.getClass().getName() + "]");
}
private static InternetAddress[] fromArray(Array array) throws MailException, PageException, UnsupportedEncodingException {
Iterator it = array.valueIterator();
Object el;
ArrayList<InternetAddress> pairs = new ArrayList();
while (it.hasNext()) {
el = it.next();
if (Decision.isStruct(el)) {
pairs.add(fromStruct(Caster.toStruct(el)));
}
else {
InternetAddress addr = parseEmail(Caster.toString(el), null);
if (addr != null) pairs.add(addr);
}
}
return pairs.toArray(new InternetAddress[pairs.size()]);
}
private static InternetAddress fromStruct(Struct sct) throws MailException, UnsupportedEncodingException {
String name = Caster.toString(sct.get("label", null), null);
if (name == null) name = Caster.toString(sct.get("name", null), null);
String email = Caster.toString(sct.get("email", null), null);
if (email == null) email = Caster.toString(sct.get("e-mail", null), null);
if (email == null) email = Caster.toString(sct.get("mail", null), null);
if (StringUtil.isEmpty(email)) throw new MailException("missing e-mail definition in struct");
if (name == null) name = "";
return new InternetAddress(email, name);
}
private static InternetAddress[] fromList(String strEmails) throws MailException {
if (StringUtil.isEmpty(strEmails, true)) return new InternetAddress[0];
Array raw = ListUtil.listWithQuotesToArray(strEmails, ",;", "\"");
Iterator<Object> it = raw.valueIterator();
ArrayList<InternetAddress> al = new ArrayList();
while (it.hasNext()) {
InternetAddress addr = parseEmail(it.next(), null);
if (addr != null) al.add(addr);
}
return al.toArray(new InternetAddress[al.size()]);
}
/**
* returns true if the passed value is a in valid email address format
*
* @param value
* @return
*/
public static boolean isValidEmail(Object value) {
InternetAddress addr = parseEmail(value, null);
if (addr != null) {
String address = addr.getAddress();
if (address.contains("..")) return false;
int pos = address.indexOf('@');
if (pos < 1 || pos == address.length() - 1) return false;
String local = address.substring(0, pos);
String domain = address.substring(pos + 1);
if (local.length() > 64) return false; // local part may only be 64 characters
if (domain.length() > 255) return false; // domain may only be 255 characters
if (domain.charAt(0) == '.' || local.charAt(0) == '.' || local.charAt(local.length() - 1) == '.') return false;
pos = domain.lastIndexOf('.');
if (pos > 0 && pos < domain.length() - 2) { // test TLD to be at
// least 2 chars all
// alpha characters
if (StringUtil.isAllAlpha(domain.substring(pos + 1))) return true;
try {
addr.validate();
return true;
}
catch (AddressException e) {
}
}
}
return false;
}
public static InternetAddress parseEmail(Object value) throws MailException {
InternetAddress ia = parseEmail(value, null);
if (ia != null) return ia;
if (value instanceof CharSequence) throw new MailException("[" + value + "] cannot be converted to an email address");
throw new MailException("input cannot be converted to an email address");
}
/**
* returns an InternetAddress object or null if the parsing fails. to be be used in multiple places.
*
* @param value
* @return
*/
public static InternetAddress parseEmail(Object value, InternetAddress defaultValue) {
String str = Caster.toString(value, "");
if (str.indexOf('@') > -1) {
try {
str = fixIDN(str);
InternetAddress addr = new InternetAddress(str);
// fixIDN( addr );
return addr;
}
catch (AddressException ex) {
}
}
return defaultValue;
}
/**
* converts IDN to ASCII if needed
*
* @param addr
* @return
*/
public static String fixIDN(String addr) {
int pos = addr.indexOf('@');
if (pos > 0 && pos < addr.length() - 1) {
String domain = addr.substring(pos + 1);
if (!StringUtil.isAscii(domain)) {
domain = IDN.toASCII(domain);
return addr.substring(0, pos) + "@" + domain;
}
}
return addr;
}
/**
* This method should be called when TLS is used to ensure that the supported protocols are set.
* Some servers, e.g. Outlook365, reject lists with older protocols so we only pass protocols that
* start with the prefix "TLS"
*/
public static void setSystemPropMailSslProtocols() {
String protocols = SystemUtil.getSystemPropOrEnvVar(SYSTEM_PROP_MAIL_SSL_PROTOCOLS, "");
if (protocols.isEmpty()) {
List<String> supportedProtocols = SSLConnectionSocketFactoryImpl.getSupportedSslProtocols();
protocols = supportedProtocols.stream().filter(el -> el.startsWith("TLS")).collect(Collectors.joining(" "));
if (!protocols.isEmpty()) {
System.setProperty(SYSTEM_PROP_MAIL_SSL_PROTOCOLS, protocols);
Config config = ThreadLocalPageContext.getConfig();
if (config != null) config.getLog("mail").info("mail", "Lucee system property " + SYSTEM_PROP_MAIL_SSL_PROTOCOLS + " set to [" + protocols + "]");
}
}
}
} |
package net.darkmist.alib.io;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BufferUtil
{
private static final Class<BufferUtil> CLASS = BufferUtil.class;
private static final Logger logger = LoggerFactory.getLogger(CLASS);
private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0).asReadOnlyBuffer();
public static ByteBuffer getEmptyBuffer()
{
return EMPTY_BUFFER;
}
/**
* Allocate a buffer and fill it from a channel. The returned
* buffer will be rewound to the begining.
* @return Buffer containing size bytes from the channel.
* @throws IOException if the channel read does.
* @throws EOFException if a end of stream is encountered
* before the full size is read.
*/
public static ByteBuffer allocateAndReadAll(int size, ReadableByteChannel channel) throws IOException
{
ByteBuffer buf = ByteBuffer.allocate(size);
int justRead;
int totalRead = 0;
// FIXME, this will be a tight loop if the channel is non-blocking...
while(totalRead < size)
{
logger.debug("reading totalRead={}", totalRead);
if((justRead = channel.read(buf))<0)
throw new EOFException("Unexpected end of stream after reading " + totalRead + " bytes");
totalRead += justRead;
}
buf.rewind();
return buf;
}
public static void writeAll(ByteBuffer buf, WritableByteChannel channel) throws IOException
{
while(buf.remaining() > 0)
channel.write(buf);
}
public static byte[] asBytes(ByteBuffer buf)
{
/* To use buf.array() the buffer must:
* be writable as the array will be writable
* have arrayOffset() == 0 or the array will not start at the right location
* the returned array must be the same length as the buffer's limit or it will be the wrong size.
*/
if(!buf.isReadOnly() && buf.hasArray() && buf.arrayOffset() == 0)
{
logger.debug("read-only, hasArray && offset is 0");
byte[] ret = buf.array();
if(ret.length == buf.limit())
return buf.array();
logger.debug("length of array !=limit, doing copy...");
}
byte[] bytes = new byte[buf.limit()];
buf.get(bytes,0,buf.limit());
return bytes;
}
private static class ByteBufferInputStream extends InputStream
{
private ByteBuffer buf;
private int mark = -1;
ByteBufferInputStream(ByteBuffer buf)
{
this.buf = buf;
}
@Override
public int read(byte[] bytes) throws IOException
{
int num;
if(bytes == null)
throw new NullPointerException("Byte buffer is null");
if(bytes.length == 0)
return 0;
if(!buf.hasRemaining())
return -1;
num = Math.min(buf.remaining(), bytes.length);
buf.get(bytes, 0, num);
return num;
}
@Override
public int read(byte[] bytes, int off, int len) throws IOException
{
if(bytes == null)
throw new NullPointerException("Byte buffer is null");
if(off >= bytes.length)
throw new IllegalArgumentException("Offset is larger than or equal to byte array length");
if(off < 0)
throw new IllegalArgumentException("Offset is negative");
if(len < 0)
throw new IllegalArgumentException("Length is negative");
if(len + off > bytes.length)
throw new IllegalArgumentException("Length + off set is larger than byte array length");
int num;
if(len == 0)
return 0;
if(!buf.hasRemaining())
return -1;
num = Math.min(buf.remaining(), len);
buf.get(bytes, off, num);
return num;
}
@Override
public int read() throws IOException
{
if(buf.hasRemaining())
return (int)(buf.get()) & 0xFF;
return -1;
}
@Override
public int available() throws IOException
{
return buf.remaining();
}
@Override
public long skip(long amount) throws IOException
{
int bufRemaining = buf.remaining();
if(amount <= 0)
return 0;
if(bufRemaining == 0)
return 0;
if(bufRemaining < 0)
throw new IllegalStateException("Remaining is negative");
if(bufRemaining < amount)
{
buf.position(buf.position() + bufRemaining);
return bufRemaining;
}
buf.position((int)(buf.position() + amount));
return amount;
}
@Override
public void mark(int ignored)
{
mark = buf.position();
}
@Override
public void reset() throws IOException
{
buf.position(mark);
}
@Override
public boolean markSupported()
{
return true;
}
}
public static InputStream asInputStream(ByteBuffer buf)
{
return new ByteBufferInputStream(buf);
}
public static DataInput asDataInput(ByteBuffer buf)
{
return new DataInputStream(asInputStream(buf));
}
/**
* Sane ByteBuffer slice
* @param buf the buffer to slice something out of
* @param off The offset into the buffer
* @param len the length of the part to slice out
*/
public static ByteBuffer slice(ByteBuffer buf, int off, int len)
{
ByteBuffer localBuf=buf.duplicate(); // so we don't mess up the position,etc
logger.debug("off={} len={}", off, len);
localBuf.position(off);
localBuf.limit(off+len);
logger.debug("pre-slice: localBuf.position()={} localBuf.limit()={}", localBuf.position(), localBuf.limit());
localBuf = localBuf.slice();
logger.debug("post-slice: localBuf.position()={} localBuf.limit()={}", localBuf.position(), localBuf.limit());
return localBuf;
}
public static ByteBuffer map(File file) throws IOException
{
FileInputStream fin=null;
FileChannel fc=null;
try
{
fin = new FileInputStream(file);
fc = fin.getChannel();
return fc.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
}
finally
{
fc = Closer.close(fc);
fin = Closer.close(fin);
}
}
public static ByteBuffer mapFile(String path) throws IOException
{
return map(new File(path));
}
public static boolean isAll(ByteBuffer buf, byte b)
{
buf = buf.duplicate();
while(buf.hasRemaining())
if(buf.get() != b)
return false;
return true;
}
public static boolean isAllZero(ByteBuffer buf)
{
return isAll(buf, (byte)0);
}
public static ByteBuffer asBuffer(InputStream in) throws IOException
{
return ByteBuffer.wrap(IOUtils.toByteArray(in));
}
public static ByteBuffer asBuffer(InputStream in, int len) throws IOException
{
return ByteBuffer.wrap(Slurp.slurp(in,len));
}
public static ByteBuffer asBuffer(InputStream in, long len) throws IOException
{
return ByteBuffer.wrap(Slurp.slurp(in,len));
}
public static ByteBuffer asBuffer(DataInput in) throws IOException
{
return ByteBuffer.wrap(Slurp.slurp(in));
}
public static ByteBuffer asBuffer(DataInput in, int len) throws IOException
{
return ByteBuffer.wrap(Slurp.slurp(in,len));
}
public static ByteBuffer asBuffer(DataInput in, long len) throws IOException
{
return ByteBuffer.wrap(Slurp.slurp(in,len));
}
} |
package roart.calculate;
import java.util.Random;
public class CalcComplexNode extends CalcNode {
double minMutateThresholdRange;
double maxMutateThresholdRange;
double threshold;
boolean useminmaxthreshold;
boolean usethreshold;
//boolean divideminmaxthreshold;
int weight;
//boolean changeSignWhole;
// not mutatable
boolean useMax;
//boolean threshMaxValue; //?
//boolean norm;
public double getMinMutateThresholdRange() {
return minMutateThresholdRange;
}
public void setMinMutateThresholdRange(double minMutateThresholdRange) {
this.minMutateThresholdRange = minMutateThresholdRange;
}
public double getMaxMutateThresholdRange() {
return maxMutateThresholdRange;
}
public void setMaxMutateThresholdRange(double maxMutateThresholdRange) {
this.maxMutateThresholdRange = maxMutateThresholdRange;
}
public double getThreshold() {
return threshold;
}
public void setThreshold(double threshold) {
this.threshold = threshold;
}
public boolean isUseminmaxthreshold() {
return useminmaxthreshold;
}
public void setUseminmaxthreshold(boolean useminmaxthreshold) {
this.useminmaxthreshold = useminmaxthreshold;
}
public boolean isUsethreshold() {
return usethreshold;
}
public void setUsethreshold(boolean usethreshold) {
this.usethreshold = usethreshold;
}
/*
public boolean isDivideminmaxthreshold() {
return divideminmaxthreshold;
}
public void setDivideminmaxthreshold(boolean divideminmaxthreshold) {
this.divideminmaxthreshold = divideminmaxthreshold;
}
*/
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
/*
public boolean isChangeSignWhole() {
return changeSignWhole;
}
public void setChangeSignWhole(boolean changeSignWhole) {
this.changeSignWhole = changeSignWhole;
}
*/
public boolean isUseMax() {
return useMax;
}
public void setUseMax(boolean doBuy) {
this.useMax = doBuy;
}
@Override
public double calc(double val, double minmaxthreshold2) {
double minmaxthreshold = maxMutateThresholdRange;
if (!useMax) {
minmaxthreshold = minMutateThresholdRange;
}
double mythreshold = 0;
if (usethreshold) {
mythreshold = threshold;
}
if (useminmaxthreshold) {
mythreshold = minmaxthreshold;
}
double myvalue = val - mythreshold;
// if usemax...?
/*
if (false && divideminmaxthreshold) {
myvalue = myvalue / minmaxthreshold;
}
*/
myvalue = myvalue / (maxMutateThresholdRange - minMutateThresholdRange);
/*
if (changeSignWhole) {
myvalue = -myvalue;
}
*/
return myvalue * weight;
}
@Override
public void randomize() {
Random rand = new Random();
getUseminmaxthreshold(rand);
getUsethreshold(rand);
//getDivideminmaxthreshold(rand); // not
//getChangeSignWhole(rand); // not
getWeight(rand);
getThreshold(rand);
}
private void getThreshold(Random rand) {
if (useMax) {
threshold = rand.nextDouble() * maxMutateThresholdRange;
} else {
threshold = rand.nextDouble() * minMutateThresholdRange;
}
}
private void getWeight(Random rand) {
weight = 1 + rand.nextInt(100);
}
/*
private void getChangeSignWhole(Random rand) {
changeSignWhole = rand.nextBoolean();
}
private void getDivideminmaxthreshold(Random rand) {
divideminmaxthreshold = rand.nextBoolean();
}
*/
private void getUsethreshold(Random rand) {
usethreshold = rand.nextBoolean();
}
private void getUseminmaxthreshold(Random rand) {
useminmaxthreshold = rand.nextBoolean();
}
@Override
public void mutate() {
Random rand = new Random();
int task = rand.nextInt(4);
switch (task) {
case 0:
getUseminmaxthreshold(rand);
break;
case 1:
getUsethreshold(rand);
break;
case 2:
getWeight(rand);
break;
case 3:
getThreshold(rand);
break;
/*
case 2:
getDivideminmaxthreshold(rand);
break;
case 3:
getChangeSignWhole(rand);
break;
*/
default:
System.out.println("Too many");
break;
}
}
} |
package xal.sim.scenario;
import xal.model.IComponent;
import xal.model.IComposite;
import xal.model.ModelException;
import xal.model.elem.ThickElement;
import xal.model.elem.ThinElement;
import xal.smf.AcceleratorNode;
import xal.smf.AcceleratorSeq;
import xal.smf.impl.Bend;
import xal.smf.impl.Magnet;
/**
* <h3>CKA NOTES:</h3>
* <p>
* This class is essentially an association class between accelerator hardware
* nodes and modeling elements of the XAL online model.
* </p>
* <p>
* This can also be a proxy for SMF hardware nodes and can generates its modeling element
* counterpart. Currently it represents one atomic hardware node, but I believe
* it can represent many modeling elements (see <code>{@link #getParts()}</code>).
* </p>
* <p>
* · I have modified this objects so it carries the additional attribute
* of the <em>modeling element</em> identifier. This is in contrast to the hardware node
* identifier from which it maps.
* <br>
* <br>
* · The idea is that probes states produced by simulation will carry this attribute
* <b>if</b> it has been set. If not, then the probe state will have the same attribute
* ID as the hardware node.
* <br>
* <br>
* · Note that probe states now carry two identifier attributes, one for the modeling
* element, and one for the SMF hardware node from which it came.
* <br/>
* <br/>
* · The modeling element parameter initialization is done by calling the
* <code>{@link IComponent#initializeFrom(LatticeElement)}</code>. This design
* effectively couples the <code>xal.model</code> online model subsystem to the
* <code>xal.smf</code> hardware representation subsystem. These
* systems should be independent, able to function without each other.
* <br/>
* <br/>
* · I cannot really tell exactly what is happening as there was no commenting. I have
* added some comments wherever I have gone over the code, hopefully they are in the ball park.
* </p>
*
* @author Ivo List
* @author Christopher K. Allen
* @since Oct 3, 2013
* @version Sep 5, 2014
*/
public class LatticeElement implements Comparable<LatticeElement> {
/*
* Local Attributes
*/
// Accelerator Node
/** the associated hardware node */
private AcceleratorNode smfNode;
/** original index position of the hardware within its accelerator sequence - this is used to sort thin elements */
private int indNodeOrigPos;
// Modeling Element
/** CKA: Modeling element identifier, which can be different that the Accelerator node's ID */
private String strElemId;
/** flag indicating that this is actually an "artificial" element with no hardware counterpart */
private boolean bolArtificalElem;
/** the associated modeling element class type */
private Class<? extends IComponent> clsModElemType;
/** length of the modeling element */
private double dblElemLen;
/** center position of the modeling element within its parent sequence */
protected double dblElemCntrPos;
/** axial position of the modeling element entrance */
protected double dblElemEntrPos;
/** axial position of the modeling element exit */
protected double dblElemExitPos;
// State Variables
private IComponent component;
private LatticeElement firstSlice;
private LatticeElement nextSlice;
/*
* Initialization
*/
/**
* Initializing constructor for <code>LatticeElement</code>. The hardware node
* entrance and exit positions are initialized using the given center position
* and length attribute.
*
* @param smfNode associated hardware node
* @param dblPosCtr center position of hardware node within accelerator sequence
* @param clsModElemType class type of the modeling element for associated hardware
* @param originalPosition index position of the hardware node within its sequence (used to sort elements)
*
* @since Dec 8, 2014
*/
public LatticeElement(AcceleratorNode smfNode, double dblPosCtr, Class<? extends IComponent> clsModElemType, int originalPosition) {
this.strElemId = smfNode.getId();
this.smfNode = smfNode;
this.clsModElemType = clsModElemType;
this.indNodeOrigPos = originalPosition;
this.dblElemCntrPos = dblPosCtr;
// Determine the element length - special cases
double dblLenElem = smfNode.getLength();
double dblLenEffec = 0.0;
if (smfNode instanceof Magnet) {
if (smfNode instanceof Bend)
dblLenEffec = ((Bend) smfNode).getDfltPathLength();
else
dblLenEffec = ((Magnet) smfNode).getEffLength();
} else if (ThickElement.class.isAssignableFrom(clsModElemType)) {
dblLenEffec = dblLenElem;
} else if (IComposite.class.isAssignableFrom(clsModElemType)) {
dblLenEffec = dblLenElem;
}
this.dblElemLen = dblLenEffec;
// Set the entrance and exit positions according to the determined length
if (isThin())
dblElemEntrPos = dblElemExitPos = dblPosCtr;
else {
dblElemEntrPos = dblPosCtr - 0.5*this.dblElemLen;
dblElemExitPos = dblElemEntrPos + this.dblElemLen;
}
firstSlice = this;
}
/**
* Initializing constructor for <code>LatticeElement</code>. The entrance and exit
* positions are given directly for this constructor, which is called only within
* this class. This constructor is used when splitting lattice elements.
*
* @param smfNode associated hardware node
* @param dblPosStart entrance location of this lattice element within sequence
* @param dblPosEnd exit location of this lattice element within sequence
* @param clsModElemType class type of the modeling element for associated hardware
* @param originalPosition original index position of hardware node within its sequence
*
* @since Dec 8, 2014
*/
private LatticeElement(AcceleratorNode smfNode, double dblPosStart, double dblPosEnd, Class<? extends IComponent> clsModElemType, int originalPosition) {
this.strElemId = smfNode.getId();
this.smfNode = smfNode;
this.clsModElemType = clsModElemType;
this.bolArtificalElem = false;
this.dblElemEntrPos = dblPosStart;
this.dblElemExitPos = dblPosEnd;
this.dblElemCntrPos = (dblPosStart + dblPosEnd)/2.0;
this.dblElemLen = dblPosEnd - dblPosStart;
this.indNodeOrigPos = originalPosition;
}
/**
* Sets the (optional) string identifier for the modeling element that
* this object will create. Typically used when splitting up modeling
* elements associated with the proxied hardware node.
*
* @param strElemId identifier for the modeling element to be created
*
* @since Sep 5, 2014
*/
public void setModelingElementId(String strElemId) {
this.strElemId = strElemId;
}
/*
* Attribute Queries
*/
/**
* Returns the hardware node associated with this lattice element
* proxy.
*
* @return accelerator hardware node proxied by this lattice element
*
* @since Dec 9, 2014
*/
public AcceleratorNode getHardwareNode() {
return smfNode;
}
/**
* Returns the identifier string to be used for the modeling element created
* by this object.
*
* @return the element ID of the created object
*
* @author Christopher K. Allen
* @since Sep 5, 2014
*/
public String getModelingElementId() {
return strElemId;
}
/**
* Returns the class type of the modeling element used to represent the
* associated hardware node.
*
* @return class type of the modeling element to be created
*
* @author Christopher K. Allen
* @since Dec 9, 2014
*/
public Class<? extends IComponent> getModelingClass() {
return this.clsModElemType;
}
/**
* <p>
* Returns the length associated with the <em>hardware node</em>. This length
* depends upon the length of the hardware node and how many times it has
* been split to create the appropriate modeling element.
* </p>
* <p>
* Note that the <em>effective</em> length of the associated hardware node
* is used.
* If the hardware is a bending magnet then this is the path length. If
* the hardware node <em>is not</em> a magnet then the physical length is
* returned. These values are determined in the <code>LatticeElement</code>
* constructor.
* </p>
*
* @return length of this lattice element based upon hardware length and splitting
*
* @since Dec 9, 2014
*/
public double getLength() {
if (isThin())
return dblElemLen;
else
return dblElemExitPos - dblElemEntrPos;
}
/**
* Returns the entrance location within its parent element sequence
* of the modeling element to be created.
* This value is derived from the associated hardware position and the splitting
* of the representative lattice elements.
*
* @return entrance position of the modeling element w.r.t. the parent sequence
*
* @since Dec 9, 2014
*/
public double getStartPosition() {
return dblElemEntrPos;
}
/**
* Returns the center location of the modeling element to be created.
* This value is derived from the associated hardware position and the splitting
* of the representative lattice elements.
*
* @return axial center position within the parent sequence
*
* @since Dec 9, 2014
*/
public double getCenterPosition() {
if (isThin())
return dblElemCntrPos;
else
return dblElemEntrPos + 0.5 * (dblElemExitPos - dblElemEntrPos);
}
/**
* Returns the exit location of the modeling element to be created within its
* parent accelerator sequence.
*
* @return exit position of the modeling element w.r.t. the parent sequence
*
* @since Dec 9, 2014
*/
public double getEndPosition() {
return dblElemExitPos;
}
/**
* Determines whether or not the hardware accelerator node will be represented with a
* thin modeling element. Looks at both the <em>effective length</em>
* of the hardware node and the class type of the modeling element used to
* represent it.
*
* @return <code>true</code> if a modeling element derived from
* <code>ThinElement</code> will be returned, <code>false</code> otherwise
*
* @since Dec 4, 2014
*/
public boolean isThin() {
return dblElemLen == 0.0 || ThinElement.class.isAssignableFrom(clsModElemType);
}
/**
* Indicates whether or not this lattice element is artificial or not.
* An element is <i>artificial</i> if there is no hardware representation for
* it in the XDXF file. It was probably created as a placeholder within the
* lattice generation process.
*
* @return <code>true</code> if this element has no corresponding SMF hardware node,
* <code>false</code> if this element is artifical
*
* @since Jan 30, 2015 by Christopher K. Allen
*/
public boolean isArtificial() {
return this.bolArtificalElem;
}
/**
* Determines whether or not the given lattice element contains this element
* with respect to the axial positions. Specifically, if the entrance location
* of this element is greater than or equal to the entrance location of the given
* element, and the exit location of this element is less than or equal to the
* exit location of the given element, this method returns <code>true</code>.
*
* @param lem lattice element to compare against
*
* @return <code>true</code> if this element is contained within the axial
* position occupied by the given element, <code>false</code> otherwise
*
* @since Jan 28, 2015 by Christopher K. Allen
*/
public boolean isContainedIn(LatticeElement lem) {
if ( this.getStartPosition() >= lem.getStartPosition()
&& this.getEndPosition() <= lem.getEndPosition()
)
return true;
else
return false;
}
/*
* Operations
*/
/**
* Translates the element by the given amount along the beamline
* axis (of which sequence it belongs).
*
* @param dblOffset distance by which this element is translated
* (either positive or negative)
*
* @since Jan 29, 2015 by Christopher K. Allen
*/
public void axialTranslation(double dblOffset) {
this.dblElemEntrPos += dblOffset;
this.dblElemCntrPos += dblOffset;
this.dblElemExitPos += dblOffset;
}
/**
* <p>
* Appears to split this lattice element into two parts, presumably at the
* center position of the given element, returning the second part.
* </p>
* <p>
* The number of parts is doubled and I can't
* figure this out?? I assume "parts" is the number of modeling elements used
* to represent the hardware.
* </p>
* <p>
* In any event, this lattice element is modified,
* its position now lives only up to the center position of the given element.
* </p>
* <p>
* I am guessing that the given lattice element should be a proxy for a thin
* element, but it is not enforced here.
* </p>
*
* @param elemSplitPos the lattice element defining the splitting position
*
* @return a new lattice element which is the second part of this original lattice element
*
* @author Christopher K. Allen
* @since Dec 4, 2014
*/
public LatticeElement splitElementAt(final LatticeElement elemSplitPos) {
if (elemSplitPos.dblElemCntrPos == dblElemEntrPos || elemSplitPos.dblElemCntrPos == dblElemExitPos) return null;
return splitElementAt(elemSplitPos.dblElemCntrPos);
}
public LatticeElement splitElementAt(final double splitPos) {
LatticeElement secondPart;
if (isThin()) {
// For thin magnets, splitPos is the center of the new part and
// one should take care of moving the previous part to the right
// location.
secondPart = new LatticeElement(smfNode, splitPos, clsModElemType, indNodeOrigPos);
} else {
secondPart = new LatticeElement(smfNode, splitPos, dblElemExitPos, clsModElemType, indNodeOrigPos);
dblElemExitPos = splitPos;
}
secondPart.firstSlice = firstSlice;
secondPart.nextSlice = nextSlice;
nextSlice = secondPart;
return secondPart;
}
/**
* <p>
* Creates and initializes a new modeling element represented by this
* object. Java reflection is used to create a new instance from the element's
* class type. There must be a zero constructor for the element.
* </p>
* <p>
* <h4>CKA Notes</h4>
* · The parameter initialization is done by calling the
* <code>{@link IComponent#initializeFrom(LatticeElement)}</code>. This design
* effectively couples the <code>xal.model</code> online model subsystem to the
* <code>xal.smf</code> hardware representation subsystem. These
* systems should be independent, able to function without each other.
* </p>
*
* @return a new modeling element for the hardware proxied by this object
*
* @throws ModelException Java reflection threw an <code>InstantiationException</code>
*
* @since Dec 4, 2014
*/
public IComponent createModelingElement() throws ModelException {
if (component == null) {
try {
component = clsModElemType.newInstance();
component.initializeFrom(this);
return component;
} catch (InstantiationException | IllegalAccessException e) {
throw new ModelException("Exception while instantiating class "+clsModElemType.getName()+" for node "+smfNode.getId(), e);
}
}
return component;
}
/*
* Comparable Interface
*/
/**
* Compare by looking at hardware node positions. If the positions
* are equal and the elements are both thin then we look at the
* position index within the sequence.
*
* @see java.lang.Comparable#compareTo(java.lang.Object)
*
* @since Dec 4, 2014
*/
@Override
public int compareTo(LatticeElement e2) {
double p1 = isThin() ? dblElemCntrPos : dblElemEntrPos;
double p2 = e2.isThin() ? e2.dblElemCntrPos : e2.dblElemEntrPos;
int d = Double.compare(p1, p2);
if (d == 0) {
if (isThin() && e2.isThin())
d = indNodeOrigPos - e2.indNodeOrigPos;
else
d = isThin() ? -1 : 1;
}
return d;
}
/*
* Object Overrides
*/
/**
* Writes out entrance position, exit position, center position,
* and length.
*
* @see java.lang.Object#toString()
*
* @since Dec 4, 2014
*/
@Override
public String toString() {
String strDescr = this.getModelingElementId();
if (this.getHardwareNode() != null)
strDescr += ": Hardware ID=" + this.getHardwareNode().getId();
strDescr += " I=[" + getStartPosition() +
"," + getEndPosition() + "]" +
", p=" + getCenterPosition() +
", l= " + getLength();
return strDescr;
}
public LatticeElement getFirstSlice() {
return firstSlice;
}
public LatticeElement getNextSlice() {
return nextSlice;
}
public boolean isFirstSlice() {
return firstSlice == this;
}
public boolean isLastSlice() {
return nextSlice == null;
}
} |
package bisq.inventory;
import bisq.core.network.p2p.inventory.model.DeviationByIntegerDiff;
import bisq.core.network.p2p.inventory.model.DeviationByPercentage;
import bisq.core.network.p2p.inventory.model.DeviationSeverity;
import bisq.core.network.p2p.inventory.model.InventoryItem;
import bisq.core.network.p2p.inventory.model.RequestInfo;
import bisq.core.util.FormattingUtils;
import bisq.network.p2p.NodeAddress;
import bisq.common.app.Version;
import bisq.common.util.MathUtils;
import bisq.common.util.Utilities;
import com.google.common.base.Joiner;
import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.Nullable;
import spark.Spark;
@Slf4j
public class InventoryWebServer {
private final static String CLOSE_TAG = "</font><br/>";
private final static String WARNING_ICON = "⚠ ";
private final static String ALERT_ICON = "☠ "; // ⚡ ⚡
private final List<NodeAddress> seedNodes;
private final Map<String, String> operatorByNodeAddress = new HashMap<>();
private String html;
private int requestCounter;
// Constructor
public InventoryWebServer(int port,
List<NodeAddress> seedNodes,
BufferedReader seedNodeFile) {
this.seedNodes = seedNodes;
setupOperatorMap(seedNodeFile);
Spark.port(port);
Spark.get("/", (req, res) -> {
log.info("Incoming request from: {}", req.userAgent());
return html == null ? "Starting up..." : html;
});
}
// API
public void onNewRequestInfo(Map<NodeAddress, List<RequestInfo>> requestInfoListByNode, int requestCounter) {
this.requestCounter = requestCounter;
html = generateHtml(requestInfoListByNode);
}
public void shutDown() {
Spark.stop();
}
// HTML
private String generateHtml(Map<NodeAddress, List<RequestInfo>> map) {
StringBuilder html = new StringBuilder();
html.append("<html>" +
"<head>" +
"<style type=\"text/css\">" +
" a {" +
" text-decoration:none; color: black;" +
" }" +
" #warn { color: #ff7700; } " +
" #alert { color: #ff0000; } " +
"table, th, td {border: 1px solid black;}" +
"</style></head>" +
"<body><h3>")
.append("Current time: ").append(new Date().toString()).append("<br/>")
.append("Request cycle: ").append(requestCounter).append("<br/>")
.append("Version/commit: ").append(Version.VERSION).append(" / ").append(RequestInfo.COMMIT_HASH).append("<br/>")
.append("<table style=\"width:100%\">")
.append("<tr>")
.append("<th align=\"left\">Seed node info</th>")
.append("<th align=\"left\">Request info</th>")
.append("<th align=\"left\">Data inventory</th>")
.append("<th align=\"left\">DAO data</th>")
.append("<th align=\"left\">Network info</th>").append("</tr>");
seedNodes.forEach(seedNode -> {
html.append("<tr valign=\"top\">");
if (map.containsKey(seedNode) && !map.get(seedNode).isEmpty()) {
List<RequestInfo> list = map.get(seedNode);
int numRequests = list.size();
RequestInfo requestInfo = list.get(numRequests - 1);
html.append("<td>").append(getSeedNodeInfo(seedNode, requestInfo)).append("</td>")
.append("<td>").append(getRequestInfo(seedNode, requestInfo, numRequests, map)).append("</td>")
.append("<td>").append(getDataInfo(seedNode, requestInfo, map)).append("</td>")
.append("<td>").append(getDaoInfo(seedNode, requestInfo, map)).append("</td>")
.append("<td>").append(getNetworkInfo(seedNode, requestInfo, map)).append("</td>");
} else {
html.append("<td>").append(getSeedNodeInfo(seedNode, null)).append("</td>")
.append("<td>").append("n/a").append("</td>")
.append("<td>").append("n/a").append("</td>")
.append("<td>").append("n/a").append("</td>")
.append("<td>").append("n/a").append("</td>");
}
html.append("</tr>");
});
html.append("</table></body></html>");
return html.toString();
}
// Sub sections
private String getSeedNodeInfo(NodeAddress nodeAddress,
@Nullable RequestInfo requestInfo) {
StringBuilder sb = new StringBuilder();
String operator = operatorByNodeAddress.get(nodeAddress.getFullAddress());
sb.append("Operator: ").append(operator).append("<br/>");
String address = nodeAddress.getFullAddress();
String filteredSeeds = requestInfo != null ? requestInfo.getValue(InventoryItem.filteredSeeds) : null;
if (filteredSeeds != null && filteredSeeds.contains(address)) {
sb.append(getColorTagByDeviationSeverity(DeviationSeverity.ALERT)).append("Node address: ")
.append(address).append(" (is filtered!)").append(CLOSE_TAG);
} else {
sb.append("Node address: ").append(address).append("<br/>");
}
if (requestInfo != null) {
sb.append("Version: ").append(requestInfo.getDisplayValue(InventoryItem.version)).append("<br/>");
sb.append("Commit hash: ").append(requestInfo.getDisplayValue(InventoryItem.commitHash)).append("<br/>");
String memory = requestInfo.getValue(InventoryItem.usedMemory);
String memoryString = memory != null ? Utilities.readableFileSize(Long.parseLong(memory)) : "n/a";
sb.append("Memory used: ")
.append(memoryString)
.append("<br/>");
String jvmStartTimeString = requestInfo.getValue(InventoryItem.jvmStartTime);
long jvmStartTime = jvmStartTimeString != null ? Long.parseLong(jvmStartTimeString) : 0;
sb.append("Node started at: ")
.append(new Date(jvmStartTime).toString())
.append("<br/>");
String duration = jvmStartTime > 0 ?
FormattingUtils.formatDurationAsWords(System.currentTimeMillis() - jvmStartTime,
true, true) :
"n/a";
sb.append("Run duration: ").append(duration).append("<br/>");
String filteredSeedNodes = requestInfo.getDisplayValue(InventoryItem.filteredSeeds)
.replace(System.getProperty("line.separator"), "<br/>");
if (filteredSeedNodes.isEmpty()) {
filteredSeedNodes = "-";
}
sb.append("Filtered seed nodes: ")
.append(filteredSeedNodes)
.append("<br/>");
}
return sb.toString();
}
private String getRequestInfo(NodeAddress seedNode,
RequestInfo requestInfo,
int numRequests,
Map<NodeAddress, List<RequestInfo>> map) {
StringBuilder sb = new StringBuilder();
DeviationSeverity deviationSeverity = numRequests == requestCounter ?
DeviationSeverity.OK :
requestCounter - numRequests > 4 ?
DeviationSeverity.ALERT :
DeviationSeverity.WARN;
sb.append("Number of requests: ").append(getColorTagByDeviationSeverity(deviationSeverity))
.append(numRequests).append(CLOSE_TAG);
DeviationSeverity rrtDeviationSeverity = DeviationSeverity.OK;
String rrtString = "n/a";
if (requestInfo.getResponseTime() > 0) {
long rrt = requestInfo.getResponseTime() - requestInfo.getRequestStartTime();
if (rrt > 20_000) {
rrtDeviationSeverity = DeviationSeverity.ALERT;
} else if (rrt > 10_000) {
rrtDeviationSeverity = DeviationSeverity.WARN;
}
rrtString = MathUtils.roundDouble(rrt / 1000d, 3) + " sec";
}
sb.append("Round trip time: ").append(getColorTagByDeviationSeverity(rrtDeviationSeverity))
.append(rrtString).append(CLOSE_TAG);
Date requestStartTime = new Date(requestInfo.getRequestStartTime());
sb.append("Requested at: ").append(requestStartTime).append("<br/>");
String responseTime = requestInfo.getResponseTime() > 0 ?
new Date(requestInfo.getResponseTime()).toString() :
"n/a";
sb.append("Response received at: ").append(responseTime).append("<br/>");
sb.append(getErrorMsgLine(seedNode, requestInfo, map));
return sb.toString();
}
private String getDataInfo(NodeAddress seedNode,
RequestInfo requestInfo,
Map<NodeAddress, List<RequestInfo>> map) {
StringBuilder sb = new StringBuilder();
sb.append(getLine(InventoryItem.OfferPayload, seedNode, requestInfo, map));
sb.append(getLine(InventoryItem.MailboxStoragePayload, seedNode, requestInfo, map));
sb.append(getLine(InventoryItem.TradeStatistics3, seedNode, requestInfo, map));
sb.append(getLine(InventoryItem.AccountAgeWitness, seedNode, requestInfo, map));
sb.append(getLine(InventoryItem.SignedWitness, seedNode, requestInfo, map));
sb.append(getLine(InventoryItem.Alert, seedNode, requestInfo, map));
sb.append(getLine(InventoryItem.Filter, seedNode, requestInfo, map));
sb.append(getLine(InventoryItem.Mediator, seedNode, requestInfo, map));
sb.append(getLine(InventoryItem.RefundAgent, seedNode, requestInfo, map));
return sb.toString();
}
private String getDaoInfo(NodeAddress seedNode,
RequestInfo requestInfo,
Map<NodeAddress, List<RequestInfo>> map) {
StringBuilder sb = new StringBuilder();
sb.append(getLine("Number of BSQ blocks: ", InventoryItem.numBsqBlocks, seedNode, requestInfo, map));
sb.append(getLine(InventoryItem.TempProposalPayload, seedNode, requestInfo, map));
sb.append(getLine(InventoryItem.ProposalPayload, seedNode, requestInfo, map));
sb.append(getLine(InventoryItem.BlindVotePayload, seedNode, requestInfo, map));
sb.append(getLine("DAO state block height: ", InventoryItem.daoStateChainHeight, seedNode, requestInfo, map));
sb.append(getLine("DAO state hash: ", InventoryItem.daoStateHash, seedNode, requestInfo, map));
// The hash for proposal changes only at first block of blind vote phase but as we do not want to initialize the
// dao domain we cannot check that. But we also don't need that as we can just compare that all hashes at all
// blocks from all seeds are the same. Same for blindVoteHash.
sb.append(getLine("Proposal state hash: ", InventoryItem.proposalHash, seedNode, requestInfo, map));
sb.append(getLine("Blind vote state hash: ", InventoryItem.blindVoteHash, seedNode, requestInfo, map));
return sb.toString();
}
private String getNetworkInfo(NodeAddress seedNode,
RequestInfo requestInfo,
Map<NodeAddress, List<RequestInfo>> map) {
StringBuilder sb = new StringBuilder();
sb.append(getLine("Max. connections: ",
InventoryItem.maxConnections, seedNode, requestInfo, map));
sb.append(getLine("Number of connections: ",
InventoryItem.numConnections, seedNode, requestInfo, map));
sb.append(getLine("Peak number of connections: ",
InventoryItem.peakNumConnections, seedNode, requestInfo, map));
sb.append(getLine("Number of 'All connections lost' events: ",
InventoryItem.numAllConnectionsLostEvents, seedNode, requestInfo, map));
sb.append(getLine("Sent messages/sec: ",
InventoryItem.sentMessagesPerSec, seedNode, requestInfo, map, this::getRounded));
sb.append(getLine("Received messages/sec: ",
InventoryItem.receivedMessagesPerSec, seedNode, requestInfo, map, this::getRounded));
sb.append(getLine("Sent kB/sec: ",
InventoryItem.sentBytesPerSec, seedNode, requestInfo, map, this::getKbRounded));
sb.append(getLine("Received kB/sec: ",
InventoryItem.receivedBytesPerSec, seedNode, requestInfo, map, this::getKbRounded));
sb.append(getLine("Sent data: ",
InventoryItem.sentBytes, seedNode, requestInfo, map,
value -> Utilities.readableFileSize(Long.parseLong(value))));
sb.append(getLine("Received data: ",
InventoryItem.receivedBytes, seedNode, requestInfo, map,
value -> Utilities.readableFileSize(Long.parseLong(value))));
return sb.toString();
}
// Utils
private String getLine(InventoryItem inventoryItem,
NodeAddress seedNode,
RequestInfo requestInfo,
Map<NodeAddress, List<RequestInfo>> map) {
return getLine(getTitle(inventoryItem),
inventoryItem,
seedNode,
requestInfo,
map);
}
private String getLine(String title,
InventoryItem inventoryItem,
NodeAddress seedNode,
RequestInfo requestInfo,
Map<NodeAddress, List<RequestInfo>> map) {
return getLine(title,
inventoryItem,
seedNode,
requestInfo,
map,
null);
}
private String getLine(String title,
InventoryItem inventoryItem,
NodeAddress seedNode,
RequestInfo requestInfo,
Map<NodeAddress, List<RequestInfo>> map,
@Nullable Function<String, String> formatter) {
String displayValue = requestInfo.getDisplayValue(inventoryItem);
String value = requestInfo.getValue(inventoryItem);
if (formatter != null && value != null) {
displayValue = formatter.apply(value);
}
String deviationAsPercentString = "";
DeviationSeverity deviationSeverity = DeviationSeverity.OK;
if (requestInfo.getDataMap().containsKey(inventoryItem)) {
RequestInfo.Data data = requestInfo.getDataMap().get(inventoryItem);
deviationAsPercentString = getDeviationAsPercentString(inventoryItem, data);
deviationSeverity = data.getDeviationSeverity();
}
List<RequestInfo> requestInfoList = map.get(seedNode);
String historicalWarnings = "";
String historicalAlerts = "";
List<String> warningsAtRequestNumber = new ArrayList<>();
List<String> alertsAtRequestNumber = new ArrayList<>();
if (requestInfoList != null) {
for (int i = 0; i < requestInfoList.size(); i++) {
RequestInfo reqInfo = requestInfoList.get(i);
Map<InventoryItem, RequestInfo.Data> deviationInfoMap = reqInfo.getDataMap();
if (deviationInfoMap.containsKey(inventoryItem)) {
RequestInfo.Data data = deviationInfoMap.get(inventoryItem);
String deviationAsPercent = getDeviationAsPercentString(inventoryItem, data);
if (data.isPersistentWarning()) {
warningsAtRequestNumber.add((i + 1) + deviationAsPercent);
} else if (data.isPersistentAlert()) {
alertsAtRequestNumber.add((i + 1) + deviationAsPercent);
}
}
}
if (!warningsAtRequestNumber.isEmpty()) {
historicalWarnings = warningsAtRequestNumber.size() + " repeated warning(s) at request(s) " +
Joiner.on(", ").join(warningsAtRequestNumber);
}
if (!alertsAtRequestNumber.isEmpty()) {
historicalAlerts = alertsAtRequestNumber.size() + " repeated alert(s) at request(s): " +
Joiner.on(", ").join(alertsAtRequestNumber);
}
}
String historicalWarningsHtml = warningsAtRequestNumber.isEmpty() ? "" :
", <b><a id=\"warn\" href=\"#\" title=\"" + historicalWarnings + "\">" + WARNING_ICON +
warningsAtRequestNumber.size() + "</a></b>";
String historicalAlertsHtml = alertsAtRequestNumber.isEmpty() ? "" :
", <b><a id=\"alert\" href=\"#\" title=\"" + historicalAlerts + "\">" + ALERT_ICON +
alertsAtRequestNumber.size() + "</a></b>";
return title +
getColorTagByDeviationSeverity(deviationSeverity) +
displayValue +
deviationAsPercentString +
historicalWarningsHtml +
historicalAlertsHtml +
CLOSE_TAG;
}
private String getDeviationAsPercentString(InventoryItem inventoryItem, RequestInfo.Data data) {
Double deviation = data.getDeviation();
if (deviation == null || deviation == 1) {
return "";
}
if (inventoryItem.getDeviationType() instanceof DeviationByPercentage) {
return getDeviationInRoundedPercent(deviation);
} else if (inventoryItem.getDeviationType() instanceof DeviationByIntegerDiff) {
// For larger numbers like chain height we need to show all decimals as diff can be very small
return getDeviationInExactPercent(deviation);
} else {
return "";
}
}
private String getDeviationInRoundedPercent(double deviation) {
return " (" + MathUtils.roundDouble(100 * deviation, 2) + " %)";
}
private String getDeviationInExactPercent(double deviation) {
return " (" + 100 * deviation + " %)";
}
private String getColorTagByDeviationSeverity(@Nullable DeviationSeverity deviationSeverity) {
if (deviationSeverity == null) {
return "<font color=\"black\">";
}
switch (deviationSeverity) {
case WARN:
return "<font color=\"#0000cc\">";
case ALERT:
return "<font color=\"#cc0000\">";
case IGNORED:
return "<font color=\"#333333\">";
case OK:
default:
return "<font color=\"black\">";
}
}
private String getTitle(InventoryItem inventoryItem) {
return "Number of " + inventoryItem.getKey() + ": ";
}
private String getRounded(String value) {
return String.valueOf(MathUtils.roundDouble(Double.parseDouble(value), 2));
}
private String getKbRounded(String bytes) {
return String.valueOf(MathUtils.roundDouble(Double.parseDouble(bytes) / 1000, 2));
}
private void setupOperatorMap(BufferedReader seedNodeFile) {
seedNodeFile.lines().forEach(line -> {
if (!line.startsWith("
String[] strings = line.split(" \\(@");
String node = strings.length > 0 ? strings[0] : "n/a";
String operator = strings.length > 1 ? strings[1].replace(")", "") : "n/a";
operatorByNodeAddress.put(node, operator);
}
});
}
// We use here a bit diff. model as with other historical data alerts/warnings as we do not store it in the data
// object as we do with normal inventoryItems. So the historical error msg are not available in the json file.
// If we need it we have to move that handling here to the InventoryMonitor and change the data model to support the
// missing data for error messages.
private String getErrorMsgLine(NodeAddress seedNode,
RequestInfo requestInfo,
Map<NodeAddress, List<RequestInfo>> map) {
String errorMessage = requestInfo.hasError() ? requestInfo.getErrorMessage() : "-";
List<RequestInfo> requestInfoList = map.get(seedNode);
List<String> errorsAtRequestNumber = new ArrayList<>();
String historicalErrorsHtml = "";
if (requestInfoList != null) {
for (int i = 0; i < requestInfoList.size(); i++) {
RequestInfo requestInfo1 = requestInfoList.get(i);
// We ignore old errors as at startup timeouts are expected and each node restarts once a day
long duration = System.currentTimeMillis() - requestInfo1.getRequestStartTime();
if (requestInfo1.getRequestStartTime() > 0 && duration > TimeUnit.HOURS.toMillis(24)) {
continue;
}
if (requestInfo1.hasError()) {
errorsAtRequestNumber.add((i + 1) + " (" + requestInfo1.getErrorMessage() + ")");
}
}
if (!errorsAtRequestNumber.isEmpty()) {
String errorIcon;
String type;
String style;
if (errorsAtRequestNumber.size() > 4) {
errorIcon = ALERT_ICON;
type = "alert";
style = "alert";
} else {
errorIcon = WARNING_ICON;
type = "warning";
style = "warn";
}
String historicalAlerts = errorsAtRequestNumber.size() + " repeated " + type + "(s) at request(s): " +
Joiner.on(", ").join(errorsAtRequestNumber);
historicalErrorsHtml = errorsAtRequestNumber.isEmpty() ? "" :
", <b><a id=\"" + style + "\" href=\"#\" title=\"" + historicalAlerts + "\">" + errorIcon +
errorsAtRequestNumber.size() + "</a></b>";
}
}
DeviationSeverity deviationSeverity = requestInfo.hasError() ?
errorsAtRequestNumber.size() > 4 ? DeviationSeverity.ALERT : DeviationSeverity.WARN
: DeviationSeverity.OK;
return "Error message: " +
getColorTagByDeviationSeverity(deviationSeverity) +
errorMessage +
historicalErrorsHtml +
CLOSE_TAG;
}
} |
package com.j2ooxml.pptx;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import org.apache.commons.imaging.ImageInfo;
import org.apache.commons.imaging.ImageReadException;
import org.apache.commons.imaging.Imaging;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.sl.usermodel.PlaceableShape;
import org.apache.poi.util.IOUtils;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFBackground;
import org.apache.poi.xslf.usermodel.XSLFConnectorShape;
import org.apache.poi.xslf.usermodel.XSLFPictureShape;
import org.apache.poi.xslf.usermodel.XSLFShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.poi.xslf.usermodel.XSLFTextShape;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualPictureProperties;
import org.openxmlformats.schemas.presentationml.x2006.main.CTBackground;
import org.openxmlformats.schemas.presentationml.x2006.main.CTPicture;
import org.openxmlformats.schemas.presentationml.x2006.main.CTPictureNonVisual;
import org.w3c.css.sac.InputSource;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.css.CSSRule;
import org.w3c.dom.css.CSSRuleList;
import org.w3c.dom.css.CSSStyleDeclaration;
import org.w3c.dom.css.CSSStyleRule;
import org.w3c.dom.css.CSSStyleSheet;
import org.xml.sax.SAXException;
import com.j2ooxml.pptx.util.XmlUtil;
import com.steadystate.css.parser.CSSOMParser;
public class PptxGenerator {
private static final String NO_BACKGROUND = "no-background";
private VariableProcessor variableProcessor = new VariableProcessor();
private VideoReplacer videoReplacer = new VideoReplacer();
private Deletor deletor = new Deletor();
private EmptyNodesRemover emptyNodesRemover = new EmptyNodesRemover();
public void process(Path templatePath, Path cssPath, Path outputPath, Map<String, Object> model)
throws IOException, GenerationException {
try {
Files.copy(templatePath, outputPath, StandardCopyOption.REPLACE_EXISTING);
FileSystem fs = FileSystems.newFileSystem(outputPath, null);
CSSOMParser parser = new CSSOMParser();
String cssString = new String(Files.readAllBytes(cssPath), StandardCharsets.UTF_8);
if (model.containsKey("CSS")) {
String modelCss = (String) model.get("CSS");
cssString += " " + modelCss;
}
StringReader reader = new StringReader(cssString);
CSSStyleSheet css = parser.parseStyleSheet(new InputSource(reader), null, null);
Path slides = fs.getPath("/ppt/slides");
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(slides)) {
for (Path slideXml : directoryStream) {
if (Files.isRegularFile(slideXml)) {
String slide = slideXml.getFileName().toString();
Path relXml = fs.getPath("/ppt/slides/_rels/" + slide + ".rels");
State state = initState(fs, slideXml, model, css);
videoReplacer.replace(fs, slideXml, state, model);
deletor.process(state, model);
variableProcessor.process(state, css, model);
XmlUtil.save(slideXml, state.getSlideDoc());
XmlUtil.save(relXml, state.getRelDoc());
try (Stream<String> lines = Files.lines(relXml, StandardCharsets.UTF_8)) {
List<String> replaced = lines
.map(line -> line.replaceAll(
"(Target=\".*?\"(\\sTargetMode=\".*?\")?)\\s(Type=\".*?\")", "$3 $1"))
.collect(Collectors.toList());
lines.close();
Files.delete(relXml);
Files.write(relXml, replaced, StandardCharsets.UTF_8);
}
}
}
}
slides = fs.getPath("/ppt/slideLayouts");
try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(slides)) {
for (Path slideXml : directoryStream) {
if (Files.isRegularFile(slideXml)) {
Document slideDoc = XmlUtil.parse(slideXml);
emptyNodesRemover.process(slideDoc, model);
XmlUtil.save(slideXml, slideDoc);
}
}
}
Properties.fillProperies(fs, model);
fs.close();
XMLSlideShow ppt = new XMLSlideShow(Files.newInputStream(outputPath));
for (XSLFSlide slide : ppt.getSlides()) {
Boolean noBackground = (Boolean) model.get(NO_BACKGROUND);
if (noBackground) {
XSLFBackground bg = slide.getBackground();
CTBackground xmlBg = (CTBackground) bg.getXmlObject();
Node bgDomNode = xmlBg.getDomNode();
bgDomNode.getParentNode().removeChild(bgDomNode);
}
List<XSLFShape> shpesToRemove = new ArrayList<>();
for (XSLFShape sh : slide.getShapes()) {
String name = sh.getShapeName();
if (StringUtils.isNotEmpty(name) && name.startsWith("${") && name.endsWith("}")) {
name = name.substring(2, name.length() - 1);
Object value = model.get(name);
// shapes's anchor which defines the position of this shape in the slide
if (sh instanceof PlaceableShape) {
java.awt.geom.Rectangle2D anchor = ((PlaceableShape) sh).getAnchor();
}
if (sh instanceof XSLFConnectorShape) {
XSLFConnectorShape line = (XSLFConnectorShape) sh;
// work with Line
} else if (sh instanceof XSLFTextShape) {
XSLFTextShape shape = (XSLFTextShape) sh;
// work with a shape that can hold text
} else if (sh instanceof XSLFPictureShape) {
if (value == null) {
shpesToRemove.add(sh);
} else {
XSLFPictureShape picture = (XSLFPictureShape) sh;
Rectangle2D anchor = picture.getAnchor();
CTPicture xmlObject = (CTPicture) picture.getXmlObject();
CTPictureNonVisual nvPicPr = xmlObject.getNvPicPr();
CTNonVisualPictureProperties cNvPicPr = nvPicPr.getCNvPicPr();
boolean verticalCenter = !cNvPicPr.isSetPreferRelativeResize() || cNvPicPr.getPreferRelativeResize();
boolean smartStretch = !cNvPicPr.getPicLocks().getNoChangeAspect();
if (value instanceof Path) {
Path picturePath = (Path) value;
byte[] pictureBytes = IOUtils.toByteArray(Files.newInputStream(picturePath));
picture.getPictureData().setData(pictureBytes);
}
if (value instanceof Path && (smartStretch || verticalCenter)) {
Path picturePath = (Path) value;
double x = anchor.getX();
double y = anchor.getY();
double wp = anchor.getWidth();
double hp = anchor.getHeight();
ImageInfo imageInfo = Imaging.getImageInfo(picturePath.toFile());
int physicalHeightDpi = imageInfo.getPhysicalHeightDpi();
if (physicalHeightDpi < 0) {
physicalHeightDpi = 72;
}
int physicalWidthDpi = imageInfo.getPhysicalWidthDpi();
if (physicalWidthDpi < 0) {
physicalWidthDpi = 72;
}
double wi = Math.round(72. * imageInfo.getWidth() / physicalHeightDpi);
double hi = Math.round(72. * imageInfo.getHeight() / physicalWidthDpi);
double w = wp;
double h = hp;
double dx = 0;
double dy = 0;
if (verticalCenter) {
w = wi;
h = hi;
dx = wp - wi;
dy = (hp - hi) / 2;
} else if (smartStretch) {
if (wp / hp > wi / hi) {
w = wi * hp / hi;
dx = (wp - w) / 2;
} else if (wp / hp < wi / hi) {
h = hi * wp / wi;
dy = (hp - h) / 2;
}
}
anchor.setRect(x + dx, y + dy, w, h);
picture.setAnchor(anchor);
} else {
CSSRuleList rules = css.getCssRules();
if (value instanceof String) {
StringBuilder imsgeCss = new StringBuilder("
imsgeCss.append(name);
imsgeCss.append("{");
imsgeCss.append(value);
imsgeCss.append("}");
css.insertRule(imsgeCss.toString(), rules.getLength());
}
rules = css.getCssRules();
for (int r = 0; r < rules.getLength(); r++) {
CSSRule rule = rules.item(r);
if (rule instanceof CSSStyleRule) {
CSSStyleRule styleRule = (CSSStyleRule) rule;
if (styleRule.getSelectorText().equals("*#" + name)) {
CSSStyleDeclaration styleDeclaration = styleRule.getStyle();
for (int j = 0; j < styleDeclaration.getLength(); j++) {
String propertyName = styleDeclaration.item(j);
if ("left".equals(propertyName) || "top".equals(propertyName)) {
String propertyValue = styleDeclaration
.getPropertyValue(propertyName);
if ("left".equals(propertyName)) {
anchor.setRect(parseLength(propertyValue), anchor.getY(),
anchor.getWidth(), anchor.getHeight());
} else {
anchor.setRect(anchor.getX(), parseLength(propertyValue),
anchor.getWidth(), anchor.getHeight());
}
}
}
}
}
}
}
}
}
}
}
for (XSLFShape sh : shpesToRemove) {
slide.removeShape(sh);
}
}
OutputStream out = Files.newOutputStream(outputPath);
ppt.write(out);
out.close();
ppt.close();
} catch (Exception e) {
throw new GenerationException("Could not generate resulting ppt.", e);
}
}
private State initState(FileSystem fs, Path slideXml, Map<String, Object> model, CSSStyleSheet css) throws IOException,
ParserConfigurationException, SAXException, XPathExpressionException, DOMException, ImageReadException {
Document slideDoc = XmlUtil.parse(slideXml);
String slide = slideXml.getFileName().toString();
Path slideXmlRel = fs.getPath("/ppt/slides/_rels/" + slide + ".rels");
Document relsDoc = XmlUtil.parse(slideXmlRel);
return new State(slideDoc, relsDoc);
}
private double parseLength(String propertyValue) {
return Double.parseDouble(propertyValue.replace("mm", ""));
}
} |
package de.tum.in.reitinge.test;
import java.awt.Color;
import de.tum.in.jrealityplugin.AppearanceState;
import de.tum.in.jrealityplugin.Cindy3DViewer;
import de.tum.in.jrealityplugin.jogl.JOGLViewer;
public class JOGLViewerTest {
public static void main(String[] args) {
JOGLViewer viewer = new JOGLViewer();
viewer.setBackgroundColor(Color.white);
viewer.begin();
// colorSpiral(viewer);
// circles(viewer);
// lines(viewer);
icosahedron(viewer);
viewer.end();
}
public static void colorSpiral(Cindy3DViewer viewer) {
AppearanceState appearance = new AppearanceState(Color.red, 1.0);
double height = 2;
double radius = 1;
int segments = 100;
int rings = 20;
for (int segment = 1; segment <= segments; ++segment) {
double frac = (double) segment / segments;
appearance.setColor(new Color(Color.HSBtoRGB((float) frac, 1, 1)));
for (int ring = 1; ring <= rings; ++ring) {
double rad = (double) ring / rings * radius;
viewer.addPoint(Math.cos(frac * 2 * Math.PI) * rad,
Math.sin(frac * 2 * Math.PI) * rad, (frac - 0.5)
* height, appearance);
}
}
}
public static void circles(Cindy3DViewer viewer) {
AppearanceState appearance = new AppearanceState(Color.red, 1.0);
for (int i = -5; i <= 5; ++i) {
for (int j = -5; j <= 5; ++j) {
appearance.setColor(Color.red);
viewer.addCircle(i * 2, j * 2, 0, 1, 0, 0, 1, appearance);
appearance.setColor(Color.green);
viewer.addCircle(i * 2, j * 2, 0, 0, 1, 0, 1, appearance);
appearance.setColor(Color.blue);
viewer.addCircle(i * 2, j * 2, 0, 0, 0, 1, 1, appearance);
}
}
}
public static void lines(Cindy3DViewer viewer) {
AppearanceState appearance = new AppearanceState(Color.red, 1.0);
viewer.addSegment(-10, 0, 0, 8, 0, -0.5, appearance);
viewer.addLine(0, 2, 0, 5, 4, 0, appearance);
viewer.addRay(0, 4, 0, 5, -2, 2, appearance);
double r = 1;
int n = 750;
double[][] vertices = new double[n][3];
for (int i=0; i<n; ++i) {
vertices[i][2] = 0;
vertices[i][0] = r*Math.sin(i*2*Math.PI/n);
vertices[i][1] = r*Math.cos(i*2*Math.PI/n);
}
//viewer.addCircle(0, 0, 0.5, 0, 0, 1, r, appearance);
//viewer.addPolygon(vertices, null, appearance);
// viewer.addMesh(2, 3, new double[][] { { 0, 0, 0 }, { 1, 1, 0 },
// { 2, 0, 0 }, { 0, 0, 1 }, { 1, 1, 1 }, { 2, 0, 1 } },
// new double[][] { { -1, 1, 0 }, { 0, 1, 0 }, { 1, 1, 0 },
// { -1, 1, 1 }, { 0, 1, 0 }, { 1, 1, 0 } }, appearance);
appearance.setColor(Color.GREEN);
//viewer.addLineStrip(vertices, appearance, true);
}
public static void icosahedron(JOGLViewer viewer) {
AppearanceState appearance = new AppearanceState(Color.yellow, 1.0);
double golden = (1.0 + Math.sqrt(5)) / 2.0;
double verts[][] = {
{ 0, 1, golden },
{ 0, -1, golden },
{ 0, 1, -golden },
{ 0, -1, -golden },
{ golden, 0, 1 },
{ golden, 0, -1 },
{ -golden, 0, 1 },
{ -golden, 0, -1 },
{ 1, golden, 0 },
{ -1, golden, 0 },
{ 1, -golden, 0 },
{ -1, -golden, 0 },
};
int[][] edges = {
{ 0, 1 }, { 2, 3 }, { 4, 5 }, { 6, 7 }, { 8, 9 }, { 10, 11 },
{ 0, 8 }, { 2, 8 }, { 4, 0 }, { 6, 0 }, { 8, 4 }, { 10, 4 },
{ 0, 9 }, { 2, 9 }, { 4, 1 }, { 6, 1 }, { 8, 5 }, { 10, 5 },
{ 1, 10 }, { 3, 10 }, { 5, 2 }, { 7, 2 }, { 9, 6 }, { 11, 6 },
{ 1, 11 }, { 3, 11 }, { 5, 3 }, { 7, 3 }, { 9, 7 }, { 11, 7 },
};
for (int[] edge : edges) {
double vert1[] = verts[edge[0]];
double vert2[] = verts[edge[1]];
viewer.addSegment(vert1[0], vert1[1], vert1[2], vert2[0], vert2[1],
vert2[2], appearance);
}
}
} |
package info.tregmine.commands;
import java.util.List;
import org.bukkit.ChatColor;
import info.tregmine.Tregmine;
import info.tregmine.api.TregminePlayer;
public class InventoryCommand extends AbstractCommand
{
public InventoryCommand(Tregmine tregmine)
{
super(tregmine, "inv");
}
@Override
public boolean handlePlayer(TregminePlayer player, String[] args)
{
if(args.length == 0){
player.sendMessage(ChatColor.RED + "Incorrect usage:");
player.sendMessage(ChatColor.AQUA + "/inv inspect <name> - Inspect someones inventory");
player.sendMessage(ChatColor.AQUA + "/inv reload <name> <true/false> - Reload inventory, optional save");
player.sendMessage(ChatColor.AQUA + "/inv save - Save your current inventory to database");
return true;
}
if (!player.getRank().canInspectInventories()) {
return true;
}
if ("save".equalsIgnoreCase(args[0]) && args.length == 1) {
player.saveInventory(player.getCurrentInventory());
return true;
}
if ("reload".equalsIgnoreCase(args[0]) && args.length == 3) {
List<TregminePlayer> candidates = tregmine.matchPlayer(args[1]);
if (candidates.size() != 1) {
player.sendMessage(ChatColor.RED + "Player: " + args[1] + " not found!");
return true;
}
TregminePlayer candidate = candidates.get(0);
boolean state = "true".equalsIgnoreCase(args[2]);
if (state) {
candidate.loadInventory(candidate.getCurrentInventory(), true);
} else {
candidate.loadInventory(candidate.getCurrentInventory(), false);
}
player.sendMessage(ChatColor.GREEN + "Reloaded " + candidate.getChatName() + "'s inventory from DB!");
return true;
}
if ("inspect".equalsIgnoreCase(args[0]) && args.length == 2) {
List<TregminePlayer> candidates = tregmine.matchPlayer(args[1]);
if (candidates.size() != 1) {
player.sendMessage(ChatColor.RED + "Player: " + args[1] + " not found!");
return true;
}
TregminePlayer candidate = candidates.get(0);
player.openInventory(candidate.getInventory());
player.sendMessage(ChatColor.GREEN + "Inspecting " + candidate.getChatName() + "'s inventory!");
return true;
}
player.sendMessage(ChatColor.RED + "Incorrect usage:");
player.sendMessage(ChatColor.AQUA + "/inv inspect <name> - Inspect someones inventory");
player.sendMessage(ChatColor.AQUA + "/inv reload <name> <true/false> - Reload inventory, optional save");
player.sendMessage(ChatColor.AQUA + "/inv save - Save your current inventory to database");
return true;
}
} |
package dtos;
import de.fau.amos.virtualledger.dtos.Booking;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.Date;
public class BookingTest {
private Date date = new Date(19930501);
private double amount = 13123.3;
Booking booking;
@Before
public void setUp() {
booking = new Booking(date, amount);
}
@Test
public void constructorTest() {
Assert.assertNotNull(booking);
Booking booking2 = new Booking();
Assert.assertNotNull(booking2);
}
@Test
public void setAndGetDateTest() {
Date newDate = new Date(20170505);
booking.setDate(newDate);
Assert.assertEquals(newDate, booking.getDate());
}
@Test
public void setAndGetAmountTest() {
double newAmount = 5555;
booking.setAmount(newAmount);
Assert.assertEquals(newAmount, booking.getAmount(), 0);
}
@Test
public void setAndGetUsageTest() {
String newTestUsage = "TestUsage2";
booking.setUsage(newTestUsage);
String testUsage = booking.getUsage();
Assert.assertEquals(newTestUsage, testUsage);
}
} |
package io.flutter.console;
import com.google.common.annotations.VisibleForTesting;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.filters.Filter;
import com.intellij.execution.filters.HyperlinkInfo;
import com.intellij.execution.filters.OpenFileHyperlinkInfo;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.process.ProcessAdapter;
import com.intellij.execution.process.ProcessEvent;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import io.flutter.FlutterInitializer;
import io.flutter.FlutterMessages;
import io.flutter.FlutterUtils;
import io.flutter.actions.RestartFlutterApp;
import io.flutter.run.FlutterReloadManager;
import io.flutter.run.daemon.FlutterApp;
import io.flutter.sdk.FlutterSdk;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class FlutterConsoleFilter implements Filter {
private static class OpenExternalFileHyperlink implements HyperlinkInfo {
private final String myPath;
OpenExternalFileHyperlink(VirtualFile file) {
myPath = file.getPath();
}
@Override
public void navigate(Project project) {
try {
final GeneralCommandLine cmd = new GeneralCommandLine().withExePath("open").withParameters(myPath);
final OSProcessHandler handler = new OSProcessHandler(cmd);
handler.addProcessListener(new ProcessAdapter() {
@Override
public void processTerminated(@NotNull final ProcessEvent event) {
if (event.getExitCode() != 0) {
FlutterMessages.showError("Error Opening ", myPath);
}
}
});
handler.startNotify();
}
catch (ExecutionException e) {
FlutterMessages.showError(
"Error Opening External File",
"Exception: " + e.getMessage());
}
}
}
private static final Logger LOG = Logger.getInstance(FlutterConsoleFilter.class);
private final @NotNull Module module;
public FlutterConsoleFilter(@NotNull Module module) {
this.module = module;
}
@VisibleForTesting
@Nullable
public VirtualFile fileAtPath(@NotNull String pathPart) {
// "lib/main.dart:6"
pathPart = pathPart.split(":")[0];
final VirtualFile[] roots = ModuleRootManager.getInstance(module).getContentRoots();
for (VirtualFile root : roots) {
if (!pathPart.isEmpty()) {
final String baseDirPath = root.getPath();
final String path = baseDirPath + "/" + pathPart;
VirtualFile file = findFile(path);
if (file == null) {
// check example dir too
final String exampleDirRelativePath = baseDirPath + "/example/" + pathPart;
file = findFile(exampleDirRelativePath);
}
if (file != null) {
return file;
}
}
}
return null;
}
private static VirtualFile findFile(final String path) {
final VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path);
return file != null && file.exists() ? file : null;
}
@Nullable
public Result applyFilter(final String line, final int entireLength) {
if (line.startsWith("Run \"flutter doctor\" for information about installing additional components.")) {
return getFlutterDoctorResult(line, entireLength - line.length());
}
// Check for "restart" action in debugging output.
if (line.startsWith("you may need to restart the app")) {
return getRestartAppResult(line, entireLength - line.length());
}
int lineNumber = 0;
String pathPart = line.trim();
// Check for, e.g.,
// * "Launching lib/main.dart"
// * "open ios/Runner.xcworkspace"
if (pathPart.startsWith("Launching ") || pathPart.startsWith("open ")) {
final String[] parts = pathPart.split(" ");
if (parts.length > 1) {
pathPart = parts[1];
}
}
// Check for embedded paths, e.g.,
final String[] parts = pathPart.split(" ");
for (String part : parts) {
// "(lib/main.dart:49)"
if (part.startsWith("(") && part.endsWith(")")) {
part = part.substring(1, part.length() - 1);
final String[] split = part.split(":");
if (split.length == 2) {
try {
// Reconcile line number indexing.
lineNumber = Math.max(0, Integer.parseInt(split[1]) - 1);
}
catch (NumberFormatException e) {
// Ignored.
}
}
pathPart = part;
}
}
final VirtualFile file = fileAtPath(pathPart);
if (file != null) {
// "open ios/Runner.xcworkspace"
final boolean openAsExternalFile = FlutterUtils.isXcodeFileName(pathPart);
final int lineStart = entireLength - line.length() + line.indexOf(pathPart);
final HyperlinkInfo hyperlinkInfo =
openAsExternalFile ? new OpenExternalFileHyperlink(file) : new OpenFileHyperlinkInfo(module.getProject(), file, lineNumber, 0);
return new Result(lineStart, lineStart + pathPart.length(), hyperlinkInfo);
}
return null;
}
private static Result getFlutterDoctorResult(final String line, final int lineStart) {
final int commandStart = line.indexOf('"') + 1;
final int startOffset = lineStart + commandStart;
final int commandLength = "flutter doctor".length();
return new Result(startOffset, startOffset + commandLength, new FlutterDoctorHyperlinkInfo());
}
private static Result getRestartAppResult(final String line, final int lineStart) {
final int commandStart = line.indexOf("restart");
final int startOffset = lineStart + commandStart;
final int commandLength = "restart".length();
return new Result(startOffset, startOffset + commandLength, new RestartAppHyperlinkInfo());
}
private static class RestartAppHyperlinkInfo implements HyperlinkInfo {
@Override
public void navigate(final Project project) {
final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project);
if (sdk == null) {
Messages.showErrorDialog(project, "Flutter SDK not found", "Error");
return;
}
final FlutterApp app = FlutterApp.fromProjectProcess(project);
if (app == null) {
Messages.showErrorDialog(project, "Running Flutter App not found", "Error");
return;
}
FlutterInitializer.sendAnalyticsAction(RestartFlutterApp.class.getSimpleName());
FlutterReloadManager.getInstance(project).saveAllAndRestart(app);
}
}
private static class FlutterDoctorHyperlinkInfo implements HyperlinkInfo {
@Override
public void navigate(final Project project) {
// TODO(skybrian) analytics for clicking the link? (We do log the command.)
final FlutterSdk sdk = FlutterSdk.getFlutterSdk(project);
if (sdk == null) {
Messages.showErrorDialog(project, "Flutter SDK not found", "Error");
return;
}
if (sdk.flutterDoctor().startInConsole(project) == null) {
Messages.showErrorDialog(project, "Failed to start 'flutter doctor'", "Error");
}
}
}
} |
// $Id: LinePath.java,v 1.3 2002/05/31 20:47:32 mdb Exp $
package com.threerings.media.util;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.Point;
import com.samskivert.util.StringUtil;
import com.threerings.media.Log;
import com.threerings.media.util.MathUtil;
/**
* The line path is used to cause a pathable to go from point A to point B
* in a certain number of milliseconds.
*/
public class LinePath implements Path
{
/**
* Constructs a line path between the two specified points that will
* be followed in the specified number of milliseconds.
*/
public LinePath (int x1, int y1, int x2, int y2, long duration)
{
this(new Point(x1, y1), new Point(x2, y2), duration);
}
/**
* Constructs a line path between the two specified points that will
* be followed in the specified number of milliseconds.
*/
public LinePath (Point source, Point dest, long duration)
{
// sanity check some things
if (duration <= 0) {
String errmsg = "Requested path with illegal duration (<=0) " +
"[duration=" + duration + "]";
throw new IllegalArgumentException(errmsg);
}
_source = source;
_dest = dest;
_duration = duration;
_distance = (int)MathUtil.distance(_source, _dest);
}
// documentation inherited from interface
public void viewWillScroll (int dx, int dy)
{
// adjust our source and destination points
_source.translate(-dx, -dy);
_dest.translate(-dx, -dy);
}
// documentation inherited
public void init (Pathable pable, long timestamp)
{
// give the pable a chance to perform any starting antics
pable.pathBeginning();
// make a note of the time at which we expect to arrive
_arrivalTime = timestamp + _duration;
// pretend like we just moved the pathable
_lastMoveX = _lastMoveY = timestamp;
// update our position to the start of the path
tick(pable, timestamp);
}
// documentation inherited
public boolean tick (Pathable pable, long timestamp)
{
// if we've blown past our arrival time, we need to get our bootay
// to the prearranged spot and get the hell out
if (timestamp >= _arrivalTime) {
pable.setLocation(_dest.x, _dest.y);
pable.pathCompleted();
return true;
}
// the number of milliseconds since we last moved (move delta)
float dtX = (float)(timestamp - _lastMoveX);
float dtY = (float)(timestamp - _lastMoveY);
// the number of milliseconds until we're expected to finish
float rtX = (float)(_arrivalTime - _lastMoveX);
float rtY = (float)(_arrivalTime - _lastMoveY);
// how many pixels we have left to go
int leftx = _dest.x - pable.getX(), lefty = _dest.y - pable.getY();
// we want to move the pathable by the remaining distance
// multiplied by the move delta divided by the remaining time and
// we update our last move stamps if there is movement to be had
// in either direction
int dx = Math.round((float)(leftx * dtX) / rtX);
if (dx != 0) {
_lastMoveX = timestamp;
}
int dy = Math.round((float)(lefty * dtY) / rtY);
if (dy != 0) {
_lastMoveY = timestamp;
}
// Log.info("Updated pathable [duration=" + _duration +
// ", dist=" + _distance + ", dt=" + dt + ", rt=" + rt +
// ", leftx=" + leftx + ", lefty=" + lefty +
// ", dx=" + dx + ", dy=" + dy + "].");
// only update the pathable's location if it actually moved
if (dx != 0 || dy != 0) {
pable.setLocation(pable.getX() + dx, pable.getY() + dy);
return true;
}
return false;
}
// documentation inherited
public void fastForward (long timeDelta)
{
_arrivalTime += timeDelta;
_lastMoveX += timeDelta;
_lastMoveY += timeDelta;
}
// documentation inherited
public void paint (Graphics2D gfx)
{
gfx.setColor(Color.red);
gfx.drawLine(_source.x, _source.y, _dest.x, _dest.y);
}
// documentation inherited
public String toString ()
{
return "[src=" + StringUtil.toString(_source) +
", dest=" + StringUtil.toString(_dest) +
", duration=" + _duration + "ms]";
}
/** Our source and destination points. */
protected Point _source, _dest;
/** The direct pixel distance along the path. */
protected int _distance;
/** The duration that we're to spend following the path. */
protected long _duration;
/** The time at which we expect to complete our path. */
protected long _arrivalTime;
/** The time at which we last actually moved the pathable in the x
* direction. */
protected long _lastMoveX;
/** The time at which we last actually moved the pathable in the y
* direction. */
protected long _lastMoveY;
} |
// $Id: MessageManager.java,v 1.7 2004/03/31 02:09:37 mdb Exp $
package com.threerings.util;
import java.util.HashMap;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import com.samskivert.util.StringUtil;
/**
* The message manager provides a thin wrapper around Java's built-in
* localization support, supporting a policy of dividing up localization
* resources into logical units, all of the translations for which are
* contained in a single messages file.
*
* <p> The message manager assumes that the locale remains constant for
* the duration of its operation. If the locale were to change during the
* operation of the client, a call to {@link #setLocale} should be made to
* inform the message manager of the new locale (which will clear the
* message bundle cache).
*/
public class MessageManager
{
/** The name of the global resource bundle (which other bundles revert
* to if they can't locate a message within themselves). It must be
* named <code>global.properties</code> and live at the top of the
* bundle hierarchy. */
public static final String GLOBAL_BUNDLE = "global";
/**
* Constructs a message manager with the supplied resource prefix and
* the default locale. The prefix will be prepended to the path of all
* resource bundles prior to their resolution. For example, if a
* prefix of <code>rsrc.messages</code> was provided and a message
* bundle with the name <code>game.chess</code> was later requested,
* the message manager would attempt to load a resource bundle with
* the path <code>rsrc.messages.game.chess</code> and would eventually
* search for a file in the classpath with the path
* <code>rsrc/messages/game/chess.properties</code>.
*
* <p> See the documentation for {@link
* ResourceBundle#getBundle(String,Locale,ClassLoader)} for a more
* detailed explanation of how resource bundle paths are resolved.
*/
public MessageManager (String resourcePrefix)
{
// keep the prefix
_prefix = resourcePrefix;
// use the default locale
_locale = Locale.getDefault();
Log.info("Using locale: " + _locale + ".");
// make sure the prefix ends with a dot
if (!_prefix.endsWith(".")) {
_prefix += ".";
}
// load up the global bundle
_global = getBundle(GLOBAL_BUNDLE);
}
/**
* Sets the locale to the specified locale. Subsequent message bundles
* fetched via the message manager will use the new locale. The
* message bundle cache will also be cleared.
*/
public void setLocale (Locale locale)
{
_locale = locale;
_cache.clear();
}
/**
* Fetches the message bundle for the specified path. If no bundle can
* be located with the specified path, a special bundle is returned
* that returns the untranslated message identifiers instead of an
* associated translation. This is done so that error code to handle a
* failed bundle load need not be replicated wherever bundles are
* used. Instead an error will be logged and the requesting service
* can continue to function in an impaired state.
*/
public MessageBundle getBundle (String path)
{
// first look in the cache
MessageBundle bundle = (MessageBundle)_cache.get(path);
if (bundle != null) {
return bundle;
}
// if it's not cached, we'll need to resolve it
String fqpath = _prefix + path;
ResourceBundle rbundle = null;
try {
rbundle = ResourceBundle.getBundle(fqpath, _locale);
} catch (MissingResourceException mre) {
Log.warning("Unable to resolve resource bundle " +
"[path=" + fqpath + ", locale=" + _locale + "].");
}
// if the resource bundle contains a special resource, we'll
// interpret that as a derivation of MessageBundle to instantiate
// for handling that class
if (rbundle != null) {
String mbclass = null;
try {
mbclass = rbundle.getString(MBUNDLE_CLASS_KEY);
if (!StringUtil.blank(mbclass)) {
bundle = (MessageBundle)
Class.forName(mbclass).newInstance();
}
} catch (MissingResourceException mre) {
// nothing to worry about
} catch (Throwable t) {
Log.warning("Failure instantiating custom message bundle " +
"[mbclass=" + mbclass + ", error=" + t + "].");
}
}
// if there was no custom class, or we failed to instantiate the
// custom class, use a standard message bundle
if (bundle == null) {
bundle = new MessageBundle();
}
// initialize our message bundle, cache it and return it (if we
// couldn't resolve the bundle, the message bundle will cope with
// it's null resource bundle)
bundle.init(this, path, rbundle, _global);
_cache.put(path, bundle);
return bundle;
}
/** The prefix we prepend to resource paths prior to loading. */
protected String _prefix;
/** The locale for which we're obtaining message bundles. */
protected Locale _locale;
/** A cache of instantiated message bundles. */
protected HashMap _cache = new HashMap();
/** Our top-level message bundle, from which others obtain messages if
* they can't find them within themselves. */
protected MessageBundle _global;
/** A key that can contain the classname of a custom message bundle
* class to be used to handle messages for a particular bundle. */
protected static final String MBUNDLE_CLASS_KEY = "msgbundle_class";
} |
package org.jaxen.function;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import org.jaxen.Context;
import org.jaxen.Function;
import org.jaxen.FunctionCallException;
import org.jaxen.Navigator;
public class IdFunction implements Function
{
/**
* Returns the node with the specified ID.
*
* @param context the context at the point in the
* expression when the function is called
* @param args a list with exactly one item which is either a string
* a node-set
*
* @return a <code>List</code> containing the node with the specified ID; or
* an empty list if there is no such node
*
* @throws FunctionCallException if <code>args</code> has more or less than one item
*/
public Object call(Context context, List args) throws FunctionCallException
{
if ( args.size() == 1 ) {
return evaluate( context.getNodeSet(),
args.get(0), context.getNavigator() );
}
throw new FunctionCallException( "id() requires one argument" );
}
/**
* Returns the node with the specified ID.
* @param contextNodes the context-node-set. The first item in this list
* determines the document in which the search is performed.
* @param arg the ID or IDs to search for
* @param nav the navigator used to calculate string-values and search
* by ID
*
* @return a <code>List</code> containing the node with the specified ID; or
* an empty list if there is no such node
*
*/
public static List evaluate(List contextNodes, Object arg, Navigator nav)
{
if (contextNodes.size() == 0) return Collections.EMPTY_LIST;
List nodes = new ArrayList();
Object contextNode = contextNodes.get(0);
if (arg instanceof List) {
Iterator iter = ((List)arg).iterator();
while (iter.hasNext()) {
String id = StringFunction.evaluate(iter.next(), nav);
nodes.addAll( evaluate( contextNodes, id, nav ) );
}
}
else {
String ids = StringFunction.evaluate(arg, nav);
StringTokenizer tok = new StringTokenizer(ids, " \t\n\r");
while (tok.hasMoreTokens()) {
String id = tok.nextToken();
Object node = nav.getElementById(contextNode, id);
if (node != null) {
nodes.add(node);
}
}
}
return nodes;
}
} |
package org.jsmpp.session;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.Hashtable;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.Logger;
import org.jsmpp.BindType;
import org.jsmpp.DefaultPDUReader;
import org.jsmpp.DefaultPDUSender;
import org.jsmpp.InterfaceVersion;
import org.jsmpp.InvalidCommandLengthException;
import org.jsmpp.InvalidResponseException;
import org.jsmpp.NumberingPlanIndicator;
import org.jsmpp.PDUReader;
import org.jsmpp.PDUSender;
import org.jsmpp.PDUStringException;
import org.jsmpp.SMPPConstant;
import org.jsmpp.SynchronizedPDUReader;
import org.jsmpp.SynchronizedPDUSender;
import org.jsmpp.TypeOfNumber;
import org.jsmpp.bean.BindResp;
import org.jsmpp.bean.Command;
import org.jsmpp.bean.DataCoding;
import org.jsmpp.bean.DeliverSm;
import org.jsmpp.bean.ESMClass;
import org.jsmpp.bean.EnquireLinkResp;
import org.jsmpp.bean.QuerySmResp;
import org.jsmpp.bean.RegisteredDelivery;
import org.jsmpp.bean.SubmitSmResp;
import org.jsmpp.bean.UnbindResp;
import org.jsmpp.extra.NegativeResponseException;
import org.jsmpp.extra.PendingResponse;
import org.jsmpp.extra.ProcessMessageException;
import org.jsmpp.extra.ResponseTimeoutException;
import org.jsmpp.extra.SessionState;
import org.jsmpp.session.state.SMPPSessionState;
import org.jsmpp.util.DefaultComposer;
import org.jsmpp.util.Sequence;
/**
* @author uudashr
* @version 2.0
*
*/
public class SMPPSession {
private static final Logger logger = Logger.getLogger(SMPPSession.class);
private static final PDUSender pduSender = new SynchronizedPDUSender(new DefaultPDUSender(new DefaultComposer()));
private static final PDUReader pduReader = new SynchronizedPDUReader(new DefaultPDUReader());
private static final AtomicInteger sessionIdSequence = new AtomicInteger();
private Socket socket = new Socket();
private DataInputStream in;
private OutputStream out;
private SessionState sessionState = SessionState.CLOSED;
private SMPPSessionState stateProcessor = SMPPSessionState.CLOSED;
private final Sequence sequence = new Sequence();
private final SMPPSessionHandler sessionHandler = new SMPPSessionHandlerImpl();
private final Hashtable<Integer, PendingResponse<? extends Command>> pendingResponse = new Hashtable<Integer, PendingResponse<? extends Command>>();
private int sessionTimer = 5000;
private long transactionTimer = 2000;
private int enquireLinkToSend;
private long lastActivityTimestamp;
private MessageReceiverListener messageReceiverListener;
private SessionStateListener sessionStateListener;
private IdleActivityChecker idleActivityChecker;
private EnquireLinkSender enquireLinkSender;
private int sessionId = sessionIdSequence.incrementAndGet();
public SMPPSession() {
}
public int getSessionId() {
return sessionId;
}
public void connectAndBind(String host, int port, BindType bindType,
String systemId, String password, String systemType,
TypeOfNumber addrTon, NumberingPlanIndicator addrNpi,
String addressRange) throws IOException {
if (sequence.currentValue() != 0)
throw new IOException("Failed connecting");
socket.connect(new InetSocketAddress(host, port));
if (socket.getInputStream() == null) {
logger.fatal("InputStream is null");
} else if (socket.isInputShutdown()) {
logger.fatal("Input shutdown");
}
logger.info("Connected");
changeState(SessionState.OPEN);
try {
in = new DataInputStream(socket.getInputStream());
new PDUReaderWorker().start();
new PDUReaderWorker().start();
new PDUReaderWorker().start();
out = socket.getOutputStream();
sendBind(bindType, systemId, password, systemType,
InterfaceVersion.IF_34, addrTon, addrNpi, addressRange);
changeToBoundState(bindType);
socket.setSoTimeout(sessionTimer);
enquireLinkSender = new EnquireLinkSender();
enquireLinkSender.start();
idleActivityChecker = new IdleActivityChecker();
idleActivityChecker.start();
} catch (PDUStringException e) {
logger.error("Failed sending bind command", e);
} catch (NegativeResponseException e) {
String message = "Receive negative bind response";
logger.error(message, e);
closeSocket();
throw new IOException(message + ": " + e.getMessage());
} catch (InvalidResponseException e) {
String message = "Receive invalid response of bind";
logger.error(message, e);
closeSocket();
throw new IOException(message + ": " + e.getMessage());
} catch (ResponseTimeoutException e) {
String message = "Waiting bind response take time to long";
logger.error(message, e);
closeSocket();
throw new IOException(message + ": " + e.getMessage());
} catch (IOException e) {
logger.error("IO Error occure", e);
closeSocket();
throw e;
}
}
/**
* @param bindType
* @param systemId
* @param password
* @param systemType
* @param interfaceVersion
* @param addrTon
* @param addrNpi
* @param addressRange
* @return SMSC system id.
* @throws PDUStringException if we enter invalid bind parameter(s).
* @throws ResponseTimeoutException if there is no valid response after defined millis.
* @throws InvalidResponseException if there is invalid response found.
* @throws NegativeResponseException if we receive negative response.
* @throws IOException
*/
private String sendBind(BindType bindType, String systemId,
String password, String systemType,
InterfaceVersion interfaceVersion, TypeOfNumber addrTon,
NumberingPlanIndicator addrNpi, String addressRange)
throws PDUStringException, ResponseTimeoutException,
InvalidResponseException, NegativeResponseException, IOException {
int seqNum = sequence.nextValue();
PendingResponse<BindResp> pendingResp = new PendingResponse<BindResp>(transactionTimer);
pendingResponse.put(seqNum, pendingResp);
try {
pduSender.sendBind(out, bindType, seqNum, systemId, password, systemType, interfaceVersion, addrTon, addrNpi, addressRange);
} catch (IOException e) {
logger.error("Failed sending bind command", e);
pendingResponse.remove(seqNum);
throw e;
}
try {
pendingResp.waitDone();
logger.info("Bind response received");
} catch (ResponseTimeoutException e) {
pendingResponse.remove(seqNum);
throw e;
} catch (InvalidResponseException e) {
pendingResponse.remove(seqNum);
throw e;
}
if (pendingResp.getResponse().getCommandStatus() != SMPPConstant.STAT_ESME_ROK)
throw new NegativeResponseException(pendingResp.getResponse().getCommandStatus());
return pendingResp.getResponse().getSystemId();
}
/**
* Ensure we have proper link.
* @throws ResponseTimeoutException if there is no valid response after defined millis.
* @throws InvalidResponseException if there is invalid response found.
* @throws IOException
*/
private void enquireLink() throws ResponseTimeoutException, InvalidResponseException, IOException {
int seqNum = sequence.nextValue();
PendingResponse<EnquireLinkResp> pendingResp = new PendingResponse<EnquireLinkResp>(transactionTimer);
pendingResponse.put(seqNum, pendingResp);
try {
pduSender.sendEnquireLink(out, seqNum);
} catch (IOException e) {
logger.error("Failed sending enquire link", e);
pendingResponse.remove(seqNum);
throw e;
}
try {
pendingResp.waitDone();
logger.info("Enquire link response received");
} catch (ResponseTimeoutException e) {
pendingResponse.remove(seqNum);
throw e;
} catch (InvalidResponseException e) {
pendingResponse.remove(seqNum);
throw e;
}
if (pendingResp.getResponse().getCommandStatus() != SMPPConstant.STAT_ESME_ROK) {
// this is ok
logger.warn("Receive NON-OK response of enquire link");
}
}
public void unbindAndClose() {
try {
unbind();
} catch (ResponseTimeoutException e) {
logger.error("Timeout waiting unbind response", e);
} catch (InvalidResponseException e) {
logger.error("Receive invalid unbind response", e);
} catch (IOException e) {
logger.error("IO error found ", e);
}
closeSocket();
}
private void unbind() throws ResponseTimeoutException, InvalidResponseException, IOException {
int seqNum = sequence.nextValue();
PendingResponse<UnbindResp> pendingResp = new PendingResponse<UnbindResp>(transactionTimer);
pendingResponse.put(seqNum, pendingResp);
try {
pduSender.sendUnbind(out, seqNum);
} catch (IOException e) {
logger.error("Failed sending unbind", e);
pendingResponse.remove(seqNum);
throw e;
}
try {
pendingResp.waitDone();
logger.info("Unbind response received");
changeState(SessionState.UNBOUND);
} catch (ResponseTimeoutException e) {
pendingResponse.remove(seqNum);
throw e;
} catch (InvalidResponseException e) {
pendingResponse.remove(seqNum);
throw e;
}
if (pendingResp.getResponse().getCommandStatus() != SMPPConstant.STAT_ESME_ROK)
logger.warn("Receive NON-OK response of unbind");
}
/**
* @param serviceType
* @param sourceAddrTon
* @param sourceAddrNpi
* @param sourceAddr
* @param destAddrTon
* @param destAddrNpi
* @param destinationAddr
* @param esmClass
* @param protocoId
* @param priorityFlag
* @param scheduleDeliveryTime
* @param validityPeriod
* @param registeredDelivery
* @param replaceIfPresent
* @param dataCoding
* @param smDefaultMsgId
* @param shortMessage
* @return message id.
* @throws PDUStringException if we enter invalid bind parameter(s).
* @throws ResponseTimeoutException if there is no valid response after defined millis.
* @throws InvalidResponseException if there is invalid response found.
* @throws NegativeResponseException if we receive negative response.
* @throws IOException
*/
public String submitShortMessage(String serviceType,
TypeOfNumber sourceAddrTon, NumberingPlanIndicator sourceAddrNpi,
String sourceAddr, TypeOfNumber destAddrTon,
NumberingPlanIndicator destAddrNpi, String destinationAddr,
ESMClass esmClass, byte protocoId, byte priorityFlag,
String scheduleDeliveryTime, String validityPeriod,
RegisteredDelivery registeredDelivery, byte replaceIfPresent,
DataCoding dataCoding, byte smDefaultMsgId, byte[] shortMessage)
throws PDUStringException, ResponseTimeoutException,
InvalidResponseException, NegativeResponseException, IOException {
int seqNum = sequence.nextValue();
PendingResponse<SubmitSmResp> pendingResp = new PendingResponse<SubmitSmResp>(transactionTimer);
pendingResponse.put(seqNum, pendingResp);
try {
pduSender.sendSubmitSm(out, seqNum, serviceType, sourceAddrTon,
sourceAddrNpi, sourceAddr, destAddrTon, destAddrNpi,
destinationAddr, esmClass, protocoId, priorityFlag,
scheduleDeliveryTime, validityPeriod, registeredDelivery,
replaceIfPresent, dataCoding, smDefaultMsgId, shortMessage);
} catch (IOException e) {
logger.error("Failed submit short message", e);
pendingResponse.remove(seqNum);
closeSocket();
throw e;
}
try {
pendingResp.waitDone();
logger.debug("Submit sm response received");
} catch (ResponseTimeoutException e) {
pendingResponse.remove(seqNum);
logger.debug("Response timeout for submit_sm with sessionIdSequence number " + seqNum);
throw e;
} catch (InvalidResponseException e) {
pendingResponse.remove(seqNum);
throw e;
}
if (pendingResp.getResponse().getCommandStatus() != SMPPConstant.STAT_ESME_ROK)
throw new NegativeResponseException(pendingResp.getResponse().getCommandStatus());
return pendingResp.getResponse().getMessageId();
}
public QuerySmResult queryShortMessage(String messageId, TypeOfNumber sourceAddrTon,
NumberingPlanIndicator sourceAddrNpi, String sourceAddr)
throws PDUStringException, ResponseTimeoutException,
InvalidResponseException, NegativeResponseException, IOException {
int seqNum = sequence.nextValue();
PendingResponse<QuerySmResp> pendingResp = new PendingResponse<QuerySmResp>(transactionTimer);
pendingResponse.put(seqNum, pendingResp);
try {
pduSender.sendQuerySm(out, seqNum, messageId, sourceAddrTon, sourceAddrNpi, sourceAddr);
} catch (IOException e) {
logger.error("Failed submit short message", e);
pendingResponse.remove(seqNum);
closeSocket();
throw e;
}
try {
pendingResp.waitDone();
logger.info("Query sm response received");
} catch (ResponseTimeoutException e) {
pendingResponse.remove(seqNum);
throw e;
} catch (InvalidResponseException e) {
pendingResponse.remove(seqNum);
throw e;
}
QuerySmResp resp = pendingResp.getResponse();
if (resp.getCommandStatus() != SMPPConstant.STAT_ESME_ROK)
throw new NegativeResponseException(resp.getCommandStatus());
if (resp.getMessageId().equals(messageId)) {
return new QuerySmResult(resp.getFinalDate(), resp.getMessageState(), resp.getErrorCode());
} else {
// message id requested not same as the returned
throw new InvalidResponseException("Requested message_id doesn't match with the result");
}
}
private void changeToBoundState(BindType bindType) {
if (bindType.equals(BindType.BIND_TX)) {
changeState(SessionState.BOUND_TX);
} else if (bindType.equals(BindType.BIND_RX)) {
changeState(SessionState.BOUND_RX);
} else if (bindType.equals(BindType.BIND_TRX)){
changeState(SessionState.BOUND_TRX);
} else {
throw new IllegalArgumentException("Bind type " + bindType + " not supported");
}
try {
socket.setSoTimeout(sessionTimer);
} catch (SocketException e) {
logger.error("Failed setting so_timeout for session timer", e);
}
}
private synchronized void changeState(SessionState newState) {
if (sessionState != newState) {
final SessionState oldState = sessionState;
sessionState = newState;
// change the session state processor
if (sessionState == SessionState.OPEN) {
stateProcessor = SMPPSessionState.OPEN;
} else if (sessionState == SessionState.BOUND_RX) {
stateProcessor = SMPPSessionState.BOUND_RX;
} else if (sessionState == SessionState.BOUND_TX) {
stateProcessor = SMPPSessionState.BOUND_TX;
} else if (sessionState == SessionState.BOUND_TRX) {
stateProcessor = SMPPSessionState.BOUND_TRX;
} else if (sessionState == SessionState.UNBOUND) {
stateProcessor = SMPPSessionState.UNBOUND;
} else if (sessionState == SessionState.CLOSED) {
stateProcessor = SMPPSessionState.CLOSED;
}
fireChangeState(newState, oldState);
}
}
private void updateActivityTimestamp() {
lastActivityTimestamp = System.currentTimeMillis();
}
private void addEnquireLinkJob() {
enquireLinkToSend++;
}
public int getSessionTimer() {
return sessionTimer;
}
public void setSessionTimer(int sessionTimer) {
this.sessionTimer = sessionTimer;
if (sessionState.isBound()) {
try {
socket.setSoTimeout(sessionTimer);
} catch (SocketException e) {
logger.error("Failed setting so_timeout for session timer", e);
}
}
}
public long getTransactionTimer() {
return transactionTimer;
}
public void setTransactionTimer(long transactionTimer) {
this.transactionTimer = transactionTimer;
}
public synchronized SessionState getSessionState() {
return sessionState;
}
public void setSessionStateListener(
SessionStateListener sessionStateListener) {
this.sessionStateListener = sessionStateListener;
}
public void setMessageReceiverListener(
MessageReceiverListener messageReceiverListener) {
this.messageReceiverListener = messageReceiverListener;
}
private void closeSocket() {
changeState(SessionState.CLOSED);
if (!socket.isClosed()) {
try {
socket.close();
} catch (IOException e) {
logger.warn("Failed closing socket", e);
}
}
}
private synchronized boolean isReadPdu() {
return sessionState.isBound() || sessionState.equals(SessionState.OPEN);
}
private void readPDU() {
try {
Command pduHeader = null;
byte[] pdu = null;
synchronized (in) {
pduHeader = pduReader.readPDUHeader(in);
pdu = pduReader.readPDU(in, pduHeader);
}
switch (pduHeader.getCommandId()) {
case SMPPConstant.CID_BIND_RECEIVER_RESP:
case SMPPConstant.CID_BIND_TRANSMITTER_RESP:
case SMPPConstant.CID_BIND_TRANSCEIVER_RESP:
updateActivityTimestamp();
stateProcessor.processBindResp(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_GENERIC_NACK:
updateActivityTimestamp();
stateProcessor.processGenericNack(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_ENQUIRE_LINK:
updateActivityTimestamp();
stateProcessor.processEnquireLink(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_ENQUIRE_LINK_RESP:
updateActivityTimestamp();
stateProcessor.processEnquireLinkResp(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_SUBMIT_SM_RESP:
updateActivityTimestamp();
stateProcessor.processSubmitSmResp(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_QUERY_SM_RESP:
updateActivityTimestamp();
stateProcessor.processQuerySmResp(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_DELIVER_SM:
updateActivityTimestamp();
stateProcessor.processDeliverSm(pduHeader, pdu, sessionHandler);
break;
case SMPPConstant.CID_UNBIND:
updateActivityTimestamp();
stateProcessor.processUnbind(pduHeader, pdu, sessionHandler);
changeState(SessionState.UNBOUND);
break;
case SMPPConstant.CID_UNBIND_RESP:
updateActivityTimestamp();
stateProcessor.processUnbindResp(pduHeader, pdu, sessionHandler);
break;
default:
stateProcessor.processUnknownCid(pduHeader, pdu, sessionHandler);
}
} catch (InvalidCommandLengthException e) {
logger.warn("Receive invalid command length", e);
// FIXME uud: response to this error, generick nack or close socket
} catch (SocketTimeoutException e) {
addEnquireLinkJob();
//try { Thread.sleep(1); } catch (InterruptedException ee) {}
} catch (IOException e) {
closeSocket();
}
}
@Override
protected void finalize() throws Throwable {
closeSocket();
}
private void fireAcceptDeliverSm(DeliverSm deliverSm) throws ProcessMessageException {
if (messageReceiverListener != null) {
messageReceiverListener.onAcceptDeliverSm(deliverSm);
} else {
logger.warn("Receive deliver_sm but MessageReceiverListener is null. Short message = " + new String(deliverSm.getShortMessage()));
}
}
private void fireChangeState(SessionState newState, SessionState oldState) {
if (sessionStateListener != null) {
sessionStateListener.onStateChange(newState, oldState, this);
} else {
logger.warn("SessionStateListener is null");
}
}
private class SMPPSessionHandlerImpl implements SMPPSessionHandler {
public void processDeliverSm(DeliverSm deliverSm) throws ProcessMessageException {
fireAcceptDeliverSm(deliverSm);
}
@SuppressWarnings("unchecked")
public PendingResponse<Command> removeSentItem(int sequenceNumber) {
return (PendingResponse<Command>)pendingResponse.remove(sequenceNumber);
}
public void sendDeliverSmResp(int sequenceNumber) throws IOException {
try {
pduSender.sendDeliverSmResp(out, sequenceNumber);
// FIXME uud: delete this log
logger.debug("deliver_sm_resp with seq_number " + sequenceNumber + " has been sent");
} catch (PDUStringException e) {
logger.fatal("Failed sending deliver_sm_resp", e);
}
}
public void sendEnquireLinkResp(int sequenceNumber) throws IOException {
pduSender.sendEnquireLinkResp(out, sequenceNumber);
}
public void sendGenerickNack(int commandStatus, int sequenceNumber) throws IOException {
pduSender.sendGenericNack(out, commandStatus, sequenceNumber);
}
public void sendNegativeResponse(int originalCommandId, int commandStatus, int sequenceNumber) throws IOException {
pduSender.sendHeader(out, originalCommandId | SMPPConstant.MASK_CID_RESP, commandStatus, sequenceNumber);
}
public void sendUnbindResp(int sequenceNumber) throws IOException {
pduSender.sendUnbindResp(out, SMPPConstant.STAT_ESME_ROK, sequenceNumber);
}
}
private class PDUReaderWorker extends Thread {
@Override
public void run() {
logger.info("Starting PDUReaderWorker");
while (isReadPdu()) {
readPDU();
}
logger.info("PDUReaderWorker stop");
}
}
private class EnquireLinkSender extends Thread {
@Override
public void run() {
logger.info("Starting EnquireLinkSender");
while (isReadPdu()) {
long sleepTime = 1000;
if (enquireLinkToSend > 0) {
enquireLinkToSend
try {
enquireLink();
} catch (ResponseTimeoutException e) {
closeSocket();
} catch (InvalidResponseException e) {
// lets unbind gracefully
unbindAndClose();
} catch (IOException e) {
closeSocket();
}
}
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
}
}
logger.info("EnquireLinkSender stop");
}
}
private class IdleActivityChecker extends Thread {
@Override
public void run() {
logger.info("Starting IdleActivityChecker");
while (isReadPdu()) {
long timeLeftToEnquire = lastActivityTimestamp + sessionTimer - System.currentTimeMillis();
if (timeLeftToEnquire <= 0) {
try {
enquireLink();
} catch (ResponseTimeoutException e) {
closeSocket();
} catch (InvalidResponseException e) {
// lets unbind gracefully
unbindAndClose();
} catch (IOException e) {
closeSocket();
}
} else {
try {
Thread.sleep(timeLeftToEnquire);
} catch (InterruptedException e) {
}
}
}
logger.info("IdleActivityChecker stop");
}
}
} |
package arez;
import java.util.Collection;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import org.realityforge.guiceyloops.shared.ValueUtil;
import org.testng.annotations.Test;
import static org.testng.Assert.*;
public class MultiPriorityTaskQueueTest
extends AbstractArezTest
{
@Test
public void construct()
{
final MultiPriorityTaskQueue queue = new MultiPriorityTaskQueue( 3, 22 );
assertEquals( queue.getPriorityCount(), 3 );
assertEquals( queue.getBufferByPriority( 0 ).getCapacity(), 22 );
}
@Test
public void queueTask_badPriority()
{
final MultiPriorityTaskQueue queue = new MultiPriorityTaskQueue( 3, 10 );
assertInvariantFailure( () -> queue.queueTask( -1, new Task( "A", ValueUtil::randomString ) ),
"Arez-0215: Attempting to queue task named 'A' but passed an invalid priority -1." );
assertInvariantFailure( () -> queue.queueTask( 77, new Task( "A", ValueUtil::randomString ) ),
"Arez-0215: Attempting to queue task named 'A' but passed an invalid priority 77." );
}
@Test
public void queueTask_alreadyQueued()
{
final MultiPriorityTaskQueue queue = new MultiPriorityTaskQueue( 3, 10 );
final Task task = new Task( "A", ValueUtil::randomString );
queue.queueTask( 0, task );
assertInvariantFailure( () -> queue.queueTask( 1, task ),
"Arez-0099: Attempting to queue task named 'A' when task is already queued." );
}
@Test
public void basicOperation()
{
final MultiPriorityTaskQueue queue = new MultiPriorityTaskQueue( 5, 100 );
assertFalse( queue.hasTasks() );
assertEquals( queue.getQueueSize(), 0 );
assertNull( queue.dequeueTask() );
queue.queueTask( 0, new Task( "A", ValueUtil::randomString ) );
assertEquals( queue.getQueueSize(), 1 );
assertTrue( queue.hasTasks() );
queue.queueTask( 1, new Task( "B", ValueUtil::randomString ) );
assertEquals( queue.getQueueSize(), 2 );
queue.queueTask( 4, new Task( "C", ValueUtil::randomString ) );
assertEquals( queue.getQueueSize(), 3 );
queue.queueTask( 4, new Task( "D", ValueUtil::randomString ) );
assertEquals( queue.getQueueSize(), 4 );
queue.queueTask( 2, new Task( "E", ValueUtil::randomString ) );
assertEquals( queue.getQueueSize(), 5 );
queue.queueTask( 1, new Task( "F", ValueUtil::randomString ) );
assertEquals( queue.getQueueSize(), 6 );
assertEquals( queue.getBufferByPriority( 0 ).size(), 1 );
assertEquals( queue.getBufferByPriority( 1 ).size(), 2 );
assertEquals( queue.getBufferByPriority( 2 ).size(), 1 );
assertEquals( queue.getBufferByPriority( 3 ).size(), 0 );
assertEquals( queue.getBufferByPriority( 4 ).size(), 2 );
assertEquals( getTask( queue, 0, 0 ).getName(), "A" );
assertEquals( getTask( queue, 1, 0 ).getName(), "B" );
assertEquals( getTask( queue, 1, 1 ).getName(), "F" );
assertEquals( getTask( queue, 2, 0 ).getName(), "E" );
assertEquals( getTask( queue, 4, 0 ).getName(), "C" );
assertEquals( getTask( queue, 4, 1 ).getName(), "D" );
assertEquals( queue.getOrderedTasks().map( Task::getName ).collect( Collectors.joining( "," ) ), "A,B,F,E,C,D" );
assertEquals( queue.getQueueSize(), 6 );
assertDequeue( queue, "A" );
assertEquals( queue.getQueueSize(), 5 );
assertDequeue( queue, "B" );
assertEquals( queue.getQueueSize(), 4 );
assertDequeue( queue, "F" );
assertEquals( queue.getQueueSize(), 3 );
assertEquals( queue.getOrderedTasks().map( Task::getName ).collect( Collectors.joining( "," ) ), "E,C,D" );
assertDequeue( queue, "E" );
assertEquals( queue.getQueueSize(), 2 );
assertDequeue( queue, "C" );
assertEquals( queue.getQueueSize(), 1 );
assertTrue( queue.hasTasks() );
assertDequeue( queue, "D" );
assertEquals( queue.getQueueSize(), 0 );
assertFalse( queue.hasTasks() );
assertNull( queue.dequeueTask() );
assertEquals( queue.getQueueSize(), 0 );
}
@Test
public void clear()
{
final MultiPriorityTaskQueue queue = new MultiPriorityTaskQueue( 5, 100 );
queue.queueTask( 0, new Task( "A", ValueUtil::randomString ) );
queue.queueTask( 1, new Task( "B", ValueUtil::randomString ) );
queue.queueTask( 4, new Task( "C", ValueUtil::randomString ) );
queue.queueTask( 4, new Task( "D", ValueUtil::randomString ) );
queue.queueTask( 2, new Task( "E", ValueUtil::randomString ) );
queue.queueTask( 1, new Task( "F", ValueUtil::randomString ) );
assertEquals( queue.getQueueSize(), 6 );
final Collection<Task> tasks = queue.clear();
assertEquals( queue.getQueueSize(), 0 );
assertEquals( tasks.stream().map( Task::getName ).collect( Collectors.joining( "," ) ), "A,B,F,E,C,D" );
}
private void assertDequeue( @Nonnull final MultiPriorityTaskQueue queue, @Nonnull final String name )
{
final Task task = queue.dequeueTask();
assertNotNull( task );
assertEquals( task.getName(), name );
}
@Nonnull
private Task getTask( @Nonnull final MultiPriorityTaskQueue queue, final int priority, final int index )
{
final Task task = queue.getBufferByPriority( priority ).get( index );
assertNotNull( task );
return task;
}
} |
package net.sf.clirr.checks;
import java.util.Comparator;
import java.util.Arrays;
import net.sf.clirr.framework.AbstractDiffReporter;
import net.sf.clirr.framework.ClassChangeCheck;
import net.sf.clirr.framework.ApiDiffDispatcher;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.Type;
/**
* Checks the methods of a class.
*
* @author lkuehne
*/
public class MethodSetCheck
extends AbstractDiffReporter
implements ClassChangeCheck
{
private class MethodComparator implements Comparator
{
public int compare(Object o1, Object o2)
{
Method m1 = (Method) o1;
Method m2 = (Method) o2;
String name1 = m1.getName();
String name2 = m2.getName();
final int nameComparison = name1.compareTo(name2);
// TODO: compare argcount
return nameComparison;
}
}
public MethodSetCheck(ApiDiffDispatcher dispatcher)
{
super(dispatcher);
}
public void check(JavaClass compatBaseline, JavaClass currentVersion)
{
Method[] baselineMethods = sort(compatBaseline.getMethods());
Method[] currentMethods = sort(currentVersion.getMethods());
for (int i = 0; i < baselineMethods.length; i++)
{
Method baselineMethod = baselineMethods[i];
System.out.println("baselineMethod " + i + "= " + getMethodId(compatBaseline, baselineMethod));
}
}
private Method[] sort(Method[] methods)
{
Method[] retval = new Method[methods.length];
// TODO: filter public + protected
// TODO: remove <clinit>
System.arraycopy(methods, 0, retval, 0, methods.length);
Arrays.sort(retval, new MethodComparator());
return retval;
}
private String getMethodId(JavaClass clazz, Method method)
{
if (!method.isPublic() && !method.isProtected())
{
}
StringBuffer buf = new StringBuffer();
buf.append(method.isPublic() ? "public" : "protected");
buf.append(" ");
String name = method.getName();
if ("<init>".equals(name))
{
final String className = clazz.getClassName();
int idx = className.lastIndexOf('.');
name = className.substring(idx + 1);
}
buf.append(name);
buf.append('(');
Type[] argTypes = method.getArgumentTypes();
String argSeparator = "";
for (int i = 0; i < argTypes.length; i++)
{
buf.append(argSeparator);
buf.append(argTypes[i].toString());
argSeparator = ", ";
}
buf.append(')');
return buf.toString();
}
} |
package net.sf.jabref.groups;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import javax.swing.undo.*;
import net.sf.jabref.*;
import net.sf.jabref.search.SearchMatcher;
import net.sf.jabref.undo.NamedCompound;
public class GroupSelector extends SidePaneComponent implements
TreeSelectionListener, ActionListener, ErrorMessageDisplay {
JButton newButton = new JButton(new ImageIcon(GUIGlobals.newSmallIconFile)),
helpButton = new JButton(
new ImageIcon(GUIGlobals.helpSmallIconFile)),
refresh = new JButton(
new ImageIcon(GUIGlobals.refreshSmallIconFile)),
autoGroup = new JButton(new ImageIcon(GUIGlobals.autoGroupIcon)),
openset = new JButton(Globals.lang("Settings"));
Color bgColor = Color.white;
GroupsTree groupsTree;
DefaultTreeModel groupsTreeModel;
GroupTreeNode groupsRoot;
JScrollPane sp;
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints con = new GridBagConstraints();
JabRefFrame frame;
String searchField;
JPopupMenu groupsContextMenu = new JPopupMenu();
JPopupMenu settings = new JPopupMenu();
private JRadioButtonMenuItem hideNonHits, grayOut;
JRadioButtonMenuItem andCb = new JRadioButtonMenuItem(Globals
.lang("Intersection"), true);
JRadioButtonMenuItem orCb = new JRadioButtonMenuItem(Globals.lang("Union"),
false);
JRadioButtonMenuItem floatCb = new JRadioButtonMenuItem(Globals
.lang("Float"), true);
JRadioButtonMenuItem highlCb = new JRadioButtonMenuItem(Globals
.lang("Highlight"), false);
JCheckBoxMenuItem invCb = new JCheckBoxMenuItem(Globals.lang("Inverted"),
false), select = new JCheckBoxMenuItem(Globals
.lang("Select matches"), false);
JCheckBoxMenuItem showOverlappingGroups = new JCheckBoxMenuItem(
Globals.lang("Highlight overlapping groups")); // JZTODO lyrics
ButtonGroup bgr = new ButtonGroup();
ButtonGroup visMode = new ButtonGroup();
ButtonGroup nonHits = new ButtonGroup();
JButton expand = new JButton(new ImageIcon(GUIGlobals.downIconFile)),
reduce = new JButton(new ImageIcon(GUIGlobals.upIconFile));
SidePaneManager manager;
/**
* The first element for each group defines which field to use for the
* quicksearch. The next two define the name and regexp for the group.
*
* @param groupData
* The group meta data in raw format.
*/
public GroupSelector(JabRefFrame frame, SidePaneManager manager) {
super(manager, GUIGlobals.groupsIconFile, Globals.lang("Groups"));
this.groupsRoot = new GroupTreeNode(new AllEntriesGroup());
this.manager = manager;
this.frame = frame;
hideNonHits = new JRadioButtonMenuItem(Globals.lang("Hide non-hits"),
!Globals.prefs.getBoolean("grayOutNonHits"));
grayOut = new JRadioButtonMenuItem(Globals.lang("Gray out non-hits"),
Globals.prefs.getBoolean("grayOutNonHits"));
nonHits.add(hideNonHits);
nonHits.add(grayOut);
floatCb.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
Globals.prefs.putBoolean("groupFloatSelections", floatCb.isSelected());
}
});
andCb.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
Globals.prefs.putBoolean("groupIntersectSelections", andCb
.isSelected());
}
});
invCb.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
Globals.prefs.putBoolean("groupInvertSelections", invCb.isSelected());
}
});
showOverlappingGroups.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
Globals.prefs.putBoolean("groupShowOverlapping",
showOverlappingGroups.isSelected());
if (!showOverlappingGroups.isSelected())
groupsTree.setHighlight2Cells(null);
}
});
select.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
Globals.prefs.putBoolean("groupSelectMatches", select.isSelected());
}
});
grayOut.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent event) {
Globals.prefs.putBoolean("grayOutNonHits", grayOut.isSelected());
}
});
if (Globals.prefs.getBoolean("groupFloatSelections")) {
floatCb.setSelected(true);
highlCb.setSelected(false);
} else {
highlCb.setSelected(true);
floatCb.setSelected(false);
}
if (Globals.prefs.getBoolean("groupIntersectSelections")) {
andCb.setSelected(true);
orCb.setSelected(false);
} else {
orCb.setSelected(true);
andCb.setSelected(false);
}
invCb.setSelected(Globals.prefs.getBoolean("groupInvertSelections"));
showOverlappingGroups.setSelected(Globals.prefs.getBoolean("groupShowOverlapping"));
select.setSelected(Globals.prefs.getBoolean("groupSelectMatches"));
openset.setMargin(new Insets(0, 0, 0, 0));
settings.add(andCb);
settings.add(orCb);
settings.addSeparator();
settings.add(invCb);
settings.addSeparator();
//settings.add(highlCb);
//settings.add(floatCb);
//settings.addSeparator();
settings.add(select);
settings.addSeparator();
settings.add(grayOut);
settings.add(hideNonHits);
settings.addSeparator();
settings.add(showOverlappingGroups);
// settings.add(moreRow);
// settings.add(lessRow);
openset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (settings.isVisible()) {
// System.out.println("oee");
// settings.setVisible(false);
} else {
JButton src = (JButton) e.getSource();
settings.show(src, 0, openset.getHeight());
}
}
});
expand.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Globals.prefs.getInt("groupsVisibleRows") + 1;
groupsTree.setVisibleRowCount(i);
groupsTree.revalidate();
groupsTree.repaint();
GroupSelector.this.revalidate();
GroupSelector.this.repaint();
Globals.prefs.putInt("groupsVisibleRows", i);
}
});
reduce.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Globals.prefs.getInt("groupsVisibleRows") - 1;
if (i < 1)
i = 1;
groupsTree.setVisibleRowCount(i);
groupsTree.revalidate();
groupsTree.repaint();
GroupSelector.this.revalidate();
// _panel.sidePaneManager.revalidate();
GroupSelector.this.repaint();
Globals.prefs.putInt("groupsVisibleRows", i);
}
});
Dimension butDim = new Dimension(20, 20);
Dimension butDim2 = new Dimension(40, 20);
newButton.setPreferredSize(butDim);
newButton.setMinimumSize(butDim);
refresh.setPreferredSize(butDim);
refresh.setMinimumSize(butDim);
helpButton.setPreferredSize(butDim);
helpButton.setMinimumSize(butDim);
autoGroup.setPreferredSize(butDim);
autoGroup.setMinimumSize(butDim);
openset.setPreferredSize(butDim2);
openset.setMinimumSize(butDim2);
expand.setPreferredSize(butDim);
expand.setMinimumSize(butDim);
reduce.setPreferredSize(butDim);
reduce.setMinimumSize(butDim);
Insets butIns = new Insets(0, 0, 0, 0);
helpButton.setMargin(butIns);
reduce.setMargin(butIns);
expand.setMargin(butIns);
openset.setMargin(butIns);
newButton.addActionListener(this);
refresh.addActionListener(this);
andCb.addActionListener(this);
orCb.addActionListener(this);
invCb.addActionListener(this);
showOverlappingGroups.addActionListener(this);
autoGroup.addActionListener(this);
floatCb.addActionListener(this);
highlCb.addActionListener(this);
select.addActionListener(this);
hideNonHits.addActionListener(this);
grayOut.addActionListener(this);
newButton.setToolTipText(Globals.lang("New group"));
refresh.setToolTipText(Globals.lang("Refresh view"));
andCb.setToolTipText(Globals
.lang("Display only entries belonging to all selected"
+ " groups."));
orCb.setToolTipText(Globals
.lang("Display all entries belonging to one or more "
+ "of the selected groups."));
autoGroup.setToolTipText(Globals
.lang("Automatically create groups for database."));
invCb.setToolTipText(Globals
.lang("Show entries *not* in group selection"));
showOverlappingGroups.setToolTipText( // JZTODO lyrics
"Highlight groups that contain entries contained in any currently selected group");
floatCb.setToolTipText(Globals
.lang("Move entries in group selection to the top"));
highlCb.setToolTipText(Globals
.lang("Gray out entries not in group selection"));
select
.setToolTipText(Globals
.lang("Select entries in group selection"));
expand.setToolTipText(Globals.lang("Show one more row"));
reduce.setToolTipText(Globals.lang("Show one less rows"));
bgr.add(andCb);
bgr.add(orCb);
visMode.add(floatCb);
visMode.add(highlCb);
JPanel main = new JPanel();
main.setLayout(gbl);
/*SidePaneHeader header = new SidePaneHeader("Groups",
GUIGlobals.groupsIconFile, this);
con.gridwidth = GridBagConstraints.REMAINDER;
gbl.setConstraints(header, con);
main.add(header);*/
con.fill = GridBagConstraints.BOTH;
//con.insets = new Insets(0, 0, 2, 0);
con.weightx = 1;
con.gridwidth = 1;
//con.insets = new Insets(1, 1, 1, 1);
gbl.setConstraints(newButton, con);
main.add(newButton);
gbl.setConstraints(refresh, con);
main.add(refresh);
gbl.setConstraints(autoGroup, con);
main.add(autoGroup);
con.gridwidth = GridBagConstraints.REMAINDER;
HelpAction helpAction = new HelpAction(frame.helpDiag,
GUIGlobals.groupsHelp, "Help on groups");
helpButton.addActionListener(helpAction);
helpButton.setToolTipText(Globals.lang("Help on groups"));
gbl.setConstraints(helpButton, con);
main.add(helpButton);
// header.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.red));
// helpButton.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.red));
groupsTree = new GroupsTree(this);
groupsTree.addTreeSelectionListener(this);
groupsTree.setModel(groupsTreeModel = new DefaultTreeModel(groupsRoot));
sp = new JScrollPane(groupsTree,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
revalidateGroups();
con.gridwidth = GridBagConstraints.REMAINDER;
con.weighty = 1;
gbl.setConstraints(sp, con);
main.add(sp);
JPanel pan = new JPanel();
GridBagLayout gb = new GridBagLayout();
con.weighty = 0;
gbl.setConstraints(pan, con);
pan.setLayout(gb);
con.weightx = 1;
con.gridwidth = 1;
gb.setConstraints(openset, con);
pan.add(openset);
con.weightx = 0;
gb.setConstraints(expand, con);
pan.add(expand);
con.gridwidth = GridBagConstraints.REMAINDER;
gb.setConstraints(reduce, con);
pan.add(reduce);
main.add(pan);
main.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));
add(main, BorderLayout.CENTER);
definePopup();
moveNodeUpAction.putValue(Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_UP, KeyEvent.CTRL_MASK));
moveNodeDownAction.putValue(Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, KeyEvent.CTRL_MASK));
moveNodeLeftAction.putValue(Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, KeyEvent.CTRL_MASK));
moveNodeRightAction.putValue(Action.ACCELERATOR_KEY,
KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, KeyEvent.CTRL_MASK));
}
private void definePopup() {
// These key bindings are just to have the shortcuts displayed
// in the popup menu. The actual keystroke processing is in
// BasePanel (entryTable.addKeyListener(...)).
groupsContextMenu.add(editGroupPopupAction);
groupsContextMenu.add(addGroupPopupAction);
groupsContextMenu.add(addSubgroupPopupAction);
groupsContextMenu.addSeparator();
groupsContextMenu.add(removeGroupAndSubgroupsPopupAction);
groupsContextMenu.add(removeGroupKeepSubgroupsPopupAction);
groupsContextMenu.add(removeSubgroupsPopupAction);
groupsContextMenu.addSeparator();
groupsContextMenu.add(expandSubtreePopupAction);
groupsContextMenu.add(collapseSubtreePopupAction);
groupsContextMenu.addSeparator();
groupsContextMenu.add(moveSubmenu);
sortSubmenu.add(sortDirectSubgroupsPopupAction);
sortSubmenu.add(sortAllSubgroupsPopupAction);
groupsContextMenu.add(sortSubmenu);
moveSubmenu.add(moveNodeUpPopupAction);
moveSubmenu.add(moveNodeDownPopupAction);
moveSubmenu.add(moveNodeLeftPopupAction);
moveSubmenu.add(moveNodeRightPopupAction);
groupsContextMenu.addSeparator();
groupsContextMenu.add(addToGroup);
groupsContextMenu.add(moveToGroup);
groupsContextMenu.add(removeFromGroup);
groupsTree.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger())
showPopup(e);
}
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger())
showPopup(e);
}
public void mouseClicked(MouseEvent e) {
TreePath path = groupsTree.getPathForLocation(e.getPoint().x, e
.getPoint().y);
if (path == null)
return;
GroupTreeNode node = (GroupTreeNode) path
.getLastPathComponent();
// the root node is "AllEntries" and cannot be edited
if (node.isRoot())
return;
if (e.getClickCount() == 2
&& e.getButton() == MouseEvent.BUTTON1) { // edit
editGroupAction.actionPerformed(null); // dummy event
}
}
});
// be sure to remove a possible border highlight when the popup menu
// disappears
groupsContextMenu.addPopupMenuListener(new PopupMenuListener() {
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
// nothing to do
}
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
groupsTree.setHighlightBorderCell(null);
}
public void popupMenuCanceled(PopupMenuEvent e) {
groupsTree.setHighlightBorderCell(null);
}
});
}
private void showPopup(MouseEvent e) {
final TreePath path = groupsTree.getPathForLocation(e.getPoint().x, e
.getPoint().y);
addGroupPopupAction.setEnabled(true);
addSubgroupPopupAction.setEnabled(path != null);
editGroupPopupAction.setEnabled(path != null);
removeGroupAndSubgroupsPopupAction.setEnabled(path != null);
removeGroupKeepSubgroupsPopupAction.setEnabled(path != null);
moveSubmenu.setEnabled(path != null);
expandSubtreePopupAction.setEnabled(path != null);
collapseSubtreePopupAction.setEnabled(path != null);
removeSubgroupsPopupAction.setEnabled(path != null);
sortSubmenu.setEnabled(path != null);
addToGroup.setEnabled(false);
moveToGroup.setEnabled(false);
removeFromGroup.setEnabled(false);
if (path != null) { // some path dependent enabling/disabling
GroupTreeNode node = (GroupTreeNode) path.getLastPathComponent();
editGroupPopupAction.setNode(node);
addSubgroupPopupAction.setNode(node);
removeGroupAndSubgroupsPopupAction.setNode(node);
removeSubgroupsPopupAction.setNode(node);
removeGroupKeepSubgroupsPopupAction.setNode(node);
expandSubtreePopupAction.setNode(node);
collapseSubtreePopupAction.setNode(node);
sortDirectSubgroupsPopupAction.setNode(node);
sortAllSubgroupsPopupAction.setNode(node);
groupsTree.setHighlightBorderCell(node);
AbstractGroup group = node.getGroup();
if (group instanceof AllEntriesGroup) {
editGroupPopupAction.setEnabled(false);
addGroupPopupAction.setEnabled(false);
removeGroupAndSubgroupsPopupAction.setEnabled(false);
removeGroupKeepSubgroupsPopupAction.setEnabled(false);
} else {
editGroupPopupAction.setEnabled(true);
addGroupPopupAction.setEnabled(true);
addGroupPopupAction.setNode(node);
removeGroupAndSubgroupsPopupAction.setEnabled(true);
removeGroupKeepSubgroupsPopupAction.setEnabled(true);
}
expandSubtreePopupAction.setEnabled(groupsTree.isCollapsed(path) ||
groupsTree.hasCollapsedDescendant(path));
collapseSubtreePopupAction.setEnabled(groupsTree.isExpanded(path) ||
groupsTree.hasExpandedDescendant(path));
sortSubmenu.setEnabled(!node.isLeaf());
removeSubgroupsPopupAction.setEnabled(!node.isLeaf());
moveNodeUpPopupAction.setEnabled(node.canMoveUp());
moveNodeDownPopupAction.setEnabled(node.canMoveDown());
moveNodeLeftPopupAction.setEnabled(node.canMoveLeft());
moveNodeRightPopupAction.setEnabled(node.canMoveRight());
moveSubmenu.setEnabled(moveNodeUpPopupAction.isEnabled()
|| moveNodeDownPopupAction.isEnabled()
|| moveNodeLeftPopupAction.isEnabled()
|| moveNodeRightPopupAction.isEnabled());
moveNodeUpPopupAction.setNode(node);
moveNodeDownPopupAction.setNode(node);
moveNodeLeftPopupAction.setNode(node);
moveNodeRightPopupAction.setNode(node);
// add/remove entries to/from group
BibtexEntry[] selection = frame.basePanel().getSelectedEntries();
if (selection.length > 0) {
if (node.getGroup().supportsAdd() && !node.getGroup().
containsAll(selection)) {
addToGroup.setNode(node);
addToGroup.setBasePanel(panel);
addToGroup.setEnabled(true);
moveToGroup.setNode(node);
moveToGroup.setBasePanel(panel);
moveToGroup.setEnabled(true);
}
if (node.getGroup().supportsRemove() && node.getGroup().
containsAny(selection)) {
removeFromGroup.setNode(node);
removeFromGroup.setBasePanel(panel);
removeFromGroup.setEnabled(true);
}
}
} else {
editGroupPopupAction.setNode(null);
addGroupPopupAction.setNode(null);
addSubgroupPopupAction.setNode(null);
removeGroupAndSubgroupsPopupAction.setNode(null);
removeSubgroupsPopupAction.setNode(null);
removeGroupKeepSubgroupsPopupAction.setNode(null);
moveNodeUpPopupAction.setNode(null);
moveNodeDownPopupAction.setNode(null);
moveNodeLeftPopupAction.setNode(null);
moveNodeRightPopupAction.setNode(null);
expandSubtreePopupAction.setNode(null);
collapseSubtreePopupAction.setNode(null);
sortDirectSubgroupsPopupAction.setNode(null);
sortAllSubgroupsPopupAction.setNode(null);
}
groupsContextMenu.show(groupsTree, e.getPoint().x, e.getPoint().y);
}
public void valueChanged(TreeSelectionEvent e) {
if (panel == null) // sorry, we're closed!
return; // ignore this event
final TreePath[] selection = groupsTree.getSelectionPaths();
if (selection == null
|| selection.length == 0
|| (selection.length == 1 && ((GroupTreeNode) selection[0]
.getLastPathComponent()).getGroup() instanceof AllEntriesGroup)) {
panel.stopShowingGroup();
panel.mainTable.stopShowingFloatGrouping();
if (showOverlappingGroups.isSelected())
groupsTree.setHighlight2Cells(null);
frame.output(Globals.lang("Displaying no groups") + ".");
return;
}
final AndOrSearchRuleSet searchRules = new AndOrSearchRuleSet(andCb
.isSelected(), invCb.isSelected());
for (int i = 0; i < selection.length; ++i) {
searchRules.addRule(((GroupTreeNode) selection[i]
.getLastPathComponent()).getSearchRule());
}
Hashtable searchOptions = new Hashtable();
searchOptions.put("option", "dummy");
GroupingWorker worker = new GroupingWorker(searchRules, searchOptions);
worker.getWorker().run();
worker.getCallBack().update();
/*panel.setGroupMatcher(new SearchMatcher(searchRules, searchOptions));
DatabaseSearch search = new DatabaseSearch(this, searchOptions, searchRules,
panel, Globals.GROUPSEARCH, floatCb.isSelected(), Globals.prefs
.getBoolean("grayOutNonHits"),
//true,
select.isSelected());
search.start();*/
}
class GroupingWorker extends AbstractWorker {
private SearchRuleSet rules;
private Hashtable searchTerm;
private ArrayList matches = new ArrayList();
private boolean showOverlappingGroupsP;
int hits = 0;
public GroupingWorker(SearchRuleSet rules, Hashtable searchTerm) {
this.rules = rules;
this.searchTerm = searchTerm;
showOverlappingGroupsP = showOverlappingGroups.isSelected();
}
public void run() {
Collection entries = panel.getDatabase().getEntries();
for (Iterator i = entries.iterator(); i.hasNext();) {
BibtexEntry entry = (BibtexEntry) i.next();
boolean hit = rules.applyRule(searchTerm, entry) > 0;
entry.setGroupHit(hit);
if (hit) {
hits++;
if (showOverlappingGroupsP)
matches.add(entry);
}
}
}
public void update() {
// Show the result in the chosen way:
if (hideNonHits.isSelected()) {
panel.mainTable.stopShowingFloatGrouping(); // Turn off shading, if active.
panel.setGroupMatcher(GroupMatcher.INSTANCE); // Turn on filtering.
}
else if (grayOut.isSelected()) {
panel.stopShowingGroup(); // Turn off filtering, if active.
panel.mainTable.showFloatGrouping(GroupMatcher.INSTANCE); // Turn on shading.
}
if (showOverlappingGroupsP) {
showOverlappingGroups(matches);
}
frame.output(Globals.lang("Updated group selection") + ".");
}
}
/**
* Revalidate the groups tree (e.g. after the data stored in the model has
* been changed) and set the specified selection and expansion state.
* @param node If this is non-null, the view is scrolled to make it visible.
*/
public void revalidateGroups(TreePath[] selectionPaths,
Enumeration expandedNodes) {
revalidateGroups(selectionPaths, expandedNodes, null);
}
/**
* Revalidate the groups tree (e.g. after the data stored in the model has
* been changed) and set the specified selection and expansion state.
* @param node If this is non-null, the view is scrolled to make it visible.
*/
public void revalidateGroups(TreePath[] selectionPaths,
Enumeration expandedNodes, GroupTreeNode node) {
groupsTreeModel.reload();
groupsTree.clearSelection();
if (selectionPaths != null) {
groupsTree.setSelectionPaths(selectionPaths);
}
// tree is completely collapsed here
if (expandedNodes != null) {
while (expandedNodes.hasMoreElements())
groupsTree.expandPath((TreePath)expandedNodes.nextElement());
}
groupsTree.revalidate();
if (node != null) {
groupsTree.scrollPathToVisible(new TreePath(node.getPath()));
}
}
/**
* Revalidate the groups tree (e.g. after the data stored in the model has
* been changed) and maintain the current selection and expansion state. */
public void revalidateGroups() {
revalidateGroups(null);
}
/**
* Revalidate the groups tree (e.g. after the data stored in the model has
* been changed) and maintain the current selection and expansion state.
* @param node If this is non-null, the view is scrolled to make it visible.
*/
public void revalidateGroups(GroupTreeNode node) {
revalidateGroups(groupsTree.getSelectionPaths(),getExpandedPaths(),node);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == refresh) {
valueChanged(null);
} else if (e.getSource() == newButton) {
GroupDialog gd = new GroupDialog(frame, panel, null);
gd.show();
if (gd.okPressed()) {
AbstractGroup newGroup = gd.getResultingGroup();
GroupTreeNode newNode = new GroupTreeNode(newGroup);
groupsRoot.add(newNode);
revalidateGroups();
UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(
GroupSelector.this, groupsRoot, newNode,
UndoableAddOrRemoveGroup.ADD_NODE);
panel.undoManager.addEdit(undo);
panel.markBaseChanged();
frame.output(Globals.lang("Created_group_\"%0\".",
newGroup.getName()));
}
} else if (e.getSource() == autoGroup) {
AutoGroupDialog gd = new AutoGroupDialog(frame, panel,
GroupSelector.this, groupsRoot, Globals.prefs
.get("groupsDefaultField"), " .,", ",");
gd.show();
// gd does the operation itself
} else if (e.getSource() instanceof JCheckBox) {
valueChanged(null);
} else if (e.getSource() instanceof JCheckBoxMenuItem) {
valueChanged(null);
} else if (e.getSource() instanceof JRadioButtonMenuItem) {
valueChanged(null);
}
}
public void componentOpening() {
valueChanged(null);
}
public void componentClosing() {
if (panel != null) {// panel may be null if no file is open any more
panel.stopShowingGroup();
panel.mainTable.stopShowingFloatGrouping();
}
frame.groupToggle.setSelected(false);
}
public void setGroups(GroupTreeNode groupsRoot) {
groupsTree.setModel(groupsTreeModel = new DefaultTreeModel(groupsRoot));
this.groupsRoot = groupsRoot;
if (Globals.prefs.getBoolean("groupExpandTree"))
groupsTree.expandSubtree(groupsRoot);
}
/**
* Adds the specified node as a child of the current root. The group
* contained in <b>newGroups </b> must not be of type AllEntriesGroup, since
* every tree has exactly one AllEntriesGroup (its root). The <b>newGroups
* </b> are inserted directly, i.e. they are not deepCopy()'d.
*/
public void addGroups(GroupTreeNode newGroups, CompoundEdit ce) {
// paranoia: ensure that there are never two instances of AllEntriesGroup
if (newGroups.getGroup() instanceof AllEntriesGroup)
return; // this should be impossible anyway
groupsRoot.add(newGroups);
UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(this,
groupsRoot, newGroups, UndoableAddOrRemoveGroup.ADD_NODE);
ce.addEdit(undo);
}
private abstract class NodeAction extends AbstractAction {
protected GroupTreeNode m_node = null;
public NodeAction(String s) {
super(s);
}
public GroupTreeNode getNode() {
return m_node;
}
public void setNode(GroupTreeNode node) {
this.m_node = node;
}
/** Returns the node to use in this action. If a node has been
* set explicitly (via setNode), it is returned. Otherwise, the first
* node in the current selection is returned. If all this fails, null
* is returned. */
public GroupTreeNode getNodeToUse() {
if (m_node != null)
return m_node;
TreePath path = groupsTree.getSelectionPath();
if (path != null)
return (GroupTreeNode) path.getLastPathComponent();
return null;
}
}
final AbstractAction editGroupAction = new EditGroupAction();
final NodeAction editGroupPopupAction = new EditGroupAction();
final NodeAction addGroupPopupAction = new AddGroupAction();
final NodeAction addSubgroupPopupAction = new AddSubgroupAction();
final NodeAction removeGroupAndSubgroupsPopupAction = new RemoveGroupAndSubgroupsAction();
final NodeAction removeSubgroupsPopupAction = new RemoveSubgroupsAction();
final NodeAction removeGroupKeepSubgroupsPopupAction = new RemoveGroupKeepSubgroupsAction();
final NodeAction moveNodeUpPopupAction = new MoveNodeUpAction();
final NodeAction moveNodeDownPopupAction = new MoveNodeDownAction();
final NodeAction moveNodeLeftPopupAction = new MoveNodeLeftAction();
final NodeAction moveNodeRightPopupAction = new MoveNodeRightAction();
final NodeAction moveNodeUpAction = new MoveNodeUpAction();
final NodeAction moveNodeDownAction = new MoveNodeDownAction();
final NodeAction moveNodeLeftAction = new MoveNodeLeftAction();
final NodeAction moveNodeRightAction = new MoveNodeRightAction();
final NodeAction expandSubtreePopupAction = new ExpandSubtreeAction();
final NodeAction collapseSubtreePopupAction = new CollapseSubtreeAction();
final NodeAction sortDirectSubgroupsPopupAction = new SortDirectSubgroupsAction();
final NodeAction sortAllSubgroupsPopupAction = new SortAllSubgroupsAction();
final AddToGroupAction addToGroup = new AddToGroupAction(false);
final AddToGroupAction moveToGroup = new AddToGroupAction(true);
final RemoveFromGroupAction removeFromGroup = new RemoveFromGroupAction();
private class EditGroupAction extends NodeAction {
public EditGroupAction() {
super(Globals.lang("Edit group"));
}
public void actionPerformed(ActionEvent e) {
final GroupTreeNode node = getNodeToUse();
final AbstractGroup oldGroup = node.getGroup();
final GroupDialog gd = new GroupDialog(frame, panel, oldGroup);
gd.setVisible(true);
if (gd.okPressed()) {
AbstractGroup newGroup = gd.getResultingGroup();
AbstractUndoableEdit undoAddPreviousEntries
= gd.getUndoForAddPreviousEntries();
UndoableModifyGroup undo = new UndoableModifyGroup(
GroupSelector.this, groupsRoot, node, newGroup);
node.setGroup(newGroup);
revalidateGroups(node);
// Store undo information.
if (undoAddPreviousEntries == null) {
panel.undoManager.addEdit(undo);
} else {
NamedCompound nc = new NamedCompound("Modify Group"); // JZTODO lyrics
nc.addEdit(undo);
nc.addEdit(undoAddPreviousEntries);
nc.end();
panel.undoManager.addEdit(nc);
}
panel.markBaseChanged();
frame.output(Globals.lang("Modified group \"%0\".",
newGroup.getName()));
}
}
}
private class AddGroupAction extends NodeAction {
public AddGroupAction() {
super(Globals.lang("Add Group"));
}
public void actionPerformed(ActionEvent e) {
final GroupTreeNode node = getNodeToUse();
final GroupDialog gd = new GroupDialog(frame, panel, null);
gd.setVisible(true);
if (!gd.okPressed())
return; // ignore
final AbstractGroup newGroup = gd.getResultingGroup();
final GroupTreeNode newNode = new GroupTreeNode(newGroup);
if (node == null)
groupsRoot.add(newNode);
else
((GroupTreeNode) node.getParent()).insert(newNode, node
.getParent().getIndex(node) + 1);
UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(
GroupSelector.this, groupsRoot, newNode,
UndoableAddOrRemoveGroup.ADD_NODE);
revalidateGroups();
groupsTree.expandPath(new TreePath(
(node != null ? node : groupsRoot).getPath()));
// Store undo information.
panel.undoManager.addEdit(undo);
panel.markBaseChanged();
frame.output(Globals.lang("Added group \"%0\".",
newGroup.getName()));
}
}
private class AddSubgroupAction extends NodeAction {
public AddSubgroupAction() {
super(Globals.lang("Add Subgroup"));
}
public void actionPerformed(ActionEvent e) {
final GroupTreeNode node = getNodeToUse();
final GroupDialog gd = new GroupDialog(frame, panel, null);
gd.setVisible(true);
if (!gd.okPressed())
return; // ignore
final AbstractGroup newGroup = gd.getResultingGroup();
final GroupTreeNode newNode = new GroupTreeNode(newGroup);
node.add(newNode);
UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(
GroupSelector.this, groupsRoot, newNode,
UndoableAddOrRemoveGroup.ADD_NODE);
revalidateGroups();
groupsTree.expandPath(new TreePath(node.getPath()));
// Store undo information.
panel.undoManager.addEdit(undo);
panel.markBaseChanged();
frame.output(Globals.lang("Added group \"%0\".",
newGroup.getName()));
}
}
private class RemoveGroupAndSubgroupsAction extends NodeAction {
public RemoveGroupAndSubgroupsAction() {
super(Globals.lang("Remove group and subgroups"));
}
public void actionPerformed(ActionEvent e) {
final GroupTreeNode node = getNodeToUse();
final AbstractGroup group = node.getGroup();
int conf = JOptionPane.showConfirmDialog(frame, Globals
.lang("Remove group \"%0\" and its subgroups?",group.getName()),
Globals.lang("Remove group and subgroups"),
JOptionPane.YES_NO_OPTION);
if (conf == JOptionPane.YES_OPTION) {
final UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(
GroupSelector.this, groupsRoot, node,
UndoableAddOrRemoveGroup.REMOVE_NODE_AND_CHILDREN);
node.removeFromParent();
revalidateGroups();
// Store undo information.
panel.undoManager.addEdit(undo);
panel.markBaseChanged();
frame.output(Globals.lang("Removed group \"%0\" and its subgroups.",
group.getName()));
}
}
};
private class RemoveSubgroupsAction extends NodeAction {
public RemoveSubgroupsAction() {
super(Globals.lang("Remove all subgroups"));
}
public void actionPerformed(ActionEvent e) {
final GroupTreeNode node = getNodeToUse();
final AbstractGroup group = node.getGroup();
int conf = JOptionPane.showConfirmDialog(frame, Globals
.lang("Remove all subgroups of \"%0\"?",group.getName()),
Globals.lang("Remove all subgroups"),
JOptionPane.YES_NO_OPTION);
if (conf == JOptionPane.YES_OPTION) {
final UndoableModifySubtree undo = new UndoableModifySubtree(
GroupSelector.this, node,
"Remove all subgroups");
node.removeAllChildren();
revalidateGroups();
// Store undo information.
panel.undoManager.addEdit(undo);
panel.markBaseChanged();
frame.output(Globals.lang("Removed all subgroups of group \"%0\".",
group.getName()));
}
}
};
private class RemoveGroupKeepSubgroupsAction extends NodeAction {
public RemoveGroupKeepSubgroupsAction() {
super(Globals.lang("Remove group, keep subgroups"));
}
public void actionPerformed(ActionEvent e) {
final GroupTreeNode node = getNodeToUse();
final AbstractGroup group = node.getGroup();
int conf = JOptionPane.showConfirmDialog(frame, Globals
.lang("Remove group \"%0\"?", group.getName()), Globals
.lang("Remove group"), JOptionPane.YES_NO_OPTION);
if (conf == JOptionPane.YES_OPTION) {
final UndoableAddOrRemoveGroup undo = new UndoableAddOrRemoveGroup(
GroupSelector.this, groupsRoot, node,
UndoableAddOrRemoveGroup.REMOVE_NODE_KEEP_CHILDREN);
final GroupTreeNode parent = (GroupTreeNode) node.getParent();
final int childIndex = parent.getIndex(node);
node.removeFromParent();
while (node.getChildCount() > 0)
parent.insert((GroupTreeNode) node.getFirstChild(),
childIndex);
revalidateGroups();
// Store undo information.
panel.undoManager.addEdit(undo);
panel.markBaseChanged();
frame.output(Globals.lang("Removed group \"%0\".",
group.getName()));
}
}
};
public TreePath getSelectionPath() {
return groupsTree.getSelectionPath();
}
private class SortDirectSubgroupsAction extends NodeAction {
public SortDirectSubgroupsAction() {
super(Globals.lang("Immediate subgroups"));
}
public void actionPerformed(ActionEvent ae) {
final GroupTreeNode node = getNodeToUse();
final UndoableModifySubtree undo = new UndoableModifySubtree(
GroupSelector.this, node, Globals.lang("sort subgroups"));
groupsTree.sort(node, false);
panel.undoManager.addEdit(undo);
panel.markBaseChanged();
frame.output(Globals.lang("Sorted immediate subgroups."));
}
}
private class SortAllSubgroupsAction extends NodeAction {
public SortAllSubgroupsAction() {
super(Globals.lang("All subgroups (recursively)"));
}
public void actionPerformed(ActionEvent ae) {
final GroupTreeNode node = getNodeToUse();
final UndoableModifySubtree undo = new UndoableModifySubtree(
GroupSelector.this, node, Globals.lang("sort subgroups"));
groupsTree.sort(node, true);
panel.undoManager.addEdit(undo);
panel.markBaseChanged(); // JZTODO lyrics
frame.output(Globals.lang("Sorted all subgroups recursively."));
}
};
public final AbstractAction clearHighlightAction = new AbstractAction(Globals.lang("Clear highlight")) {
public void actionPerformed(ActionEvent ae) {
groupsTree.setHighlight3Cells(null);
}
};
private class ExpandSubtreeAction extends NodeAction {
public ExpandSubtreeAction() {
super(Globals.lang("Expand subtree"));
}
public void actionPerformed(ActionEvent ae) {
final GroupTreeNode node = getNodeToUse();
TreePath path = new TreePath(node.getPath());
groupsTree.expandSubtree((GroupTreeNode) path.getLastPathComponent());
revalidateGroups();
}
}
private class CollapseSubtreeAction extends NodeAction {
public CollapseSubtreeAction() {
super(Globals.lang("Collapse subtree"));
}
public void actionPerformed(ActionEvent ae) {
final GroupTreeNode node = getNodeToUse();
TreePath path = new TreePath(node.getPath());
groupsTree.collapseSubtree((GroupTreeNode) path.getLastPathComponent());
revalidateGroups();
}
}
private class MoveNodeUpAction extends NodeAction {
public MoveNodeUpAction() {
super(Globals.lang("Up"));
}
public void actionPerformed(ActionEvent e) {
final GroupTreeNode node = getNodeToUse();
moveNodeUp(node, false);
}
}
private class MoveNodeDownAction extends NodeAction {
public MoveNodeDownAction() {
super(Globals.lang("Down"));
}
public void actionPerformed(ActionEvent e) {
final GroupTreeNode node = getNodeToUse();
moveNodeDown(node, false);
}
}
private class MoveNodeLeftAction extends NodeAction {
public MoveNodeLeftAction() {
super(Globals.lang("Left"));
}
public void actionPerformed(ActionEvent e) {
final GroupTreeNode node = getNodeToUse();
moveNodeLeft(node, false);
}
}
private class MoveNodeRightAction extends NodeAction {
public MoveNodeRightAction() {
super(Globals.lang("Right"));
}
public void actionPerformed(ActionEvent e) {
final GroupTreeNode node = getNodeToUse();
moveNodeRight(node, false);
}
}
/**
* @param node The node to move
* @return true if move was successful, false if not.
*/
public boolean moveNodeUp(GroupTreeNode node, boolean checkSingleSelection) {
if (checkSingleSelection) {
if (groupsTree.getSelectionCount() != 1) {
frame.output(Globals.lang("Please select exactly one group to move."));
return false; // not possible
}
}
AbstractUndoableEdit undo = null;
if (!node.canMoveUp() || (undo = node.moveUp(GroupSelector.this)) == null) {
frame.output(Globals.lang(
"Cannot move group \"%0\" up.", node.getGroup().getName()));
return false; // not possible
}
// update selection/expansion state (not really needed when
// moving among siblings, but I'm paranoid)
revalidateGroups(groupsTree.refreshPaths(groupsTree.getSelectionPaths()),
groupsTree.refreshPaths(getExpandedPaths()));
concludeMoveGroup(undo, node);
return true;
}
/**
* @param node The node to move
* @return true if move was successful, false if not.
*/
public boolean moveNodeDown(GroupTreeNode node, boolean checkSingleSelection) {
if (checkSingleSelection) {
if (groupsTree.getSelectionCount() != 1) {
frame.output(Globals.lang("Please select exactly one group to move."));
return false; // not possible
}
}
AbstractUndoableEdit undo = null;
if (!node.canMoveDown() || (undo = node.moveDown(GroupSelector.this)) == null) {
frame.output(Globals.lang(
"Cannot move group \"%0\" down.", node.getGroup().getName()));
return false; // not possible
}
// update selection/expansion state (not really needed when
// moving among siblings, but I'm paranoid)
revalidateGroups(groupsTree.refreshPaths(groupsTree.getSelectionPaths()),
groupsTree.refreshPaths(getExpandedPaths()));
concludeMoveGroup(undo, node);
return true;
}
/**
* @param node The node to move
* @return true if move was successful, false if not.
*/
public boolean moveNodeLeft(GroupTreeNode node, boolean checkSingleSelection) {
if (checkSingleSelection) {
if (groupsTree.getSelectionCount() != 1) {
frame.output(Globals.lang("Please select exactly one group to move."));
return false; // not possible
}
}
AbstractUndoableEdit undo = null;
if (!node.canMoveLeft() || (undo = node.moveLeft(GroupSelector.this)) == null) {
frame.output(Globals.lang(
"Cannot move group \"%0\" left.", node.getGroup().getName()));
return false; // not possible
}
// update selection/expansion state
revalidateGroups(groupsTree.refreshPaths(groupsTree.getSelectionPaths()),
groupsTree.refreshPaths(getExpandedPaths()));
concludeMoveGroup(undo, node);
return true;
}
/**
* @param node The node to move
* @return true if move was successful, false if not.
*/
public boolean moveNodeRight(GroupTreeNode node, boolean checkSingleSelection) {
if (checkSingleSelection) {
if (groupsTree.getSelectionCount() != 1) {
frame.output(Globals.lang("Please select exactly one group to move."));
return false; // not possible
}
}
AbstractUndoableEdit undo = null;
if (!node.canMoveRight() || (undo = node.moveRight(GroupSelector.this)) == null) {
frame.output(Globals.lang(
"Cannot move group \"%0\" right.", node.getGroup().getName()));
return false; // not possible
}
// update selection/expansion state
revalidateGroups(groupsTree.refreshPaths(groupsTree.getSelectionPaths()),
groupsTree.refreshPaths(getExpandedPaths()));
concludeMoveGroup(undo, node);
return true;
}
/**
* Concludes the moving of a group tree node by storing the specified
* undo information, marking the change, and setting the status line.
* @param undo Undo information for the move operation.
* @param node The node that has been moved.
*/
public void concludeMoveGroup(AbstractUndoableEdit undo, GroupTreeNode node) {
panel.undoManager.addEdit(undo);
panel.markBaseChanged();
frame.output(Globals.lang("Moved group \"%0\".",
node.getGroup().getName()));
}
public void concludeAssignment(AbstractUndoableEdit undo, GroupTreeNode node, int assignedEntries) {
if (undo == null) {
frame.output(Globals.lang("The group \"%0\" already contains the selection.",
new String[]{node.getGroup().getName()}));
return;
}
panel.undoManager.addEdit(undo);
panel.markBaseChanged();
panel.updateEntryEditorIfShowing();
final String groupName = node.getGroup().getName();
if (assignedEntries == 1)
frame.output(Globals.lang("Assigned 1 entry to group \"%0\".", groupName));
else
frame.output(Globals.lang("Assigned %0 entries to group \"%1\".",
String.valueOf(assignedEntries), groupName));
}
JMenu moveSubmenu = new JMenu(Globals.lang("Move"));
JMenu sortSubmenu = new JMenu(Globals.lang("Sort alphabetically")); // JZTODO lyrics
public GroupTreeNode getGroupTreeRoot() {
return groupsRoot;
}
public Enumeration getExpandedPaths() {
return groupsTree.getExpandedDescendants(
new TreePath(groupsRoot.getPath()));
}
/** panel may be null to indicate that no file is currently open. */
public void setActiveBasePanel(BasePanel panel) {
super.setActiveBasePanel(panel);
if (panel == null) { // hide groups
frame.sidePaneManager.ensureNotVisible("groups");
return;
}
MetaData metaData = panel.metaData();
if (metaData.getGroups() != null) {
setGroups(metaData.getGroups());
} else {
GroupTreeNode newGroupsRoot = new GroupTreeNode(new AllEntriesGroup());
metaData.setGroups(newGroupsRoot);
setGroups(newGroupsRoot);
}
// auto show/hide groups interface
if (Globals.prefs.getBoolean("groupAutoShow") &&
!groupsRoot.isLeaf()) { // groups were defined
frame.sidePaneManager.ensureVisible("groups");
frame.groupToggle.setSelected(true);
} else if (Globals.prefs.getBoolean("groupAutoHide") &&
groupsRoot.isLeaf()) { // groups were not defined
frame.sidePaneManager.ensureNotVisible("groups");
frame.groupToggle.setSelected(false);
}
validateTree();
}
/**
* This method is required by the ErrorMessageDisplay interface, and lets this class
* serve as a callback for regular expression exceptions happening in DatabaseSearch.
* @param errorMessage
*/
public void reportError(String errorMessage) {
// this should never happen, since regular expressions are checked for
// correctness by the edit group dialog, and no other errors should
// occur in a search
System.err.println("Error in group search: "+errorMessage
+ ". Please report this on www.sf.net/projects/jabref");
}
/**
* This method is required by the ErrorMessageDisplay interface, and lets this class
* serve as a callback for regular expression exceptions happening in DatabaseSearch.
* @param errorMessage
*/
public void reportError(String errorMessage, Exception exception) {
reportError(errorMessage);
}
/**
* Highlight all groups that contain any/all of the specified entries.
* If entries is null or has zero length, highlight is cleared.
*/
public void showMatchingGroups(BibtexEntry[] entries, boolean requireAll) {
if (entries == null || entries.length == 0) { // nothing selected
groupsTree.setHighlight3Cells(null);
groupsTree.revalidate();
return;
}
GroupTreeNode node;
AbstractGroup group;
Vector vec = new Vector();
for (Enumeration e = groupsRoot.preorderEnumeration(); e.hasMoreElements(); ) {
node = (GroupTreeNode) e.nextElement();
group = node.getGroup();
int i;
for (i = 0; i < entries.length; ++i) {
if (requireAll) {
if (!group.contains(entries[i]))
break;
} else {
if (group.contains(entries[i]))
vec.add(node);
}
}
if (requireAll && i >= entries.length) // did not break from loop
vec.add(node);
}
groupsTree.setHighlight3Cells(vec.toArray());
// ensure that all highlighted nodes are visible
for (int i = 0; i < vec.size(); ++i) {
node = (GroupTreeNode)((GroupTreeNode)vec.elementAt(i)).getParent();
if (node != null)
groupsTree.expandPath(new TreePath(node.getPath()));
}
groupsTree.revalidate();
}
/** Show groups that, if selected, would show at least one
* of the entries found in the specified search. */
protected void showOverlappingGroups(List matches) { //DatabaseSearch search) {
GroupTreeNode node;
SearchRule rule;
BibtexEntry entry;
Vector vec = new Vector();
Map dummyMap = new HashMap(); // just because I don't want to use null...
for (Enumeration e = groupsRoot.depthFirstEnumeration(); e.hasMoreElements(); ) {
node = (GroupTreeNode) e.nextElement();
rule = node.getSearchRule();
for (Iterator it = matches.iterator(); it.hasNext(); ) {
entry = (BibtexEntry) it.next();
if (rule.applyRule(dummyMap, entry) == 0)
continue;
vec.add(node);
break;
}
}
groupsTree.setHighlight2Cells(vec.toArray());
}
} |
package org.jetbrains.ether.dependencyView;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import org.jetbrains.annotations.Nullable;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.Opcodes;
import java.io.File;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.RetentionPolicy;
import java.util.*;
public class Mappings {
private final static String classToSubclassesName = "classToSubclasses.tab";
private final static String classToClassName = "classToClass.tab";
private final static String sourceToClassName = "sourceToClass.tab";
private final static String sourceToAnnotationsName = "sourceToAnnotations.tab";
private final static String sourceToUsagesName = "sourceToUsages.tab";
private final static String classToSourceName = "classToSource.tab";
private final File myRootDir;
private DependencyContext myContext;
private MultiMaplet<DependencyContext.S, DependencyContext.S> myClassToSubclasses;
private MultiMaplet<DependencyContext.S, DependencyContext.S> myClassToClassDependency;
private MultiMaplet<DependencyContext.S, ClassRepr> mySourceFileToClasses;
private MultiMaplet<DependencyContext.S, UsageRepr.Usage> mySourceFileToAnnotationUsages;
private Maplet<DependencyContext.S, UsageRepr.Cluster> mySourceFileToUsages;
private Maplet<DependencyContext.S, DependencyContext.S> myClassToSourceFile;
private static final TransientMultiMaplet.CollectionConstructor<ClassRepr> ourClassSetConstructor =
new TransientMultiMaplet.CollectionConstructor<ClassRepr>() {
public Set<ClassRepr> create() {
return new HashSet<ClassRepr>();
}
};
private static final TransientMultiMaplet.CollectionConstructor<UsageRepr.Usage> ourUsageSetConstructor =
new TransientMultiMaplet.CollectionConstructor<UsageRepr.Usage>() {
public Set<UsageRepr.Usage> create() {
return new HashSet<UsageRepr.Usage>();
}
};
private static final TransientMultiMaplet.CollectionConstructor<DependencyContext.S> ourStringSetConstructor =
new TransientMultiMaplet.CollectionConstructor<DependencyContext.S>() {
public Set<DependencyContext.S> create() {
return new HashSet<DependencyContext.S>();
}
};
private Mappings(final DependencyContext context) {
myRootDir = null;
myContext = context;
myClassToSubclasses = new TransientMultiMaplet<DependencyContext.S, DependencyContext.S>(ourStringSetConstructor);
mySourceFileToClasses = new TransientMultiMaplet<DependencyContext.S, ClassRepr>(ourClassSetConstructor);
mySourceFileToUsages = new TransientMaplet<DependencyContext.S, UsageRepr.Cluster>();
mySourceFileToAnnotationUsages = new TransientMultiMaplet<DependencyContext.S, UsageRepr.Usage>(ourUsageSetConstructor);
myClassToSourceFile = new TransientMaplet<DependencyContext.S, DependencyContext.S>();
myClassToClassDependency = new TransientMultiMaplet<DependencyContext.S, DependencyContext.S>(ourStringSetConstructor);
}
public Mappings(final File rootDir) throws IOException {
myRootDir = rootDir;
createPersistentImplementation(rootDir);
}
private void createPersistentImplementation(File rootDir) throws IOException {
myContext = new DependencyContext(rootDir);
myClassToSubclasses =
new PersistentMultiMaplet<DependencyContext.S, DependencyContext.S>(DependencyContext.getTableFile(rootDir, classToSubclassesName),
DependencyContext.descriptorS, DependencyContext.descriptorS,
ourStringSetConstructor);
myClassToClassDependency =
new PersistentMultiMaplet<DependencyContext.S, DependencyContext.S>(DependencyContext.getTableFile(rootDir, classToClassName),
DependencyContext.descriptorS, DependencyContext.descriptorS,
ourStringSetConstructor);
mySourceFileToClasses =
new PersistentMultiMaplet<DependencyContext.S, ClassRepr>(DependencyContext.getTableFile(rootDir, sourceToClassName),
DependencyContext.descriptorS, ClassRepr.externalizer(myContext),
ourClassSetConstructor);
mySourceFileToAnnotationUsages =
new PersistentMultiMaplet<DependencyContext.S, UsageRepr.Usage>(DependencyContext.getTableFile(rootDir, sourceToAnnotationsName),
DependencyContext.descriptorS, UsageRepr.externalizer(myContext),
ourUsageSetConstructor);
mySourceFileToUsages =
new PersistentMaplet<DependencyContext.S, UsageRepr.Cluster>(DependencyContext.getTableFile(rootDir, sourceToUsagesName),
DependencyContext.descriptorS,
UsageRepr.Cluster.clusterExternalizer(myContext));
myClassToSourceFile =
new PersistentMaplet<DependencyContext.S, DependencyContext.S>(DependencyContext.getTableFile(rootDir, classToSourceName),
DependencyContext.descriptorS, DependencyContext.descriptorS);
}
public Mappings createDelta() {
return new Mappings(myContext);
}
private void compensateRemovedContent(final Collection<File> compiled) {
for (File file : compiled) {
final DependencyContext.S key = myContext.get(FileUtil.toSystemIndependentName(file.getAbsolutePath()));
if (!mySourceFileToClasses.containsKey(key)) {
mySourceFileToClasses.put(key, new HashSet<ClassRepr>());
}
}
}
@Nullable
private ClassRepr getReprByName(final DependencyContext.S name) {
final DependencyContext.S source = myClassToSourceFile.get(name);
if (source != null) {
final Collection<ClassRepr> reprs = mySourceFileToClasses.get(source);
if (reprs != null) {
for (ClassRepr repr : reprs) {
if (repr.name.equals(name)) {
return repr;
}
}
}
}
return null;
}
public void clean() throws IOException {
if (myRootDir != null) {
close();
FileUtil.delete(myRootDir);
createPersistentImplementation(myRootDir);
}
}
private class Util {
final Mappings delta;
private Util() {
delta = null;
}
private Util(Mappings delta) {
this.delta = delta;
}
void appendDependents(final Set<ClassRepr> classes, final Set<DependencyContext.S> result) {
if (classes == null) {
return;
}
for (ClassRepr c : classes) {
final Collection<DependencyContext.S> depClasses = delta.myClassToClassDependency.get(c.name);
if (depClasses != null) {
for (DependencyContext.S className : depClasses) {
result.add(className);
}
}
}
}
void propagateMemberAccessRec(final Collection<DependencyContext.S> acc,
final boolean isField,
final boolean root,
final DependencyContext.S name,
final DependencyContext.S reflcass) {
final ClassRepr repr = reprByName(reflcass);
if (repr != null) {
if (!root) {
final Collection members = isField ? repr.fields : repr.methods;
for (Object o : members) {
final ProtoMember m = (ProtoMember)o;
if (m.name.equals(name)) {
return;
}
}
acc.add(reflcass);
}
final Collection<DependencyContext.S> subclasses = myClassToSubclasses.get(reflcass);
if (subclasses != null) {
for (DependencyContext.S subclass : subclasses) {
propagateMemberAccessRec(acc, isField, false, name, subclass);
}
}
}
}
Collection<DependencyContext.S> propagateMemberAccess(final boolean isField,
final DependencyContext.S name,
final DependencyContext.S className) {
final Set<DependencyContext.S> acc = new HashSet<DependencyContext.S>();
propagateMemberAccessRec(acc, isField, true, name, className);
return acc;
}
Collection<DependencyContext.S> propagateFieldAccess(final DependencyContext.S name, final DependencyContext.S className) {
return propagateMemberAccess(true, name, className);
}
Collection<DependencyContext.S> propagateMethodAccess(final DependencyContext.S name, final DependencyContext.S className) {
return propagateMemberAccess(false, name, className);
}
MethodRepr.Predicate lessSpecific(final MethodRepr than) {
return new MethodRepr.Predicate() {
@Override
public boolean satisfy(final MethodRepr m) {
if (!m.name.equals(than.name) || m.argumentTypes.length != than.argumentTypes.length) {
return false;
}
for (int i = 0; i < than.argumentTypes.length; i++) {
if (!isSubtypeOf(than.argumentTypes[i], m.argumentTypes[i])) {
return false;
}
}
return true;
}
};
}
Collection<Pair<MethodRepr, ClassRepr>> findOverridingMethods(final MethodRepr m, final ClassRepr c) {
return findOverridingMethods(m, c, false);
}
Collection<Pair<MethodRepr, ClassRepr>> findOverridingMethods(final MethodRepr m, final ClassRepr c, final boolean bySpecificity) {
final Set<Pair<MethodRepr, ClassRepr>> result = new HashSet<Pair<MethodRepr, ClassRepr>>();
final MethodRepr.Predicate predicate = bySpecificity ? lessSpecific(m) : MethodRepr.equalByJavaRules(m);
new Object() {
public void run(final ClassRepr c) {
final Collection<DependencyContext.S> subClasses = myClassToSubclasses.get(c.name);
if (subClasses != null) {
for (DependencyContext.S subClassName : subClasses) {
final ClassRepr r = reprByName(subClassName);
if (r != null) {
boolean cont = true;
final Collection<MethodRepr> methods = r.findMethods(predicate);
for (MethodRepr mm : methods) {
if (isVisibleIn(c, m, r)) {
result.add(new Pair<MethodRepr, ClassRepr>(mm, r));
cont = false;
}
}
if (cont) {
run(r);
}
}
}
}
}
}.run(c);
return result;
}
Collection<Pair<MethodRepr, ClassRepr>> findOverridenMethods(final MethodRepr m, final ClassRepr c) {
return findOverridenMethods(m, c, false);
}
Collection<Pair<MethodRepr, ClassRepr>> findOverridenMethods(final MethodRepr m, final ClassRepr c, final boolean bySpecificity) {
final Set<Pair<MethodRepr, ClassRepr>> result = new HashSet<Pair<MethodRepr, ClassRepr>>();
final MethodRepr.Predicate predicate = bySpecificity ? lessSpecific(m) : MethodRepr.equalByJavaRules(m);
new Object() {
public void run(final ClassRepr c) {
final DependencyContext.S[] supers = c.getSupers();
for (DependencyContext.S succName : supers) {
final ClassRepr r = reprByName(succName);
if (r != null) {
boolean cont = true;
final Collection<MethodRepr> methods = r.findMethods(predicate);
for (MethodRepr mm : methods) {
if (isVisibleIn(r, mm, c)) {
result.add(new Pair<MethodRepr, ClassRepr>(mm, r));
cont = false;
}
}
if (cont) {
run(r);
}
}
}
}
}.run(c);
return result;
}
Collection<Pair<MethodRepr, ClassRepr>> findAllMethodsBySpecificity(final MethodRepr m, final ClassRepr c) {
final Collection<Pair<MethodRepr, ClassRepr>> result = findOverridenMethods(m, c, true);
result.addAll(findOverridingMethods(m, c, true));
return result;
}
Collection<Pair<FieldRepr, ClassRepr>> findOverridenFields(final FieldRepr f, final ClassRepr c) {
final Set<Pair<FieldRepr, ClassRepr>> result = new HashSet<Pair<FieldRepr, ClassRepr>>();
new Object() {
public void run(final ClassRepr c) {
final DependencyContext.S[] supers = c.getSupers();
for (DependencyContext.S succName : supers) {
final ClassRepr r = reprByName(succName);
if (r != null) {
boolean cont = true;
if (r.fields.contains(f)) {
final FieldRepr ff = r.findField(f.name);
if (ff != null) {
if (isVisibleIn(r, ff, c)) {
result.add(new Pair<FieldRepr, ClassRepr>(ff, r));
cont = false;
}
}
}
if (cont) {
run(r);
}
}
}
}
}.run(c);
return result;
}
ClassRepr reprByName(final DependencyContext.S name) {
if (delta != null) {
final ClassRepr r = delta.getReprByName(name);
if (r != null) {
return r;
}
}
return getReprByName(name);
}
boolean isInheritorOf(final DependencyContext.S who, final DependencyContext.S whom) {
if (who.equals(whom)) {
return true;
}
final ClassRepr repr = reprByName(who);
if (repr != null) {
for (DependencyContext.S s : repr.getSupers()) {
if (isInheritorOf(s, whom)) {
return true;
}
}
}
return false;
}
boolean isSubtypeOf(final TypeRepr.AbstractType who, final TypeRepr.AbstractType whom) {
if (who.equals(whom)) {
return true;
}
if (who instanceof TypeRepr.PrimitiveType || whom instanceof TypeRepr.PrimitiveType) {
return false;
}
if (who instanceof TypeRepr.ArrayType) {
if (whom instanceof TypeRepr.ArrayType) {
return isSubtypeOf(((TypeRepr.ArrayType)who).elementType, ((TypeRepr.ArrayType)whom).elementType);
}
final String descr = whom.getDescr(myContext);
if (descr.equals("Ljava/lang/Cloneable") || descr.equals("Ljava/lang/Object") || descr.equals("Ljava/io/Serializable")) {
return true;
}
return false;
}
if (whom instanceof TypeRepr.ClassType) {
return isInheritorOf(((TypeRepr.ClassType)who).className, ((TypeRepr.ClassType)whom).className);
}
return false;
}
boolean fieldVisible(final DependencyContext.S className, final FieldRepr field) {
final ClassRepr r = reprByName(className);
if (r != null) {
if (r.fields.contains(field)) {
return true;
}
return findOverridenFields(field, r).size() > 0;
}
return false;
}
void affectSubclasses(final DependencyContext.S className,
final Collection<File> affectedFiles,
final Collection<UsageRepr.Usage> affectedUsages,
final Collection<DependencyContext.S> dependants,
final boolean usages) {
final DependencyContext.S fileName = myClassToSourceFile.get(className);
if (fileName == null) {
return;
}
if (usages) {
final ClassRepr classRepr = reprByName(className);
if (classRepr != null) {
affectedUsages.add(classRepr.createUsage());
}
}
final Collection<DependencyContext.S> depClasses = myClassToClassDependency.get(fileName);
if (depClasses != null) {
dependants.addAll(depClasses);
}
affectedFiles.add(new File(myContext.getValue(fileName)));
final Collection<DependencyContext.S> directSubclasses = myClassToSubclasses.get(className);
if (directSubclasses != null) {
for (DependencyContext.S subClass : directSubclasses) {
affectSubclasses(subClass, affectedFiles, affectedUsages, dependants, usages);
}
}
}
void affectFieldUsages(final FieldRepr field,
final Collection<DependencyContext.S> subclasses,
final UsageRepr.Usage rootUsage,
final Set<UsageRepr.Usage> affectedUsages,
final Set<DependencyContext.S> dependents) {
affectedUsages.add(rootUsage);
for (DependencyContext.S p : subclasses) {
final Collection<DependencyContext.S> deps = myClassToClassDependency.get(p);
if (deps != null) {
dependents.addAll(deps);
}
affectedUsages
.add(rootUsage instanceof UsageRepr.FieldAssignUsage ? field.createAssignUsage(myContext, p) : field.createUsage(myContext, p));
}
}
void affectMethodUsages(final MethodRepr method,
final Collection<DependencyContext.S> subclasses,
final UsageRepr.Usage rootUsage,
final Set<UsageRepr.Usage> affectedUsages,
final Set<DependencyContext.S> dependents) {
affectedUsages.add(rootUsage);
for (DependencyContext.S p : subclasses) {
final Collection<DependencyContext.S> deps = myClassToClassDependency.get(p);
if (deps != null) {
dependents.addAll(deps);
}
affectedUsages.add(method.createUsage(myContext, p));
}
}
void affectAll(final DependencyContext.S className, final Collection<File> affectedFiles) {
final Set<DependencyContext.S> dependants = (Set<DependencyContext.S>)myClassToClassDependency.get(className);
if (dependants != null) {
for (DependencyContext.S depClass : dependants) {
final DependencyContext.S depFile = myClassToSourceFile.get(depClass);
if (depFile != null) {
affectedFiles.add(new File(myContext.getValue(depFile)));
}
}
}
}
public abstract class UsageConstraint {
public abstract boolean checkResidence(final DependencyContext.S residence);
}
public class PackageConstraint extends UsageConstraint {
public final String packageName;
public PackageConstraint(final String packageName) {
this.packageName = packageName;
}
@Override
public boolean checkResidence(final DependencyContext.S residence) {
return !ClassRepr.getPackageName(myContext.getValue(residence)).equals(packageName);
}
}
public class InheritanceConstraint extends UsageConstraint {
public final DependencyContext.S rootClass;
public InheritanceConstraint(final DependencyContext.S rootClass) {
this.rootClass = rootClass;
}
@Override
public boolean checkResidence(final DependencyContext.S residence) {
return !isInheritorOf(residence, rootClass);
}
}
public class NegationConstraint extends UsageConstraint {
final UsageConstraint x;
public NegationConstraint(UsageConstraint x) {
this.x = x;
}
@Override
public boolean checkResidence(final DependencyContext.S residence) {
return !x.checkResidence(residence);
}
}
public class IntersectionConstraint extends UsageConstraint {
final UsageConstraint x;
final UsageConstraint y;
public IntersectionConstraint(final UsageConstraint x, final UsageConstraint y) {
this.x = x;
this.y = y;
}
@Override
public boolean checkResidence(final DependencyContext.S residence) {
return x.checkResidence(residence) && y.checkResidence(residence);
}
}
}
private static boolean isPackageLocal(final int access) {
return (access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED | Opcodes.ACC_PUBLIC)) == 0;
}
private static boolean weakerAccess(final int me, final int then) {
return ((me & Opcodes.ACC_PRIVATE) > 0 && (then & Opcodes.ACC_PRIVATE) == 0) ||
((me & Opcodes.ACC_PROTECTED) > 0 && (then & Opcodes.ACC_PUBLIC) > 0) ||
(isPackageLocal(me) && (then & Opcodes.ACC_PROTECTED) > 0);
}
private static boolean isVisibleIn(final ClassRepr c, final ProtoMember m, final ClassRepr scope) {
final boolean privacy = ((m.access & Opcodes.ACC_PRIVATE) > 0) && !c.name.equals(scope.name);
final boolean packageLocality = isPackageLocal(m.access) && !c.getPackageName().equals(scope.getPackageName());
return !privacy && !packageLocality;
}
private boolean empty(final DependencyContext.S s) {
return s.equals(myContext.get(""));
}
public boolean differentiate(final Mappings delta,
final Collection<String> removed,
final Collection<File> filesToCompile,
final Collection<File> compiledFiles,
final Collection<File> affectedFiles) {
delta.compensateRemovedContent(filesToCompile);
final Util u = new Util(delta);
final Util self = new Util(this);
final Util o = new Util();
if (removed != null) {
for (String file : removed) {
final Collection<ClassRepr> classes = mySourceFileToClasses.get(myContext.get(file));
if (classes != null) {
for (ClassRepr c : classes) {
u.affectAll(c.name, affectedFiles);
}
}
}
}
for (DependencyContext.S fileName : delta.mySourceFileToClasses.keyCollection()) {
final Set<ClassRepr> classes = (Set<ClassRepr>)delta.mySourceFileToClasses.get(fileName);
final Set<ClassRepr> pastClasses = (Set<ClassRepr>)mySourceFileToClasses.get(fileName);
final Set<DependencyContext.S> dependants = new HashSet<DependencyContext.S>();
self.appendDependents(pastClasses, dependants);
final Set<UsageRepr.Usage> affectedUsages = new HashSet<UsageRepr.Usage>();
final Set<UsageRepr.AnnotationUsage> annotationQuery = new HashSet<UsageRepr.AnnotationUsage>();
final Map<UsageRepr.Usage, Util.UsageConstraint> usageConstraints = new HashMap<UsageRepr.Usage, Util.UsageConstraint>();
final Difference.Specifier<ClassRepr> classDiff = Difference.make(pastClasses, classes);
for (Pair<ClassRepr, Difference> changed : classDiff.changed()) {
final ClassRepr it = changed.first;
final ClassRepr.Diff diff = (ClassRepr.Diff)changed.second;
final int addedModifiers = diff.addedModifiers();
final int removedModifiers = diff.removedModifiers();
final boolean superClassChanged = (diff.base() & Difference.SUPERCLASS) > 0;
final boolean interfacesChanged = !diff.interfaces().unchanged();
final boolean signatureChanged = (diff.base() & Difference.SIGNATURE) > 0;
if (superClassChanged || interfacesChanged || signatureChanged) {
final boolean extendsChanged = superClassChanged && !diff.extendsAdded();
final boolean interfacesRemoved = interfacesChanged && !diff.interfaces().removed().isEmpty();
u.affectSubclasses(it.name, affectedFiles, affectedUsages, dependants, extendsChanged || interfacesRemoved || signatureChanged);
}
if ((diff.addedModifiers() & Opcodes.ACC_INTERFACE) > 0 || (diff.removedModifiers() & Opcodes.ACC_INTERFACE) > 0) {
affectedUsages.add(it.createUsage());
}
if (it.isAnnotation() && it.policy == RetentionPolicy.SOURCE) {
return false;
}
if ((addedModifiers & Opcodes.ACC_PROTECTED) > 0) {
final UsageRepr.Usage usage = it.createUsage();
affectedUsages.add(usage);
usageConstraints.put(usage, u.new InheritanceConstraint(it.name));
}
if (diff.packageLocalOn()) {
final UsageRepr.Usage usage = it.createUsage();
affectedUsages.add(usage);
usageConstraints.put(usage, u.new PackageConstraint(it.getPackageName()));
}
if ((addedModifiers & Opcodes.ACC_FINAL) > 0 || (addedModifiers & Opcodes.ACC_PRIVATE) > 0) {
affectedUsages.add(it.createUsage());
}
if ((addedModifiers & Opcodes.ACC_ABSTRACT) > 0) {
affectedUsages.add(UsageRepr.createClassNewUsage(myContext, it.name));
}
if ((addedModifiers & Opcodes.ACC_STATIC) > 0 ||
(removedModifiers & Opcodes.ACC_STATIC) > 0 ||
(addedModifiers & Opcodes.ACC_ABSTRACT) > 0) {
affectedUsages.add(UsageRepr.createClassNewUsage(myContext, it.name));
}
if (it.isAnnotation()) {
if (diff.retentionChanged()) {
affectedUsages.add(it.createUsage());
}
else {
final Collection<ElementType> removedtargets = diff.targets().removed();
if (removedtargets.contains(ElementType.LOCAL_VARIABLE)) {
return false;
}
if (!removedtargets.isEmpty()) {
annotationQuery.add((UsageRepr.AnnotationUsage)UsageRepr
.createAnnotationUsage(myContext, TypeRepr.createClassType(myContext, it.name), null, removedtargets));
}
for (MethodRepr m : diff.methods().added()) {
if (!m.hasValue()) {
affectedUsages.add(it.createUsage());
}
}
}
}
for (MethodRepr m : diff.methods().added()) {
if ((it.access & Opcodes.ACC_INTERFACE) > 0 || (m.access & Opcodes.ACC_ABSTRACT) > 0) {
u.affectSubclasses(it.name, affectedFiles, affectedUsages, dependants, false);
}
if ((m.access & Opcodes.ACC_PRIVATE) == 0) {
final Collection<Pair<MethodRepr, ClassRepr>> affectedMethods = u.findAllMethodsBySpecificity(m, it);
final MethodRepr.Predicate overrides = MethodRepr.equalByJavaRules(m);
final Collection<DependencyContext.S> propagated = u.propagateMethodAccess(m.name, it.name);
final Collection<MethodRepr> lessSpecific = it.findMethods(u.lessSpecific(m));
for (MethodRepr mm : lessSpecific) {
u.affectMethodUsages(mm, propagated, mm.createUsage(myContext, it.name), affectedUsages, dependants);
}
for (Pair<MethodRepr, ClassRepr> p : affectedMethods) {
final MethodRepr mm = p.first;
final ClassRepr cc = p.second;
if (overrides.satisfy(mm)) {
if (weakerAccess(mm.access, m.access) ||
((m.access & Opcodes.ACC_STATIC) > 0 && (mm.access & Opcodes.ACC_STATIC) == 0) ||
((m.access & Opcodes.ACC_STATIC) == 0 && (mm.access & Opcodes.ACC_STATIC) > 0) ||
((m.access & Opcodes.ACC_FINAL) > 0) ||
!m.exceptions.equals(mm.exceptions) ||
!u.isSubtypeOf(mm.type, m.type) ||
!empty(mm.signature) || !empty(m.signature)) {
final DependencyContext.S file = myClassToSourceFile.get(cc.name);
if (file != null) {
affectedFiles.add(new File(myContext.getValue(file)));
}
}
}
else {
final Collection<DependencyContext.S> yetPropagated = u.propagateMethodAccess(mm.name, cc.name);
u.affectMethodUsages(mm, yetPropagated, mm.createUsage(myContext, cc.name), affectedUsages, dependants);
}
}
}
}
for (MethodRepr m : diff.methods().removed()) {
final Collection<Pair<MethodRepr, ClassRepr>> overridenMethods = u.findOverridenMethods(m, it);
final Collection<DependencyContext.S> propagated = u.propagateMethodAccess(m.name, it.name);
if (overridenMethods.size() == 0) {
u.affectMethodUsages(m, propagated, m.createUsage(myContext, it.name), affectedUsages, dependants);
}
else {
boolean clear = true;
loop:
for (Pair<MethodRepr, ClassRepr> overriden : overridenMethods) {
final MethodRepr mm = overriden.first;
if (!mm.type.equals(m.type) || !empty(mm.signature) || !empty(m.signature)) {
clear = false;
break loop;
}
}
if (!clear) {
u.affectMethodUsages(m, propagated, m.createUsage(myContext, it.name), affectedUsages, dependants);
}
}
if ((m.access & Opcodes.ACC_ABSTRACT) == 0) {
for (DependencyContext.S p : propagated) {
final ClassRepr s = u.reprByName(p);
if (s != null) {
final Collection<Pair<MethodRepr, ClassRepr>> overridenInS = u.findOverridenMethods(m, s);
overridenInS.addAll(overridenMethods);
boolean allAbstract = true;
boolean visited = false;
for (Pair<MethodRepr, ClassRepr> pp : overridenInS) {
if (pp.second.name.equals(it.name)) {
continue;
}
visited = true;
allAbstract = ((pp.first.access & Opcodes.ACC_ABSTRACT) > 0) || ((pp.second.access & Opcodes.ACC_INTERFACE) > 0);
if (!allAbstract) {
break;
}
}
if (allAbstract && visited) {
final DependencyContext.S source = myClassToSourceFile.get(p);
if (source != null) {
affectedFiles.add(new File(myContext.getValue(source)));
}
}
}
}
}
}
for (Pair<MethodRepr, Difference> mr : diff.methods().changed()) {
final MethodRepr m = mr.first;
final MethodRepr.Diff d = (MethodRepr.Diff)mr.second;
final boolean throwsChanged = (d.exceptions().added().size() > 0) || (d.exceptions().changed().size() > 0);
if (it.isAnnotation()) {
if (d.defaultRemoved()) {
final List<DependencyContext.S> l = new LinkedList<DependencyContext.S>();
l.add(m.name);
annotationQuery.add((UsageRepr.AnnotationUsage)UsageRepr
.createAnnotationUsage(myContext, TypeRepr.createClassType(myContext, it.name), l, null));
}
}
else if (d.base() != Difference.NONE || throwsChanged) {
final Collection<DependencyContext.S> propagated = u.propagateMethodAccess(m.name, it.name);
if (d.packageLocalOn()) {
final Set<UsageRepr.Usage> usages = new HashSet<UsageRepr.Usage>();
u.affectMethodUsages(m, propagated, m.createUsage(myContext, it.name), usages, dependants);
for (UsageRepr.Usage usage : usages) {
usageConstraints.put(usage, u.new InheritanceConstraint(it.name));
}
affectedUsages.addAll(usages);
}
if ((d.base() & Difference.TYPE) > 0 || (d.base() & Difference.SIGNATURE) > 0 || throwsChanged) {
u.affectMethodUsages(m, propagated, m.createUsage(myContext, it.name), affectedUsages, dependants);
}
else if ((d.base() & Difference.ACCESS) > 0) {
if ((d.addedModifiers() & Opcodes.ACC_STATIC) > 0 ||
(d.removedModifiers() & Opcodes.ACC_STATIC) > 0 ||
(d.addedModifiers() & Opcodes.ACC_PRIVATE) > 0) {
u.affectMethodUsages(m, propagated, m.createUsage(myContext, it.name), affectedUsages, dependants);
if ((d.addedModifiers() & Opcodes.ACC_STATIC) > 0) {
u.affectSubclasses(it.name, affectedFiles, affectedUsages, dependants, false);
}
}
else {
if ((d.addedModifiers() & Opcodes.ACC_FINAL) > 0 ||
(d.addedModifiers() & Opcodes.ACC_PUBLIC) > 0 ||
(d.addedModifiers() & Opcodes.ACC_ABSTRACT) > 0) {
u.affectSubclasses(it.name, affectedFiles, affectedUsages, dependants, false);
}
if ((d.addedModifiers() & Opcodes.ACC_PROTECTED) > 0 && !((d.removedModifiers() & Opcodes.ACC_PRIVATE) > 0)) {
final Set<UsageRepr.Usage> usages = new HashSet<UsageRepr.Usage>();
u.affectMethodUsages(m, propagated, m.createUsage(myContext, it.name), usages, dependants);
for (UsageRepr.Usage usage : usages) {
usageConstraints.put(usage, u.new InheritanceConstraint(it.name));
}
affectedUsages.addAll(usages);
}
}
}
}
}
final int mask = Opcodes.ACC_STATIC | Opcodes.ACC_FINAL;
for (FieldRepr f : diff.fields().added()) {
final boolean fPrivate = (f.access & Opcodes.ACC_PRIVATE) > 0;
final boolean fProtected = (f.access & Opcodes.ACC_PROTECTED) > 0;
final boolean fPublic = (f.access & Opcodes.ACC_PUBLIC) > 0;
final boolean fPLocal = !fPrivate && !fProtected && !fPublic;
if (!fPrivate) {
final Collection<DependencyContext.S> subClasses = myClassToSubclasses.get(it.name);
if (subClasses != null) {
for (final DependencyContext.S subClass : subClasses) {
final ClassRepr r = u.reprByName(subClass);
final DependencyContext.S sourceFileName = myClassToSourceFile.get(subClass);
if (r != null && sourceFileName != null) {
if (r.isLocal) {
affectedFiles.add(new File(myContext.getValue(sourceFileName)));
}
else {
final DependencyContext.S outerClass = r.outerClassName;
if (u.fieldVisible(outerClass, f)) {
affectedFiles.add(new File(myContext.getValue(sourceFileName)));
}
}
}
final Collection<DependencyContext.S> propagated = u.propagateFieldAccess(f.name, subClass);
u.affectFieldUsages(f, propagated, f.createUsage(myContext, subClass), affectedUsages, dependants);
final Collection<DependencyContext.S> deps = myClassToClassDependency.get(subClass);
if (deps != null) {
dependants.addAll(deps);
}
}
}
}
final Collection<Pair<FieldRepr, ClassRepr>> overriden = u.findOverridenFields(f, it);
for (Pair<FieldRepr, ClassRepr> p : overriden) {
final FieldRepr ff = p.first;
final ClassRepr cc = p.second;
final boolean ffPrivate = (ff.access & Opcodes.ACC_PRIVATE) > 0;
final boolean ffProtected = (ff.access & Opcodes.ACC_PROTECTED) > 0;
final boolean ffPublic = (ff.access & Opcodes.ACC_PUBLIC) > 0;
final boolean ffPLocal = isPackageLocal(ff.access);
if (!ffPrivate) {
final Collection<DependencyContext.S> propagated = o.propagateFieldAccess(ff.name, cc.name);
final Set<UsageRepr.Usage> localUsages = new HashSet<UsageRepr.Usage>();
u.affectFieldUsages(ff, propagated, ff.createUsage(myContext, cc.name), localUsages, dependants);
if (fPrivate || (fPublic && (ffPublic || ffPLocal)) || (fProtected && ffProtected) || (fPLocal && ffPLocal)) {
}
else {
Util.UsageConstraint constaint;
if ((ffProtected && fPublic) || (fProtected && ffPublic) || (ffPLocal && fProtected)) {
constaint = u.new NegationConstraint(u.new InheritanceConstraint(cc.name));
}
else if (ffPublic && ffPLocal) {
constaint = u.new NegationConstraint(u.new PackageConstraint(cc.getPackageName()));
}
else {
constaint = u.new IntersectionConstraint(u.new NegationConstraint(u.new InheritanceConstraint(cc.name)),
u.new NegationConstraint(u.new PackageConstraint(cc.getPackageName())));
}
for (UsageRepr.Usage usage : localUsages) {
usageConstraints.put(usage, constaint);
}
}
affectedUsages.addAll(localUsages);
}
}
}
for (FieldRepr f : diff.fields().removed()) {
if ((f.access & mask) == mask && f.hasValue()) {
return false;
}
final Collection<DependencyContext.S> propagated = u.propagateFieldAccess(f.name, it.name);
u.affectFieldUsages(f, propagated, f.createUsage(myContext, it.name), affectedUsages, dependants);
}
for (Pair<FieldRepr, Difference> f : diff.fields().changed()) {
final Difference d = f.second;
final FieldRepr field = f.first;
if ((field.access & mask) == mask) {
if ((d.base() & Difference.ACCESS) > 0 || (d.base() & Difference.VALUE) > 0) {
return false;
}
}
if (d.base() != Difference.NONE) {
final Collection<DependencyContext.S> propagated = u.propagateFieldAccess(field.name, it.name);
if ((d.base() & Difference.TYPE) > 0 || (d.base() & Difference.SIGNATURE) > 0) {
u.affectFieldUsages(field, propagated, field.createUsage(myContext, it.name), affectedUsages, dependants);
}
else if ((d.base() & Difference.ACCESS) > 0) {
if ((d.addedModifiers() & Opcodes.ACC_STATIC) > 0 ||
(d.removedModifiers() & Opcodes.ACC_STATIC) > 0 ||
(d.addedModifiers() & Opcodes.ACC_PRIVATE) > 0 ||
(d.addedModifiers() & Opcodes.ACC_VOLATILE) > 0) {
u.affectFieldUsages(field, propagated, field.createUsage(myContext, it.name), affectedUsages, dependants);
}
else {
if ((d.addedModifiers() & Opcodes.ACC_FINAL) > 0) {
u.affectFieldUsages(field, propagated, field.createAssignUsage(myContext, it.name), affectedUsages, dependants);
}
if ((d.removedModifiers() & Opcodes.ACC_PUBLIC) > 0) {
final Set<UsageRepr.Usage> usages = new HashSet<UsageRepr.Usage>();
u.affectFieldUsages(field, propagated, field.createUsage(myContext, it.name), usages, dependants);
for (UsageRepr.Usage usage : usages) {
if ((d.addedModifiers() & Opcodes.ACC_PROTECTED) > 0) {
usageConstraints.put(usage, u.new InheritanceConstraint(it.name));
}
else {
usageConstraints.put(usage, u.new PackageConstraint(it.getPackageName()));
}
}
affectedUsages.addAll(usages);
}
}
}
}
}
}
for (ClassRepr c : classDiff.removed()) {
affectedUsages.add(c.createUsage());
}
for (ClassRepr c : classDiff.added()) {
final Collection<DependencyContext.S> depClasses = myClassToClassDependency.get(c.name);
if (depClasses != null) {
for (DependencyContext.S depClass : depClasses) {
final DependencyContext.S fName = myClassToSourceFile.get(depClass);
if (fName != null) {
affectedFiles.add(new File(myContext.getValue(fName)));
}
}
}
}
if (dependants != null) {
final Set<DependencyContext.S> dependentFiles = new HashSet<DependencyContext.S>();
for (DependencyContext.S depClass : dependants) {
final DependencyContext.S file = myClassToSourceFile.get(depClass);
if (file != null) {
dependentFiles.add(file);
}
}
dependentFiles.removeAll(compiledFiles);
filewise:
for (DependencyContext.S depFile : dependentFiles) {
if (affectedFiles.contains(new File(myContext.getValue(depFile)))) {
continue filewise;
}
final UsageRepr.Cluster depCluster = mySourceFileToUsages.get(depFile);
final Set<UsageRepr.Usage> depUsages = depCluster.getUsages();
if (depUsages != null) {
final Set<UsageRepr.Usage> usages = new HashSet<UsageRepr.Usage>(depUsages);
usages.retainAll(affectedUsages);
if (!usages.isEmpty()) {
for (UsageRepr.Usage usage : usages) {
final Util.UsageConstraint constraint = usageConstraints.get(usage);
if (constraint == null) {
affectedFiles.add(new File(myContext.getValue(depFile)));
continue filewise;
}
else {
final Set<DependencyContext.S> residenceClasses = depCluster.getResidence(usage);
for (DependencyContext.S residentName : residenceClasses) {
if (constraint.checkResidence(residentName)) {
affectedFiles.add(new File(myContext.getValue(depFile)));
continue filewise;
}
}
}
}
}
if (annotationQuery.size() > 0) {
final Collection<UsageRepr.Usage> annotationUsages = mySourceFileToAnnotationUsages.get(depFile);
for (UsageRepr.Usage usage : annotationUsages) {
for (UsageRepr.AnnotationUsage query : annotationQuery) {
if (query.satisfies(usage)) {
affectedFiles.add(new File(myContext.getValue(depFile)));
continue filewise;
}
}
}
}
}
}
}
}
return true;
}
public void integrate(final Mappings delta, final Collection<File> compiled, final Collection<String> removed) {
if (removed != null) {
for (String file : removed) {
final DependencyContext.S key = myContext.get(file);
final Set<ClassRepr> classes = (Set<ClassRepr>)mySourceFileToClasses.get(key);
final UsageRepr.Cluster cluster = mySourceFileToUsages.get(key);
final Set<UsageRepr.Usage> usages = cluster == null ? null : cluster.getUsages();
if (classes != null) {
for (ClassRepr cr : classes) {
myClassToSubclasses.remove(cr.name);
myClassToSourceFile.remove(cr.name);
myClassToClassDependency.remove(cr.name);
for (DependencyContext.S superSomething : cr.getSupers()) {
myClassToSubclasses.removeFrom(superSomething, cr.name);
}
if (usages != null) {
for (UsageRepr.Usage u : usages) {
if (u instanceof UsageRepr.ClassUsage) {
final Set<DependencyContext.S> residents = cluster.getResidence(u);
if (residents != null && residents.contains(cr.name)) {
myClassToClassDependency.removeFrom(((UsageRepr.ClassUsage)u).className, cr.name);
}
}
}
}
}
}
mySourceFileToClasses.remove(key);
mySourceFileToUsages.remove(key);
}
}
myClassToSubclasses.putAll(delta.myClassToSubclasses);
mySourceFileToClasses.putAll(delta.mySourceFileToClasses);
mySourceFileToUsages.putAll(delta.mySourceFileToUsages);
mySourceFileToAnnotationUsages.putAll(delta.mySourceFileToAnnotationUsages);
myClassToSourceFile.putAll(delta.myClassToSourceFile);
for (DependencyContext.S file : delta.myClassToClassDependency.keyCollection()) {
final Collection<DependencyContext.S> now = delta.myClassToClassDependency.get(file);
final Collection<DependencyContext.S> past = myClassToClassDependency.get(file);
if (past == null) {
myClassToClassDependency.put(file, now);
}
else {
final Collection<DependencyContext.S> removeSet = new HashSet<DependencyContext.S>();
for (File c : compiled) {
removeSet.add(myContext.get(FileUtil.toSystemIndependentName(c.getAbsolutePath())));
}
removeSet.removeAll(now);
past.addAll(now);
past.removeAll(removeSet);
myClassToClassDependency.remove(file);
myClassToClassDependency.put(file, past);
}
}
}
private void updateSourceToUsages(final DependencyContext.S source, final UsageRepr.Cluster usages) {
final UsageRepr.Cluster c = mySourceFileToUsages.get(source);
if (c == null) {
mySourceFileToUsages.put(source, usages);
}
else {
c.updateCluster(usages);
}
}
private void updateSourceToAnnotationUsages(final DependencyContext.S source, final Set<UsageRepr.Usage> usages) {
mySourceFileToAnnotationUsages.put(source, usages);
}
public Callbacks.Backend getCallback() {
return new Callbacks.Backend() {
public Collection<String> getClassFiles() {
final HashSet<String> result = new HashSet<String>();
for (DependencyContext.S s : myClassToSourceFile.keyCollection()) {
result.add(myContext.getValue(s));
}
return result;
}
public void associate(final String classFileName, final Callbacks.SourceFileNameLookup sourceFileName, final ClassReader cr) {
final DependencyContext.S classFileNameS = myContext.get(classFileName);
final Pair<ClassRepr, Pair<UsageRepr.Cluster, Set<UsageRepr.Usage>>> result =
new ClassfileAnalyzer(myContext).analyze(classFileNameS, cr);
final ClassRepr repr = result.first;
final UsageRepr.Cluster localUsages = result.second.first;
final Set<UsageRepr.Usage> localAnnotationUsages = result.second.second;
final String srcFileName = sourceFileName.get(repr == null ? null : myContext.getValue(repr.getSourceFileName()));
final DependencyContext.S sourceFileNameS = myContext.get(srcFileName);
if (repr != null) {
final DependencyContext.S className = repr.name;
for (UsageRepr.Usage u : localUsages.getUsages()) {
myClassToClassDependency.put(u.getOwner(), className);
}
}
if (repr != null) {
myClassToSourceFile.put(repr.name, sourceFileNameS);
mySourceFileToClasses.put(sourceFileNameS, repr);
for (DependencyContext.S s : repr.getSupers()) {
myClassToSubclasses.put(s, repr.name);
}
}
if (!localUsages.isEmpty()) {
updateSourceToUsages(sourceFileNameS, localUsages);
}
if (!localAnnotationUsages.isEmpty()) {
updateSourceToAnnotationUsages(sourceFileNameS, localAnnotationUsages);
}
}
};
}
@Nullable
public Set<ClassRepr> getClasses(final String sourceFileName) {
return (Set<ClassRepr>)mySourceFileToClasses.get(myContext.get(sourceFileName));
}
public void close() {
if (myRootDir != null) {
// only close if you own the context
myContext.close();
}
myClassToSubclasses.close();
myClassToClassDependency.close();
mySourceFileToClasses.close();
mySourceFileToAnnotationUsages.close();
mySourceFileToUsages.close();
myClassToSourceFile.close();
}
} |
package evidence;
public class Testing {
private static String[] weapons = {"The Norton","Gun Candlestick","Tuba","Frozen Waterbottle","Cafeteria Food","Fire Axe"};
private static String[] people = {
"Nicholas Biegel",
"Victor Bolivar",
"Nathon Bowdish",
"Jordan Buckmaster",
"Jocelynn Cheesebourough",
"Jay Chopra",
"Daniel Gilbert",
"Lauren Granskog",
"Ethan Hunt",
"Samuel Hupp",
"Nathon Jackson",
"Jacob Kieta",
"Celine McCormack",
"Noah Miller",
"Mike the Pimp Norcutt",
"Gage O'Conner",
"Mathew Palm",
"Dino Rinaldi",
"Andrew Ring",
"Peter Shepered",
"Justin Tancos",
"Tiffany Tao",
"Jesse Veloz",
"Jakub Wrobel",
"Jacob Zak"
};
private static String[] rooms = {"Mr. Clark's Room","Chem Lab","Chavez's Room","Cafeteria","Auto Room","Bathroom","Band Room","Art Studio","Gym"};
public static void main(String[] args){
System.out.println(people[(int) (Math.random() * people.length)] + " was found with a " + weapons[(int) (Math.random() * weapons.length)] + " in the " + rooms[(int) (Math.random() * rooms.length)]);
}
} |
package ts.client;
import java.io.File;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Consumer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import ts.TypeScriptException;
import ts.TypeScriptNoContentAvailableException;
import ts.client.codefixes.CodeAction;
import ts.client.compileonsave.CompileOnSaveAffectedFileListSingleProject;
import ts.client.completions.CompletionEntry;
import ts.client.completions.CompletionEntryDetails;
import ts.client.completions.ICompletionEntryFactory;
import ts.client.completions.ICompletionEntryMatcherProvider;
import ts.client.configure.ConfigureRequestArguments;
import ts.client.diagnostics.Diagnostic;
import ts.client.diagnostics.DiagnosticEvent;
import ts.client.diagnostics.DiagnosticEventBody;
import ts.client.installtypes.BeginInstallTypesEventBody;
import ts.client.installtypes.EndInstallTypesEventBody;
import ts.client.installtypes.IInstallTypesListener;
import ts.client.jsdoc.TextInsertion;
import ts.client.navbar.NavigationBarItem;
import ts.client.occurrences.OccurrencesResponseItem;
import ts.client.projectinfo.ProjectInfo;
import ts.client.quickinfo.QuickInfo;
import ts.client.references.ReferencesResponseBody;
import ts.client.rename.RenameResponseBody;
import ts.client.signaturehelp.SignatureHelpItems;
import ts.internal.FileTempHelper;
import ts.internal.SequenceHelper;
import ts.internal.client.protocol.ChangeRequest;
import ts.internal.client.protocol.CloseRequest;
import ts.internal.client.protocol.CodeFixRequest;
import ts.internal.client.protocol.CompileOnSaveAffectedFileListRequest;
import ts.internal.client.protocol.CompileOnSaveEmitFileRequest;
import ts.internal.client.protocol.CompletionDetailsRequest;
import ts.internal.client.protocol.CompletionsRequest;
import ts.internal.client.protocol.ConfigureRequest;
import ts.internal.client.protocol.DefinitionRequest;
import ts.internal.client.protocol.DocCommentTemplateRequest;
import ts.internal.client.protocol.FormatRequest;
import ts.internal.client.protocol.GetSupportedCodeFixesRequest;
import ts.internal.client.protocol.GeterrForProjectRequest;
import ts.internal.client.protocol.GeterrRequest;
import ts.internal.client.protocol.GsonHelper;
import ts.internal.client.protocol.IRequestEventable;
import ts.internal.client.protocol.ImplementationRequest;
import ts.internal.client.protocol.MessageType;
import ts.internal.client.protocol.NavBarRequest;
import ts.internal.client.protocol.NavTreeRequest;
import ts.internal.client.protocol.OccurrencesRequest;
import ts.internal.client.protocol.OpenExternalProjectRequest;
import ts.internal.client.protocol.OpenRequest;
import ts.internal.client.protocol.ProjectInfoRequest;
import ts.internal.client.protocol.QuickInfoRequest;
import ts.internal.client.protocol.ReferencesRequest;
import ts.internal.client.protocol.ReloadRequest;
import ts.internal.client.protocol.RenameRequest;
import ts.internal.client.protocol.Request;
import ts.internal.client.protocol.Response;
import ts.internal.client.protocol.SemanticDiagnosticsSyncRequest;
import ts.internal.client.protocol.SignatureHelpRequest;
import ts.internal.client.protocol.SyntacticDiagnosticsSyncRequest;
import ts.nodejs.INodejsLaunchConfiguration;
import ts.nodejs.INodejsProcess;
import ts.nodejs.INodejsProcessListener;
import ts.nodejs.NodejsProcessAdapter;
import ts.nodejs.NodejsProcessManager;
import ts.repository.TypeScriptRepositoryManager;
import ts.utils.FileUtils;
/**
* TypeScript service client implementation.
*
*/
public class TypeScriptServiceClient implements ITypeScriptServiceClient {
private static final String NO_CONTENT_AVAILABLE = "No content available.";
private static final String TSSERVER_FILE_TYPE = "tsserver";
private INodejsProcess process;
private List<INodejsProcessListener> nodeListeners;
private final List<ITypeScriptClientListener> listeners;
private final List<IInstallTypesListener> installTypesListener;
private final ReentrantReadWriteLock stateLock;
private boolean dispose;
private final Map<Integer, PendingRequestInfo> sentRequestMap;
private final Map<String, PendingRequestEventInfo> receivedRequestMap;
private List<IInterceptor> interceptors;
private ICompletionEntryMatcherProvider completionEntryMatcherProvider;
private final INodejsProcessListener listener = new NodejsProcessAdapter() {
@Override
public void onStart(INodejsProcess process) {
TypeScriptServiceClient.this.fireStartServer();
}
@Override
public void onStop(INodejsProcess process) {
dispose();
fireEndServer();
}
public void onMessage(INodejsProcess process, String message) {
if (message.startsWith("{")) {
TypeScriptServiceClient.this.dispatchMessage(message);
}
}
};
private static abstract class RequestInfo {
final Request<?> requestMessage;
final long startTime;
final CompletableFuture<?> requiredResult;
RequestInfo(Request<?> requestMessage, CompletableFuture<?> requiredResult) {
this.requestMessage = requestMessage;
this.startTime = System.nanoTime();
this.requiredResult = requiredResult;
}
}
private static class PendingRequestInfo extends RequestInfo {
final Consumer<Response<?>> responseHandler;
PendingRequestInfo(Request<?> requestMessage, Consumer<Response<?>> responseHandler,
CompletableFuture<?> requiredResult) {
super(requestMessage, requiredResult);
this.responseHandler = responseHandler;
}
}
private static class PendingRequestEventInfo extends RequestInfo {
final Consumer<Event<?>> eventHandler;
PendingRequestEventInfo(Request<?> requestMessage, Consumer<Event<?>> eventHandler,
CompletableFuture<?> requiredResult) {
super(requestMessage, requiredResult);
this.eventHandler = eventHandler;
}
}
public TypeScriptServiceClient(final File projectDir, File tsserverFile, File nodeFile) throws TypeScriptException {
this(projectDir, tsserverFile, nodeFile, false, false, null);
}
public TypeScriptServiceClient(final File projectDir, File typescriptDir, File nodeFile, boolean enableTelemetry,
boolean disableAutomaticTypingAcquisition, File tsserverPluginsFile) throws TypeScriptException {
this(NodejsProcessManager.getInstance().create(projectDir,
tsserverPluginsFile != null ? tsserverPluginsFile
: TypeScriptRepositoryManager.getTsserverFile(typescriptDir),
nodeFile, new INodejsLaunchConfiguration() {
@Override
public List<String> createNodeArgs() {
List<String> args = new ArrayList<String>();
// args.add("-p");
// args.add(FileUtils.getPath(projectDir));
if (enableTelemetry) {
args.add("--enableTelemetry");
}
if (disableAutomaticTypingAcquisition) {
args.add("--disableAutomaticTypingAcquisition");
}
if (tsserverPluginsFile != null) {
args.add("--typescriptDir");
args.add(FileUtils.getPath(typescriptDir));
}
// args.add("--useSingleInferredProject");
return args;
}
}, TSSERVER_FILE_TYPE));
}
public TypeScriptServiceClient(INodejsProcess process) {
this.listeners = new ArrayList<>();
this.installTypesListener = new ArrayList<>();
this.stateLock = new ReentrantReadWriteLock();
this.dispose = false;
this.sentRequestMap = new LinkedHashMap<>();
this.receivedRequestMap = new LinkedHashMap<>();
this.process = process;
process.addProcessListener(listener);
setCompletionEntryMatcherProvider(ICompletionEntryMatcherProvider.LCS_PROVIDER);
}
private void dispatchMessage(String message) {
JsonObject json = GsonHelper.parse(message).getAsJsonObject();
JsonElement typeElement = json.get("type");
if (typeElement != null) {
MessageType messageType = MessageType.getType(typeElement.getAsString());
if (messageType == null) {
throw new IllegalStateException("Unknown response type message " + json);
}
switch (messageType) {
case response:
int seq = json.get("request_seq").getAsInt();
PendingRequestInfo pendingRequestInfo;
synchronized (sentRequestMap) {
pendingRequestInfo = sentRequestMap.remove(seq);
}
if (pendingRequestInfo == null) {
// message " + json);
return;
}
Response<?> responseMessage = pendingRequestInfo.requestMessage.parseResponse(json);
if (responseMessage == null) {
responseMessage = GsonHelper.DEFAULT_GSON.fromJson(json, Response.class);
}
try {
handleResponse(responseMessage, message, pendingRequestInfo.startTime);
pendingRequestInfo.responseHandler.accept(responseMessage);
} catch (RuntimeException e) {
// LOG.log(Level.WARNING, "Handling repsonse
// "+responseMessage+" threw an exception.", e);
}
break;
case event:
String event = json.get("event").getAsString();
if ("syntaxDiag".equals(event) || "semanticDiag".equals(event)) {
DiagnosticEvent response = GsonHelper.DEFAULT_GSON.fromJson(json, DiagnosticEvent.class);
PendingRequestEventInfo pendingRequestEventInfo;
synchronized (receivedRequestMap) {
pendingRequestEventInfo = receivedRequestMap.remove(response.getKey());
}
if (pendingRequestEventInfo != null) {
pendingRequestEventInfo.eventHandler.accept(response);
}
} else if ("telemetry".equals(event)) {
// TelemetryEventBody telemetryData =
// GsonHelper.DEFAULT_GSON.fromJson(json,
// TelemetryEvent.class)
// .getBody();
JsonObject telemetryData = json.get("body").getAsJsonObject();
JsonObject payload = telemetryData.has("payload") ? telemetryData.get("payload").getAsJsonObject()
: null;
if (payload != null) {
String telemetryEventName = telemetryData.get("telemetryEventName").getAsString();
fireLogTelemetry(telemetryEventName, payload);
}
} else if ("beginInstallTypes".equals(event)) {
BeginInstallTypesEventBody data = GsonHelper.DEFAULT_GSON.fromJson(json,
BeginInstallTypesEventBody.class);
fireBeginInstallTypes(data);
} else if ("endInstallTypes".equals(event)) {
EndInstallTypesEventBody data = GsonHelper.DEFAULT_GSON.fromJson(json,
EndInstallTypesEventBody.class);
fireEndInstallTypes(data);
}
break;
default:
// Do nothing
}
}
}
@Override
public void openFile(String fileName, String content) throws TypeScriptException {
openFile(fileName, content, null);
}
@Override
public void openFile(String fileName, String content, ScriptKindName scriptKindName) throws TypeScriptException {
waitForFuture(executeNoResult(new OpenRequest(fileName, null, content, scriptKindName)));
}
@Override
public void closeFile(String fileName) throws TypeScriptException {
waitForFuture(executeNoResult(new CloseRequest(fileName)));
}
// @Override
// public void changeFile(String fileName, int position, int endPosition,
// String insertString) {
// execute(new ChangeRequest(fileName, position, endPosition, insertString),
// false);
@Override
public void changeFile(String fileName, int line, int offset, int endLine, int endOffset, String insertString)
throws TypeScriptException {
waitForFuture(executeNoResult(new ChangeRequest(fileName, line, offset, endLine, endOffset, insertString)));
}
/**
* Write the buffer of editor content to a temporary file and have the
* server reload it
*
* @param fileName
* @param newText
*/
@Override
public void updateFile(String fileName, String newText) throws TypeScriptException {
int seq = SequenceHelper.getRequestSeq();
String tempFileName = FileTempHelper.updateTempFile(newText, seq);
try {
execute(new ReloadRequest(fileName, tempFileName, seq)).get(5000, TimeUnit.MILLISECONDS);
} catch (Exception e) {
if (e instanceof TypeScriptException) {
throw (TypeScriptException) e;
}
throw new TypeScriptException(e);
}
}
// @Override
// public CompletableFuture<List<CompletionEntry>> completions(String
// fileName, int position) {
// return execute(new CompletionsRequest(fileName, position));
@Override
public CompletableFuture<List<CompletionEntry>> completions(String fileName, int line, int offset) {
return completions(fileName, line, offset, ICompletionEntryFactory.DEFAULT);
}
@Override
public CompletableFuture<List<CompletionEntry>> completions(String fileName, int line, int offset,
ICompletionEntryFactory factory) {
return execute(
new CompletionsRequest(fileName, line, offset, getCompletionEntryMatcherProvider(), this, factory));
}
@Override
public CompletableFuture<List<CompletionEntryDetails>> completionEntryDetails(String fileName, int line, int offset,
String[] entryNames, CompletionEntry completionEntry) {
return execute(new CompletionDetailsRequest(fileName, line, offset, null, entryNames));
}
@Override
public CompletableFuture<List<FileSpan>> definition(String fileName, int line, int offset) {
return execute(new DefinitionRequest(fileName, line, offset));
}
@Override
public CompletableFuture<SignatureHelpItems> signatureHelp(String fileName, int line, int offset) {
return execute(new SignatureHelpRequest(fileName, line, offset));
}
@Override
public CompletableFuture<QuickInfo> quickInfo(String fileName, int line, int offset) {
return execute(new QuickInfoRequest(fileName, line, offset));
}
@Override
public CompletableFuture<List<DiagnosticEvent>> geterr(String[] files, int delay) {
return execute(new GeterrRequest(files, delay));
}
@Override
public CompletableFuture<List<DiagnosticEvent>> geterrForProject(String file, int delay, ProjectInfo projectInfo) {
return execute(new GeterrForProjectRequest(file, delay, projectInfo));
}
@Override
public CompletableFuture<List<CodeEdit>> format(String fileName, int line, int offset, int endLine, int endOffset) {
return execute(new FormatRequest(fileName, line, offset, endLine, endOffset));
}
@Override
public CompletableFuture<ReferencesResponseBody> references(String fileName, int line, int offset) {
return execute(new ReferencesRequest(fileName, line, offset));
}
@Override
public CompletableFuture<List<OccurrencesResponseItem>> occurrences(String fileName, int line, int offset) {
return execute(new OccurrencesRequest(fileName, line, offset));
}
@Override
public CompletableFuture<RenameResponseBody> rename(String file, int line, int offset, Boolean findInComments,
Boolean findInStrings) {
return execute(new RenameRequest(file, line, offset, findInComments, findInStrings));
}
@Override
public CompletableFuture<List<NavigationBarItem>> navbar(String fileName, IPositionProvider positionProvider) {
return execute(new NavBarRequest(fileName, positionProvider));
}
@Override
public void configure(ConfigureRequestArguments arguments) throws TypeScriptException {
waitForFuture(execute(new ConfigureRequest(arguments)));
}
@Override
public CompletableFuture<ProjectInfo> projectInfo(String file, String projectFileName, boolean needFileNameList) {
return execute(new ProjectInfoRequest(file, needFileNameList));
}
@Override
public CompletableFuture<Void> openExternalProject(String projectFileName, List<String> rootFileNames) {
return executeCausingWait(new OpenExternalProjectRequest(projectFileName, rootFileNames));
}
// Since 2.0.3
@Override
public CompletableFuture<DiagnosticEventBody> semanticDiagnosticsSync(String file, Boolean includeLinePosition) {
return execute(new SemanticDiagnosticsSyncRequest(file, includeLinePosition)).thenApply(d -> {
return new DiagnosticEventBody(file, (List<Diagnostic>) d);
});
}
@Override
public CompletableFuture<DiagnosticEventBody> syntacticDiagnosticsSync(String file, Boolean includeLinePosition) {
return execute(new SyntacticDiagnosticsSyncRequest(file, includeLinePosition)).thenApply(d -> {
return new DiagnosticEventBody(file, (List<Diagnostic>) d);
});
}
// Since 2.0.5
@Override
public CompletableFuture<Boolean> compileOnSaveEmitFile(String fileName, Boolean forced) {
return execute(new CompileOnSaveEmitFileRequest(fileName, forced));
}
@Override
public CompletableFuture<List<CompileOnSaveAffectedFileListSingleProject>> compileOnSaveAffectedFileList(
String fileName) {
return execute(new CompileOnSaveAffectedFileListRequest(fileName));
}
// Since 2.0.6
@Override
public CompletableFuture<NavigationBarItem> navtree(String fileName, IPositionProvider positionProvider) {
return execute(new NavTreeRequest(fileName, positionProvider));
}
@Override
public CompletableFuture<TextInsertion> docCommentTemplate(String fileName, int line, int offset) {
return execute(new DocCommentTemplateRequest(fileName, line, offset));
}
// Since 2.1.0
@Override
public CompletableFuture<List<CodeAction>> getCodeFixes(String fileName, IPositionProvider positionProvider,
int startLine, int startOffset, int endLine, int endOffset, List<Integer> errorCodes) {
return execute(new CodeFixRequest(fileName, startLine, startOffset, endLine, endOffset, errorCodes));
}
@Override
public CompletableFuture<List<String>> getSupportedCodeFixes() {
return execute(new GetSupportedCodeFixesRequest());
}
@Override
public CompletableFuture<List<FileSpan>> implementation(String fileName, int line, int offset) {
return execute(new ImplementationRequest(fileName, line, offset));
}
/**
* Executes a request that does not expect a result. A future is returned
* (even if there is no result) in order to handle the possible waiting for
* required requests and for their exceptions.
*
* @param request
*/
private CompletableFuture<Void> executeNoResult(Request<?> request) {
return this._execute(request, false, false);
}
/**
* Executes a request that expects a result. The waiting for any pending
* request is chained with the completable future result that the caller has
* to handle anyway.
*
* @param request
* @return
*/
private <T> CompletableFuture<T> execute(Request<?> request) {
return this._execute(request, true, false);
}
/**
* Executes a request that expects a result, causing all subsequent requests
* to wait for this one to complete.
*
* @param request
* @return
*/
private <T> CompletableFuture<T> executeCausingWait(Request<?> request) {
return this._execute(request, true, true);
}
private <T> CompletableFuture<T> _execute(Request<?> request, boolean expectsResult, boolean causesWait) {
// prepare a future for waiting for all required requests
final CompletableFuture<?> requiredFuture = computeRequiredRequestsFuture();
// send the request after waiting for previous required requests
return requiredFuture.thenCompose(requiredResult -> {
CompletableFuture<T> result = new CompletableFuture<>();
// augment the future with response handling, if expected
if (expectsResult) {
// remove request info after completing exceptionally
result.whenComplete((requestResult, e) -> {
if (e != null) {
if (request instanceof IRequestEventable) {
List<String> keys = ((IRequestEventable) request).getKeys();
synchronized (receivedRequestMap) {
for (String key : keys) {
receivedRequestMap.remove(key);
}
}
} else {
synchronized (sentRequestMap) {
sentRequestMap.remove(request.getSeq());
}
}
}
});
// register request info in maps for handling the result
if (request instanceof IRequestEventable) {
Consumer<Event<?>> responseHandler = (event) -> {
if (((IRequestEventable) request).accept(event)) {
result.complete((T) ((IRequestEventable) request).getEvents());
}
};
List<String> keys = ((IRequestEventable) request).getKeys();
PendingRequestEventInfo info = new PendingRequestEventInfo(request, responseHandler,
causesWait ? result : null);
synchronized (receivedRequestMap) {
for (String key : keys) {
receivedRequestMap.put(key, info);
}
}
} else {
Consumer<Response<?>> responseHandler = (response) -> {
if (response.isSuccess()) {
// tsserver response with success
result.complete((T) response.getBody());
} else {
// tsserver response with error
result.completeExceptionally(createException(response.getMessage()));
}
};
int seq = request.getSeq();
synchronized (sentRequestMap) {
sentRequestMap.put(seq,
new PendingRequestInfo(request, responseHandler, causesWait ? result : null));
}
}
}
// send the request
try {
sendRequest(request);
} catch (TypeScriptException e) {
result.completeExceptionally(e);
}
// complete immediately, if no result expected
if (!expectsResult) {
result.complete(null);
}
return result;
});
}
private CompletableFuture<Void> computeRequiredRequestsFuture() {
synchronized (receivedRequestMap) {
synchronized (sentRequestMap) {
if (receivedRequestMap.isEmpty() && sentRequestMap.isEmpty()) {
return CompletableFuture.completedFuture(null);
}
List<CompletableFuture<?>> cfs = new ArrayList<>();
for (RequestInfo info : receivedRequestMap.values()) {
if (info.requiredResult != null) {
cfs.add(info.requiredResult);
}
}
for (RequestInfo info : sentRequestMap.values()) {
if (info.requiredResult != null) {
cfs.add(info.requiredResult);
}
}
return CompletableFuture.allOf(cfs.toArray(new CompletableFuture<?>[cfs.size()]));
}
}
}
private static <T> T waitForFuture(Future<T> future) throws TypeScriptException {
try {
return future.get(5000, TimeUnit.MILLISECONDS);
} catch (ExecutionException e) {
Throwable cause = e.getCause();
if (cause instanceof TypeScriptException) {
throw (TypeScriptException) cause;
}
throw new TypeScriptException(cause);
} catch (Exception e) {
throw new TypeScriptException(e);
}
}
private TypeScriptException createException(String message) {
if (NO_CONTENT_AVAILABLE.equals(message)) {
return new TypeScriptNoContentAvailableException(message);
}
return new TypeScriptException(message);
}
private void sendRequest(Request<?> request) throws TypeScriptException {
String req = GsonHelper.DEFAULT_GSON.toJson(request);
handleRequest(request, req);
getProcess().sendRequest(req);
}
private INodejsProcess getProcess() throws TypeScriptException {
if (!process.isStarted()) {
process.start();
}
return process;
}
@Override
public void addClientListener(ITypeScriptClientListener listener) {
synchronized (listeners) {
listeners.add(listener);
}
}
@Override
public void removeClientListener(ITypeScriptClientListener listener) {
synchronized (listeners) {
listeners.remove(listener);
}
}
private void fireStartServer() {
synchronized (listeners) {
for (ITypeScriptClientListener listener : listeners) {
listener.onStart(this);
}
}
}
private void fireEndServer() {
synchronized (listeners) {
for (ITypeScriptClientListener listener : listeners) {
listener.onStop(this);
}
}
}
@Override
public void addInstallTypesListener(IInstallTypesListener listener) {
synchronized (installTypesListener) {
installTypesListener.add(listener);
}
}
@Override
public void removeInstallTypesListener(IInstallTypesListener listener) {
synchronized (installTypesListener) {
installTypesListener.remove(listener);
}
}
private void fireBeginInstallTypes(BeginInstallTypesEventBody body) {
synchronized (installTypesListener) {
for (IInstallTypesListener listener : installTypesListener) {
listener.onBegin(body);
}
}
}
private void fireEndInstallTypes(EndInstallTypesEventBody body) {
synchronized (installTypesListener) {
for (IInstallTypesListener listener : installTypesListener) {
listener.onEnd(body);
}
}
}
private void fireLogTelemetry(String telemetryEventName, JsonObject payload) {
synchronized (installTypesListener) {
for (IInstallTypesListener listener : installTypesListener) {
listener.logTelemetry(telemetryEventName, payload);
}
}
}
@Override
public void addInterceptor(IInterceptor interceptor) {
beginWriteState();
try {
if (interceptors == null) {
interceptors = new ArrayList<IInterceptor>();
}
interceptors.add(interceptor);
} finally {
endWriteState();
}
}
@Override
public void removeInterceptor(IInterceptor interceptor) {
beginWriteState();
try {
if (interceptors != null) {
interceptors.remove(interceptor);
}
} finally {
endWriteState();
}
}
public void addProcessListener(INodejsProcessListener listener) {
beginWriteState();
try {
if (nodeListeners == null) {
nodeListeners = new ArrayList<INodejsProcessListener>();
}
nodeListeners.add(listener);
if (process != null) {
process.addProcessListener(listener);
}
} finally {
endWriteState();
}
}
public void removeProcessListener(INodejsProcessListener listener) {
beginWriteState();
try {
if (nodeListeners != null && listener != null) {
nodeListeners.remove(listener);
}
if (process != null) {
process.removeProcessListener(listener);
}
} finally {
endWriteState();
}
}
@Override
public void join() throws InterruptedException {
if (process != null) {
this.process.join();
}
}
@Override
public boolean isDisposed() {
return dispose;
}
@Override
public final void dispose() {
beginWriteState();
try {
if (!isDisposed()) {
this.dispose = true;
if (process != null) {
process.kill();
}
this.process = null;
}
} finally {
endWriteState();
}
}
private void beginReadState() {
stateLock.readLock().lock();
}
private void endReadState() {
stateLock.readLock().unlock();
}
private void beginWriteState() {
stateLock.writeLock().lock();
}
private void endWriteState() {
stateLock.writeLock().unlock();
}
public void setCompletionEntryMatcherProvider(ICompletionEntryMatcherProvider completionEntryMatcherProvider) {
this.completionEntryMatcherProvider = completionEntryMatcherProvider;
}
public ICompletionEntryMatcherProvider getCompletionEntryMatcherProvider() {
return completionEntryMatcherProvider;
}
/**
* Handle the given request.
*
* @param request
*/
private void handleRequest(Request<?> request, String json) {
if (interceptors == null) {
return;
}
for (IInterceptor interceptor : interceptors) {
interceptor.handleRequest(request, json, this);
}
}
/**
* Handle the given reponse.
*
* @param request
* @param response
* @param startTime
*/
private void handleResponse(Response<?> response, String json, long startTime) {
if (interceptors == null) {
return;
}
long ellapsedTime = getElapsedTimeInMs(startTime);
for (IInterceptor interceptor : interceptors) {
interceptor.handleResponse(response, json, ellapsedTime, this);
}
}
/**
* Handle the given error.
*
* @param request
* @param e
* @param startTime
*/
private void handleError(String command, Throwable e, long startTime) {
if (interceptors == null) {
return;
}
long ellapsedTime = getElapsedTimeInMs(startTime);
for (IInterceptor interceptor : interceptors) {
interceptor.handleError(e, this, command, ellapsedTime);
}
}
/**
* Returns the elappsed time in ms.
*
* @param startTime
* in nano time.
* @return the elappsed time in ms.
*/
private static long getElapsedTimeInMs(long startTime) {
return ((System.nanoTime() - startTime) / 1000000L);
}
} |
package org.jdesktop.swingx;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.LayoutManager;
/**
* Organizes components in a vertical layout.
*
* @author fred
*/
public class VerticalLayout implements LayoutManager {
private int gap = 0;
public VerticalLayout() {}
public VerticalLayout(int gap) {
this.gap = gap;
}
public int getGap() {
return gap;
}
public void setGap(int gap) {
this.gap = gap;
}
public void addLayoutComponent(String name, Component c) {}
public void layoutContainer(Container parent) {
Insets insets = parent.getInsets();
Dimension size = parent.getSize();
int width = size.width - insets.left - insets.right;
int height = insets.top;
for (int i = 0, c = parent.getComponentCount(); i < c; i++) {
Component m = parent.getComponent(i);
if (m.isVisible()) {
m.setBounds(insets.left, height, width, m.getPreferredSize().height);
height += m.getSize().height + gap;
}
}
}
public Dimension minimumLayoutSize(Container parent) {
return preferredLayoutSize(parent);
}
public Dimension preferredLayoutSize(Container parent) {
Insets insets = parent.getInsets();
Dimension pref = new Dimension(0, 0);
for (int i = 0, c = parent.getComponentCount(); i < c; i++) {
Component m = parent.getComponent(i);
if (m.isVisible()) {
Dimension componentPreferredSize =
parent.getComponent(i).getPreferredSize();
pref.height += componentPreferredSize.height + gap;
pref.width = Math.max(pref.width, componentPreferredSize.width);
}
}
pref.width += insets.left + insets.right;
pref.height += insets.top + insets.bottom;
return pref;
}
public void removeLayoutComponent(Component c) {}
} |
package picard.sam;
import htsjdk.samtools.BAMRecordCodec;
import htsjdk.samtools.Cigar;
import htsjdk.samtools.CigarElement;
import htsjdk.samtools.CigarOperator;
import htsjdk.samtools.ReservedTagConstants;
import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMFileHeader.SortOrder;
import htsjdk.samtools.SAMFileWriter;
import htsjdk.samtools.SAMFileWriterFactory;
import htsjdk.samtools.SAMProgramRecord;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SAMRecordCoordinateComparator;
import htsjdk.samtools.SAMRecordQueryNameComparator;
import htsjdk.samtools.SAMRecordUtil;
import htsjdk.samtools.SAMSequenceDictionary;
import htsjdk.samtools.SAMSequenceRecord;
import htsjdk.samtools.SAMTag;
import htsjdk.samtools.SAMUtils;
import htsjdk.samtools.SamPairUtil;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.filter.FilteringIterator;
import htsjdk.samtools.filter.SamRecordFilter;
import htsjdk.samtools.reference.ReferenceSequenceFileWalker;
import htsjdk.samtools.util.CigarUtil;
import htsjdk.samtools.util.CloseableIterator;
import htsjdk.samtools.util.CloserUtil;
import htsjdk.samtools.util.IOUtil;
import htsjdk.samtools.util.Log;
import htsjdk.samtools.util.ProgressLogger;
import htsjdk.samtools.util.SequenceUtil;
import htsjdk.samtools.util.SortingCollection;
import picard.PicardException;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public abstract class AbstractAlignmentMerger {
public static final int MAX_RECORDS_IN_RAM = 500000;
private static final char[] RESERVED_ATTRIBUTE_STARTS = {'X', 'Y', 'Z'};
private final Log log = Log.getInstance(AbstractAlignmentMerger.class);
private final ProgressLogger progress = new ProgressLogger(this.log, 1000000, "Merged", "records");
private final File unmappedBamFile;
private final File targetBamFile;
private final SAMSequenceDictionary sequenceDictionary;
private ReferenceSequenceFileWalker refSeq = null;
private final boolean clipAdapters;
private final boolean bisulfiteSequence;
private SAMProgramRecord programRecord;
private final boolean alignedReadsOnly;
private final SAMFileHeader header;
private final List<String> attributesToRetain = new ArrayList<String>();
private final List<String> attributesToRemove = new ArrayList<String>();
protected final File referenceFasta;
private final Integer read1BasesTrimmed;
private final Integer read2BasesTrimmed;
private final List<SamPairUtil.PairOrientation> expectedOrientations;
private final SortOrder sortOrder;
private MultiHitAlignedReadIterator alignedIterator = null;
private boolean clipOverlappingReads = true;
private int maxRecordsInRam = MAX_RECORDS_IN_RAM;
private final PrimaryAlignmentSelectionStrategy primaryAlignmentSelectionStrategy;
private boolean keepAlignerProperPairFlags = false;
private boolean addMateCigar = false;
private final SamRecordFilter alignmentFilter = new SamRecordFilter() {
public boolean filterOut(final SAMRecord record) {
return ignoreAlignment(record);
}
public boolean filterOut(final SAMRecord first, final SAMRecord second) {
throw new UnsupportedOperationException("Paired SamRecordFilter not implemented!");
}
};
private boolean includeSecondaryAlignments = true;
/** Class that allows a Sorting Collection and a SAMFileWriter to be treated identically. */
private static class Sink {
private final SAMFileWriter writer;
private final SortingCollection<SAMRecord> sorter;
/** Constructs a sink that outputs to a SAMFileWriter. */
public Sink(final SAMFileWriter writer) {
this.writer = writer;
this.sorter = null;
}
/** Constructs a sink that outputs to a Sorting Collection. */
public Sink(final SortingCollection<SAMRecord> sorter) {
this.writer = null;
this.sorter = sorter;
}
/** Adds a record to the sink. */
void add(final SAMRecord rec) {
if (writer != null) writer.addAlignment(rec);
if (sorter != null) sorter.add(rec);
}
/** Closes the underlying resource. */
void close() {
if (this.writer != null) this.writer.close();
if (this.sorter != null) this.sorter.doneAdding();
}
}
protected abstract CloseableIterator<SAMRecord> getQuerynameSortedAlignedRecords();
protected boolean ignoreAlignment(final SAMRecord sam) { return false; } // default implementation
/**
* Constructor
*
* @param unmappedBamFile The BAM file that was used as the input to the aligner, which will
* include info on all the reads that did not map. Required.
* @param targetBamFile The file to which to write the merged SAM records. Required.
* @param referenceFasta The reference sequence for the map files. Required.
* @param clipAdapters Whether adapters marked in unmapped BAM file should be marked as
* soft clipped in the merged bam. Required.
* @param bisulfiteSequence Whether the reads are bisulfite sequence (used when calculating the
* NM and UQ tags). Required.
* @param alignedReadsOnly Whether to output only those reads that have alignment data
* @param programRecord Program record for target file SAMRecords created.
* @param attributesToRetain private attributes from the alignment record that should be
* included when merging. This overrides the exclusion of
* attributes whose tags start with the reserved characters
* of X, Y, and Z
* @param attributesToRemove attributes from the alignment record that should be
* removed when merging. This overrides attributesToRetain if they share
* common tags.
* @param read1BasesTrimmed The number of bases trimmed from start of read 1 prior to alignment. Optional.
* @param read2BasesTrimmed The number of bases trimmed from start of read 2 prior to alignment. Optional.
* @param expectedOrientations A List of SamPairUtil.PairOrientations that are expected for
* aligned pairs. Used to determine the properPair flag.
* @param sortOrder The order in which the merged records should be output. If null,
* output will be coordinate-sorted
* @param primaryAlignmentSelectionStrategy What to do when there are multiple primary alignments, or multiple
* alignments but none primary, for a read or read pair.
* @param addMateCigar True if we are to add or maintain the mate CIGAR (MC) tag, false if we are to remove or not include.
*/
public AbstractAlignmentMerger(final File unmappedBamFile, final File targetBamFile,
final File referenceFasta, final boolean clipAdapters,
final boolean bisulfiteSequence, final boolean alignedReadsOnly,
final SAMProgramRecord programRecord, final List<String> attributesToRetain,
final List<String> attributesToRemove,
final Integer read1BasesTrimmed, final Integer read2BasesTrimmed,
final List<SamPairUtil.PairOrientation> expectedOrientations,
final SAMFileHeader.SortOrder sortOrder,
final PrimaryAlignmentSelectionStrategy primaryAlignmentSelectionStrategy,
final boolean addMateCigar) {
IOUtil.assertFileIsReadable(unmappedBamFile);
IOUtil.assertFileIsWritable(targetBamFile);
IOUtil.assertFileIsReadable(referenceFasta);
this.unmappedBamFile = unmappedBamFile;
this.targetBamFile = targetBamFile;
this.referenceFasta = referenceFasta;
this.refSeq = new ReferenceSequenceFileWalker(referenceFasta);
this.sequenceDictionary = refSeq.getSequenceDictionary();
if (this.sequenceDictionary == null) {
throw new PicardException("No sequence dictionary found for " + referenceFasta.getAbsolutePath() +
". Use CreateSequenceDictionary.jar to create a sequence dictionary.");
}
this.clipAdapters = clipAdapters;
this.bisulfiteSequence = bisulfiteSequence;
this.alignedReadsOnly = alignedReadsOnly;
this.header = new SAMFileHeader();
this.sortOrder = sortOrder != null ? sortOrder : SortOrder.coordinate;
header.setSortOrder(SortOrder.coordinate);
if (programRecord != null) {
setProgramRecord(programRecord);
}
header.setSequenceDictionary(this.sequenceDictionary);
if (attributesToRetain != null) {
this.attributesToRetain.addAll(attributesToRetain);
}
if (attributesToRemove != null) {
this.attributesToRemove.addAll(attributesToRemove);
// attributesToRemove overrides attributesToRetain
if (!this.attributesToRetain.isEmpty()) {
for (String attribute : this.attributesToRemove) {
if (this.attributesToRetain.contains(attribute)) {
log.info("Overriding retaining the " + attribute + " tag since remove overrides retain.");
this.attributesToRetain.remove(attribute);
}
}
}
}
this.read1BasesTrimmed = read1BasesTrimmed;
this.read2BasesTrimmed = read2BasesTrimmed;
this.expectedOrientations = expectedOrientations;
this.primaryAlignmentSelectionStrategy = primaryAlignmentSelectionStrategy;
this.addMateCigar = addMateCigar;
}
/** Allows the caller to override the maximum records in RAM. */
public void setMaxRecordsInRam(final int maxRecordsInRam) {
this.maxRecordsInRam = maxRecordsInRam;
}
/**
* Do this unconditionally, not just for aligned records, for two reasons:
* - An unaligned read has been processed by the aligner, so it is more truthful.
* - When chaining additional PG records, having all the records in the output file refer to the same PG
* record means that only one chain will need to be created, rather than a chain for the mapped reads
* and a separate chain for the unmapped reads.
*/
private void maybeSetPgTag(final SAMRecord rec) {
if (this.programRecord != null) {
rec.setAttribute(ReservedTagConstants.PROGRAM_GROUP_ID, this.programRecord.getProgramGroupId());
}
}
* /**
* Merges the alignment data with the non-aligned records from the source BAM file.
*/
public void mergeAlignment(final File referenceFasta) {
// Open the file of unmapped records and write the read groups to the the header for the merged file
final SamReader unmappedSam = SamReaderFactory.makeDefault().referenceSequence(referenceFasta).open(this.unmappedBamFile);
final CloseableIterator<SAMRecord> unmappedIterator = unmappedSam.iterator();
this.header.setReadGroups(unmappedSam.getFileHeader().getReadGroups());
int aligned = 0;
int unmapped = 0;
// Get the aligned records and set up the first one
alignedIterator = new MultiHitAlignedReadIterator(new FilteringIterator(getQuerynameSortedAlignedRecords(), alignmentFilter), primaryAlignmentSelectionStrategy);
HitsForInsert nextAligned = nextAligned();
// Check that the program record we are going to insert is not already used in the unmapped SAM
// Must come after calling getQuerynameSortedAlignedRecords() in case opening the aligned records
// sets the program group
if (getProgramRecord() != null) {
for (final SAMProgramRecord pg : unmappedSam.getFileHeader().getProgramRecords()) {
if (pg.getId().equals(getProgramRecord().getId())) {
throw new PicardException("Program Record ID already in use in unmapped BAM file.");
}
}
}
// If the output requested is coordinate order then run everything through a sorting collection
// in order to have access to the records in coordinate order prior to outputting them. Otherwise
// write directly to the output BAM file in queryname order.
final Sink sink;
if (this.sortOrder == SortOrder.coordinate) {
final SortingCollection<SAMRecord> sorted1 = SortingCollection.newInstance(
SAMRecord.class, new BAMRecordCodec(header), new SAMRecordCoordinateComparator(),
MAX_RECORDS_IN_RAM);
sink = new Sink(sorted1);
}
else { // catches queryname and unsorted
final SAMFileHeader header = this.header.clone();
header.setSortOrder(this.sortOrder);
final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, true, this.targetBamFile);
writer.setProgressLogger(new ProgressLogger(log, (int) 1e7, "Wrote", "records to output in queryname order"));
sink = new Sink(writer);
}
while (unmappedIterator.hasNext()) {
// Load next unaligned read or read pair.
final SAMRecord rec = unmappedIterator.next();
rec.setHeader(this.header);
maybeSetPgTag(rec);
final SAMRecord secondOfPair;
if (rec.getReadPairedFlag()) {
secondOfPair = unmappedIterator.next();
secondOfPair.setHeader(this.header);
maybeSetPgTag(secondOfPair);
// Validate that paired reads arrive as first of pair followed by second of pair
if (!rec.getReadName().equals(secondOfPair.getReadName()))
throw new PicardException("Second read from pair not found in unmapped bam: " + rec.getReadName() + ", " + secondOfPair.getReadName());
if (!rec.getFirstOfPairFlag())
throw new PicardException("First record in unmapped bam is not first of pair: " + rec.getReadName());
if (!secondOfPair.getReadPairedFlag())
throw new PicardException("Second record in unmapped bam is not marked as paired: " + secondOfPair.getReadName());
if (!secondOfPair.getSecondOfPairFlag())
throw new PicardException("Second record in unmapped bam is not second of pair: " + secondOfPair.getReadName());
} else {
secondOfPair = null;
}
// See if there are alignments for current unaligned read or read pair.
if (nextAligned != null && rec.getReadName().equals(nextAligned.getReadName())) {
// If there are multiple alignments for a read (pair), then the unaligned SAMRecord must be cloned
// before copying info from the aligned record to the unaligned.
final boolean clone = nextAligned.numHits() > 1 || nextAligned.hasSupplementalHits();
SAMRecord r1Primary = null, r2Primary = null;
if (rec.getReadPairedFlag()) {
for (int i = 0; i < nextAligned.numHits(); ++i) {
// firstAligned or secondAligned may be null, if there wasn't an alignment for the end,
// or if the alignment was rejected by ignoreAlignment.
final SAMRecord firstAligned = nextAligned.getFirstOfPair(i);
final SAMRecord secondAligned = nextAligned.getSecondOfPair(i);
final boolean isPrimaryAlignment = (firstAligned != null && !firstAligned.isSecondaryOrSupplementary()) ||
(secondAligned != null && !secondAligned.isSecondaryOrSupplementary());
final SAMRecord firstToWrite;
final SAMRecord secondToWrite;
if (clone) {
firstToWrite = clone(rec);
secondToWrite = clone(secondOfPair);
} else {
firstToWrite = rec;
secondToWrite = secondOfPair;
}
// If these are the primary alignments then stash them for use on any supplemental alignments
if (isPrimaryAlignment) {
r1Primary = firstToWrite;
r2Primary = secondToWrite;
}
transferAlignmentInfoToPairedRead(firstToWrite, secondToWrite, firstAligned, secondAligned);
// Only write unmapped read when it has the mate info from the primary alignment.
if (!firstToWrite.getReadUnmappedFlag() || isPrimaryAlignment) {
addIfNotFiltered(sink, firstToWrite);
if (firstToWrite.getReadUnmappedFlag()) ++unmapped;
else ++aligned;
}
if (!secondToWrite.getReadUnmappedFlag() || isPrimaryAlignment) {
addIfNotFiltered(sink, secondToWrite);
if (!secondToWrite.getReadUnmappedFlag()) ++aligned;
else ++unmapped;
}
}
// Take all of the supplemental reads which had been stashed and add them (as appropriate) to sorted
for (final boolean isRead1 : new boolean[]{true, false}) {
final List<SAMRecord> supplementals = isRead1 ? nextAligned.getSupplementalFirstOfPairOrFragment() : nextAligned.getSupplementalSecondOfPair();
final SAMRecord sourceRec = isRead1 ? rec : secondOfPair;
final SAMRecord matePrimary = isRead1 ? r2Primary : r1Primary;
for (final SAMRecord supp : supplementals) {
final SAMRecord out = clone(sourceRec);
transferAlignmentInfoToFragment(out, supp);
if (matePrimary != null) SamPairUtil.setMateInformationOnSupplementalAlignment(out, matePrimary, addMateCigar);
++aligned;
addIfNotFiltered(sink, out);
}
}
} else {
for (int i = 0; i < nextAligned.numHits(); ++i) {
final SAMRecord recToWrite = clone ? clone(rec) : rec;
transferAlignmentInfoToFragment(recToWrite, nextAligned.getFragment(i));
addIfNotFiltered(sink, recToWrite);
if (recToWrite.getReadUnmappedFlag()) ++unmapped;
else ++aligned;
}
// Take all of the supplemental reads which had been stashed and add them (as appropriate) to sorted
for (final SAMRecord supplementalRec : nextAligned.getSupplementalFirstOfPairOrFragment()) {
final SAMRecord recToWrite = clone(rec);
transferAlignmentInfoToFragment(recToWrite, supplementalRec);
addIfNotFiltered(sink, recToWrite);
++aligned;
}
}
nextAligned = nextAligned();
} else {
// There was no alignment for this read or read pair.
if (nextAligned != null &&
SAMRecordQueryNameComparator.compareReadNames(rec.getReadName(), nextAligned.getReadName()) > 0) {
throw new IllegalStateException("Aligned record iterator (" + nextAligned.getReadName() +
") is behind the unmapped reads (" + rec.getReadName() + ")");
}
// No matching read from alignedIterator -- just output reads as is.
if (!alignedReadsOnly) {
sink.add(rec);
++unmapped;
if (secondOfPair != null) {
sink.add(secondOfPair);
++unmapped;
}
}
}
}
unmappedIterator.close();
if (alignedIterator.hasNext()) {
throw new IllegalStateException("Reads remaining on alignment iterator: " + alignedIterator.next().getReadName() + "!");
}
alignedIterator.close();
sink.close();
// Write the records to the output file in specified sorted order,
if (this.sortOrder == SortOrder.coordinate) {
header.setSortOrder(this.sortOrder);
final SAMFileWriter writer = new SAMFileWriterFactory().makeSAMOrBAMWriter(header, true, this.targetBamFile);
writer.setProgressLogger(new ProgressLogger(log, (int) 1e7, "Wrote", "records from a sorting collection"));
final ProgressLogger finalProgress = new ProgressLogger(log, 10000000, "Written in coordinate order to output", "records");
for (final SAMRecord rec : sink.sorter) {
if (!rec.getReadUnmappedFlag()) {
if (refSeq != null) {
final byte[] referenceBases = refSeq.get(sequenceDictionary.getSequenceIndex(rec.getReferenceName())).getBases();
rec.setAttribute(SAMTag.NM.name(), SequenceUtil.calculateSamNmTag(rec, referenceBases, 0, bisulfiteSequence));
if (rec.getBaseQualities() != SAMRecord.NULL_QUALS) {
rec.setAttribute(SAMTag.UQ.name(), SequenceUtil.sumQualitiesOfMismatches(rec, referenceBases, 0, bisulfiteSequence));
}
}
}
writer.addAlignment(rec);
finalProgress.record(rec);
}
writer.close();
sink.sorter.cleanup();
}
CloserUtil.close(unmappedSam);
log.info("Wrote " + aligned + " alignment records and " + (alignedReadsOnly ? 0 : unmapped) + " unmapped reads.");
}
/**
* Add record if it is primary or optionally secondary.
*/
private void addIfNotFiltered(final Sink out, final SAMRecord rec) {
if (includeSecondaryAlignments || !rec.getNotPrimaryAlignmentFlag()) {
out.add(rec);
this.progress.record(rec);
}
}
private SAMRecord clone(final SAMRecord rec) {
try {
return (SAMRecord) rec.clone();
} catch (CloneNotSupportedException e) {
throw new PicardException("Should never happen.");
}
}
/**
* @return Next read's alignment(s) from aligned input or null, if there are no more.
* The alignments are run through ignoreAlignment() filter before being returned, which may result
* in an entire read being skipped if all alignments for that read should be ignored.
*/
private HitsForInsert nextAligned() {
if (alignedIterator.hasNext()) return alignedIterator.next();
return null;
}
/**
* Copies alignment info from aligned to unaligned read, clips as appropriate, and sets PG ID.
*
* @param unaligned Original SAMRecord, and object into which values are copied.
* @param aligned Holds alignment info that will be copied into unaligned.
*/
private void transferAlignmentInfoToFragment(final SAMRecord unaligned, final SAMRecord aligned) {
setValuesFromAlignment(unaligned, aligned);
updateCigarForTrimmedOrClippedBases(unaligned, aligned);
if (SAMUtils.cigarMapsNoBasesToRef(unaligned.getCigar())) {
SAMUtils.makeReadUnmapped(unaligned);
} else if (SAMUtils.recordMapsEntirelyBeyondEndOfReference(aligned)) {
log.warn("Record mapped off end of reference; making unmapped: " + aligned);
SAMUtils.makeReadUnmapped(unaligned);
}
}
/**
* Copies alignment info from aligned to unaligned read, if there is an alignment, and sets mate information.
*
* @param firstUnaligned Original first of pair, into which alignment and pair info will be written.
* @param secondUnaligned Original second of pair, into which alignment and pair info will be written.
* @param firstAligned Aligned first of pair, or null if no alignment.
* @param secondAligned Aligned second of pair, or null if no alignment.
*/
private void transferAlignmentInfoToPairedRead(final SAMRecord firstUnaligned, final SAMRecord secondUnaligned, final SAMRecord firstAligned, final SAMRecord secondAligned) {
if (firstAligned != null) transferAlignmentInfoToFragment(firstUnaligned, firstAligned);
if (secondAligned != null) transferAlignmentInfoToFragment(secondUnaligned, secondAligned);
if (isClipOverlappingReads()) clipForOverlappingReads(firstUnaligned, secondUnaligned);
SamPairUtil.setMateInfo(secondUnaligned, firstUnaligned, header, addMateCigar);
if (!keepAlignerProperPairFlags) {
SamPairUtil.setProperPairFlags(secondUnaligned, firstUnaligned, expectedOrientations);
}
}
/**
* Checks to see whether the ends of the reads overlap and soft clips reads
* them if necessary.
*/
protected void clipForOverlappingReads(final SAMRecord read1, final SAMRecord read2) {
// If both reads are mapped, see if we need to clip the ends due to small
// insert size
if (!(read1.getReadUnmappedFlag() || read2.getReadUnmappedFlag())) {
if (read1.getReadNegativeStrandFlag() != read2.getReadNegativeStrandFlag()) {
final SAMRecord pos = (read1.getReadNegativeStrandFlag()) ? read2 : read1;
final SAMRecord neg = (read1.getReadNegativeStrandFlag()) ? read1 : read2;
// Innies only -- do we need to do anything else about jumping libraries?
if (pos.getAlignmentStart() < neg.getAlignmentEnd()) {
final int posDiff = pos.getAlignmentEnd() - neg.getAlignmentEnd();
final int negDiff = pos.getAlignmentStart() - neg.getAlignmentStart();
if (posDiff > 0) {
CigarUtil.softClip3PrimeEndOfRead(pos, Math.min(pos.getReadLength(),
pos.getReadLength() - posDiff + 1));
}
if (negDiff > 0) {
CigarUtil.softClip3PrimeEndOfRead(neg, Math.min(neg.getReadLength(),
neg.getReadLength() - negDiff + 1));
}
}
} else {
// TODO: What about RR/FF pairs?
}
}
}
/**
* Sets the values from the alignment record on the unaligned BAM record. This
* preserves all data from the unaligned record (ReadGroup, NoiseRead status, etc)
* and adds all the alignment info
*
* @param rec The unaligned read record
* @param alignment The alignment record
*/
protected void setValuesFromAlignment(final SAMRecord rec, final SAMRecord alignment) {
for (final SAMRecord.SAMTagAndValue attr : alignment.getAttributes()) {
// Copy over any non-reserved attributes. attributesToRemove overrides attributesToRetain.
if ((!isReservedTag(attr.tag) || this.attributesToRetain.contains(attr.tag)) && !this.attributesToRemove.contains(attr.tag)) {
rec.setAttribute(attr.tag, attr.value);
}
}
rec.setReadUnmappedFlag(alignment.getReadUnmappedFlag());
// Note that it is important to get reference names rather than indices in case the sequence dictionaries
// in the two files are in different orders.
rec.setReferenceName(alignment.getReferenceName());
rec.setAlignmentStart(alignment.getAlignmentStart());
rec.setReadNegativeStrandFlag(alignment.getReadNegativeStrandFlag());
rec.setNotPrimaryAlignmentFlag(alignment.getNotPrimaryAlignmentFlag());
rec.setSupplementaryAlignmentFlag(alignment.getSupplementaryAlignmentFlag());
if (!alignment.getReadUnmappedFlag()) {
// only aligned reads should have cigar and mapping quality set
rec.setCigar(alignment.getCigar()); // cigar may change when a
// clipCigar called below
rec.setMappingQuality(alignment.getMappingQuality());
}
if (rec.getReadPairedFlag()) {
rec.setProperPairFlag(alignment.getProperPairFlag());
// Mate info and alignment size will get set by the ClippedPairFixer.
}
// If it's on the negative strand, reverse complement the bases
// and reverse the order of the qualities
if (rec.getReadNegativeStrandFlag()) {
SAMRecordUtil.reverseComplement(rec);
}
}
private static Cigar createNewCigarIfMapsOffEndOfReference(SAMFileHeader header,
boolean isUnmapped,
int referenceIndex,
int alignmentEnd,
int readLength,
Cigar oldCigar) {
Cigar newCigar = null;
if (!isUnmapped) {
final SAMSequenceRecord refseq = header.getSequence(referenceIndex);
final int overhang = alignmentEnd - refseq.getSequenceLength();
if (overhang > 0) {
// 1-based index of first base in read to clip.
int clipFrom = readLength - overhang + 1;
// we have to check if the last element is soft-clipping, so we can subtract that from clipFrom
final CigarElement cigarElement = oldCigar.getCigarElement(oldCigar.getCigarElements().size()-1);
if (CigarOperator.SOFT_CLIP == cigarElement.getOperator()) clipFrom -= cigarElement.getLength();
final List<CigarElement> newCigarElements = CigarUtil.softClipEndOfRead(clipFrom, oldCigar.getCigarElements());
newCigar = new Cigar(newCigarElements);
}
}
return newCigar;
}
/**
* Soft-clip an alignment that hangs off the end of its reference sequence. Checks both the read and its mate,
* if available.
*
* @param rec
*/
public static void createNewCigarsIfMapsOffEndOfReference(final SAMRecord rec) {
// If the read maps off the end of the alignment, clip it
if (!rec.getReadUnmappedFlag()) {
final Cigar readCigar = createNewCigarIfMapsOffEndOfReference(rec.getHeader(),
rec.getReadUnmappedFlag(),
rec.getReferenceIndex(),
rec.getAlignmentEnd(),
rec.getReadLength(),
rec.getCigar());
if (null != readCigar) rec.setCigar(readCigar);
}
// If the read's mate maps off the end of the alignment, clip it
if (SAMUtils.hasMateCigar(rec)) {
Cigar mateCigar = SAMUtils.getMateCigar(rec);
mateCigar = createNewCigarIfMapsOffEndOfReference(rec.getHeader(),
rec.getMateUnmappedFlag(),
rec.getMateReferenceIndex(),
SAMUtils.getMateAlignmentEnd(rec), // NB: this could be computed without another call to getMateCigar
mateCigar.getReadLength(),
mateCigar);
if (null != mateCigar) rec.setAttribute(SAMTag.MC.name(), mateCigar.toString());
}
}
protected void updateCigarForTrimmedOrClippedBases(final SAMRecord rec, final SAMRecord alignment) {
// If the read was trimmed or not all the bases were sent for alignment, clip it
final int alignmentReadLength = alignment.getReadLength();
final int originalReadLength = rec.getReadLength();
final int trimmed = (!rec.getReadPairedFlag()) || rec.getFirstOfPairFlag()
? this.read1BasesTrimmed != null ? this.read1BasesTrimmed : 0
: this.read2BasesTrimmed != null ? this.read2BasesTrimmed : 0;
final int notWritten = originalReadLength - (alignmentReadLength + trimmed);
// Update cigar if the mate maps off the reference
createNewCigarsIfMapsOffEndOfReference(rec);
rec.setCigar(CigarUtil.addSoftClippedBasesToEndsOfCigar(
rec.getCigar(), rec.getReadNegativeStrandFlag(), notWritten, trimmed));
// If the adapter sequence is marked and clipAdapter is true, clip it
if (this.clipAdapters && rec.getAttribute(ReservedTagConstants.XT) != null) {
CigarUtil.softClip3PrimeEndOfRead(rec, rec.getIntegerAttribute(ReservedTagConstants.XT));
}
}
protected SAMSequenceDictionary getSequenceDictionary() { return this.sequenceDictionary; }
protected SAMProgramRecord getProgramRecord() { return this.programRecord; }
protected void setProgramRecord(final SAMProgramRecord pg) {
if (this.programRecord != null) {
throw new IllegalStateException("Cannot set program record more than once on alignment merger.");
}
this.programRecord = pg;
this.header.addProgramRecord(pg);
SAMUtils.chainSAMProgramRecord(header, pg);
}
protected boolean isReservedTag(final String tag) {
final char firstCharOfTag = tag.charAt(0);
// All tags that start with a lower-case letter are user defined and should not be overridden by aligner
// unless explicitly specified in attributesToRetain.
if (Character.isLowerCase(firstCharOfTag)) return true;
for (final char c : RESERVED_ATTRIBUTE_STARTS) {
if (firstCharOfTag == c) return true;
}
return false;
}
protected SAMFileHeader getHeader() { return this.header; }
protected void resetRefSeqFileWalker() {
this.refSeq = new ReferenceSequenceFileWalker(referenceFasta);
}
public boolean isClipOverlappingReads() {
return clipOverlappingReads;
}
public void setClipOverlappingReads(final boolean clipOverlappingReads) {
this.clipOverlappingReads = clipOverlappingReads;
}
public boolean isKeepAlignerProperPairFlags() {
return keepAlignerProperPairFlags;
}
/**
* If true, keep the aligner's idea of proper pairs rather than letting alignment merger decide.
*/
public void setKeepAlignerProperPairFlags(final boolean keepAlignerProperPairFlags) {
this.keepAlignerProperPairFlags = keepAlignerProperPairFlags;
}
public void setIncludeSecondaryAlignments(final boolean includeSecondaryAlignments) {
this.includeSecondaryAlignments = includeSecondaryAlignments;
}
public void close() {
CloserUtil.close(this.refSeq);
}
} |
package jsettlers.common.map.shapes;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import jsettlers.common.position.ISPosition2D;
import jsettlers.common.position.RelativePoint;
import jsettlers.common.position.SRectangle;
/**
* This class gives a fast lookup (in O(1)) for contains if a MapArea is given
* by a list of n positions.<br>
* This class should only be used if the given positions are NOT distributed
* over big parts of the map. They should be positioned quite close to each
* other.
*
* @author Andreas Eberle
*/
public class FreeMapArea implements IMapArea {
private final List<ISPosition2D> positions;
private final short xOffset;
private final short yOffset;
private final boolean[][] areaMap;
private final int width;
private final int height;
/**
* @param positions
* the positions this map area shall contain.
*/
public FreeMapArea(List<ISPosition2D> positions) {
assert positions.size() > 0 : "positions must contain at least one value!!";
this.positions = positions;
SRectangle bounds = getBounds(positions);
xOffset = bounds.getXMin();
yOffset = bounds.getYMin();
width = bounds.getWidth() + 1;
height = bounds.getHeight() + 1;
areaMap = new boolean[width][height];
setPositionsToMap(areaMap, positions);
}
/**
* Creates a free map area by converting the relative points to absolute
* ones.
*
* @param pos The origin for the relative points
* @param relativePoints The relative points
*/
public FreeMapArea(ISPosition2D pos, RelativePoint[] relativePoints) {
this(convertRelative(pos, relativePoints));
}
private static LinkedList<ISPosition2D> convertRelative(ISPosition2D pos,
RelativePoint[] relativePoints) {
LinkedList<ISPosition2D> list = new LinkedList<ISPosition2D>();
for (RelativePoint relative : relativePoints) {
list.add(relative.calculatePoint(pos));
}
return list;
}
private void setPositionsToMap(boolean[][] areaMap,
List<ISPosition2D> positions2) {
for (ISPosition2D curr : positions) {
areaMap[getMapX(curr)][getMapY(curr)] = true;
}
}
private int getMapY(ISPosition2D pos) {
return pos.getY() - yOffset;
}
private int getMapX(ISPosition2D pos) {
return pos.getX() - xOffset;
}
private SRectangle getBounds(List<ISPosition2D> positions) {
short xMin = Short.MAX_VALUE, xMax = 0, yMin = Short.MAX_VALUE, yMax =
0;
for (ISPosition2D curr : positions) {
short x = curr.getX();
short y = curr.getY();
if (x < xMin)
xMin = x;
if (x > xMax)
xMax = x;
if (y < yMin)
yMin = y;
if (y > yMax)
yMax = y;
}
return new SRectangle(xMin, yMin, xMax, yMax);
}
@Override
public boolean contains(ISPosition2D pos) {
return isValidPos(pos) && areaMap[getMapX(pos)][getMapY(pos)];
}
private boolean isValidPos(ISPosition2D pos) {
int dx = pos.getX() - xOffset;
int dy = pos.getY() - yOffset;
return dx >= 0 && dy >= 0 && dx < width && dy < height;
}
@Override
public Iterator<ISPosition2D> iterator() {
return positions.iterator();
}
public int size() {
return positions.size();
}
public ISPosition2D get(int i) {
return positions.get(i);
}
} |
package logic;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
/**
* binary tree class
*
* @author Rico
*
*/
public class BinaryTree {
public static void main(String[] args) {
BinaryTree theTree = new BinaryTree();
theTree.addNode("50");
theTree.addNode("25");
theTree.addNode("15");
theTree.addNode("30");
theTree.addNode("75");
theTree.addNode("85");
theTree.saveTreeToFile("C:/Users/Rico/Documents/test.txt");
theTree.loadTreeFromFile("C:/Users/Rico/Documents/test.txt");
}
private Node root;
final static Charset ENCODING = StandardCharsets.UTF_8;
private String stringPath;
public void setStringPath(String path){
stringPath = path;
}
public String getStringPath(){
return stringPath;
}
public Boolean addNode(String data) {
// creates a new node
Node newNode = new Node(data);
// without a root node this will become root
if (root == null) {
root = newNode;
return true;
} else {
// sets root as starting point for traversing the tree
Node focusNode = root;
// future partent for new node
Node parent;
while (true) {
// start at top with root
parent = focusNode;
// check whether new node goes on left or right side
if (data.compareTo(focusNode.getData()) < 0) {
focusNode = focusNode.getLeftChild();
// if left child has no children
if (focusNode == null) {
// places new node on the left
parent.setLeftChild(newNode);
return true;
}
} else if (data.compareTo(focusNode.getData()) > 0) {
// puts node on right side
focusNode = focusNode.getRightChild();
// if right child has no children
if (focusNode == null) {
// place new ndoe on the right
parent.setRightChild(newNode);
return true;
}
// check if a duplicate node is being added
} else {
if (data.compareTo(focusNode.getData()) == 0) {
System.out.println("add: no duplicate nodes allowed");
return false;
}
}
}
}
}
public boolean deleteAll() {
root = null;
if (root == null) {
return true;
}
return false;
}
/**
* delete method for nodes
*
* @param data
* the node that the user wants to delete
* @return returns true if deletion was successful and false if it was not
*/
public boolean deleteNode(String data) {
Node focusNode = root;
Node parent = root;
boolean isItLeftChild = true;
if (root != null) {
while (focusNode.getData().compareTo(data) != 0) {
parent = focusNode;
if (data.compareTo(focusNode.getData()) < 0) {
isItLeftChild = true;
focusNode = focusNode.getLeftChild();
} else if (data.compareTo(focusNode.getData()) > 0) {
isItLeftChild = false;
focusNode = focusNode.getRightChild();
}
if (focusNode == null) {
return false;
}
}
// leaf node
if (focusNode.getLeftChild() == null && focusNode.getRightChild() == null) {
if (focusNode == root) {
root = null;
} else if (isItLeftChild) {
parent.setLeftChild(null);
} else {
parent.setRightChild(null);
}
// only left child
} else if (focusNode.getRightChild() == null) {
if (focusNode == root) {
root = focusNode.getLeftChild();
} else if (isItLeftChild) {
parent.setLeftChild(focusNode.getLeftChild());
} else {
parent.setRightChild(focusNode.getLeftChild());
}
// only right child
} else if (focusNode.getLeftChild() == null) {
if (focusNode == root) {
root = focusNode.getRightChild();
} else if (isItLeftChild) {
parent.setLeftChild(focusNode.getRightChild());
} else {
parent.setRightChild(focusNode.getRightChild());
}
// left and right child
} else {
Node replacement = getReplacementNode(focusNode);
if (focusNode == root) {
root = replacement;
} else if (isItLeftChild) {
parent.setLeftChild(replacement);
} else {
parent.setRightChild(replacement);
}
replacement.setLeftChild(focusNode.getLeftChild());
}
return true;
}
System.out.println("delete: node not found");
return false;
}
public Node findNode(String data) {
// starts at top of the tree
Node focusNode = root;
while (focusNode.getData().compareTo(data) != 0) {
if (data.compareTo(focusNode.getData()) < 0) {
focusNode = focusNode.getLeftChild();
} else if (data.compareTo(focusNode.getData()) > 0) {
focusNode = focusNode.getRightChild();
}
// if node is not found
if (focusNode == null) {
return null;
}
}
return focusNode;
}
public Node getRootNode() {
return root;
}
public boolean loadTreeFromFile(String stringPath) {
Path path = Paths.get(stringPath);
if (Files.isReadable(path)) {
try {
ArrayList<String> treeArray = new ArrayList<String>();
treeArray = (ArrayList<String>) Files.readAllLines(path, ENCODING);
System.out.println("loaded array");
System.out.println(treeArray.toString());
return true;
} catch (IOException e) {
System.out.println("Wasn't able to get content from file");
e.printStackTrace();
}
} else {
System.out.println("The path isn't valid");
}
return false;
}
public Boolean saveTreeToFile(String stringPath) {
Node focusNode = root;
ArrayList<String> treeArray = new ArrayList<String>();
preorderTraverseTree(focusNode, treeArray);
System.out.println(treeArray.toString());
System.out.println("save to file");
// TODO replace own code with production when finished
// fetch path string from console commit path to binary tree object for
// handling
Path storePath = Paths.get(stringPath);
System.out.println("Path to file: " + storePath);
if (!Files.isWritable(storePath)) {
try {
Files.createFile(storePath);
} catch (IOException e) {
System.out.println("Failed to create file:\n" + e);
e.printStackTrace();
return false;
}
}
try {
PrintWriter writer = new PrintWriter(new FileWriter(storePath.toString()));
for (String s : treeArray) {
writer.println(s);
}
writer.close();
} catch (IOException e) {
System.out.println("Failed to create FileWriter: " + e);
e.printStackTrace();
return false;
}
return true;
}
private void preorderTraverseTree(Node focusNode, ArrayList<String> list) {
if (focusNode != null && list != null) {
list.add(focusNode.getData());
preorderTraverseTree(focusNode.getLeftChild(), list);
preorderTraverseTree(focusNode.getRightChild(), list);
}
System.out.println(list.toString());
}
private Node getReplacementNode(Node replacedNode) {
Node replacementParent = replacedNode;
Node replacement = replacedNode;
Node focusNode = replacedNode.getRightChild();
while (focusNode != null) {
replacementParent = replacement;
replacement = focusNode;
focusNode = focusNode.getLeftChild();
}
System.out.println("Node to replace: " + replacedNode.toString());
System.out.println("Node to replacement parent: " + replacementParent.toString());
System.out.println("Node to replacement: " + replacement.toString());
if (replacement != replacedNode.getRightChild()) {
replacementParent.setLeftChild(replacement.getRightChild());
replacement.setRightChild(replacedNode.getRightChild());
}
return replacement;
}
} |
package network;
import java.util.LinkedList;
import java.util.List;
import keyvaluepair.KeyValuePair;
import network.client.TCPClient;
import output.OutputCollector;
public class NetworkMaster {
private List<Node> myNodes;
private OutputCollector<String, Integer> myOutput;
private int myPort;
private String myIp;
private String myHostPort;
private String myHostIp;
private AcceptConnection myServer;
private List<TCPClient> myClients;
private boolean isHost;
public NetworkMaster (OutputCollector<String, Integer> o) {
myOutput = o;
myNodes = new LinkedList<Node>();
myClients = new LinkedList<TCPClient>();
isHost = false;
}
public void startListening (int port) {
isHost = true;
myServer = new AcceptConnection(port, this);
new Thread(myServer).start();
}
public void requestJoin (String ownIP, String ownPort, String ip, String port) {
myServer = new AcceptConnection(Integer.parseInt(ownPort), this);
new Thread(myServer).start();
myHostIp = ip;
myPort = Integer.parseInt(ownPort);
myHostPort = port;
myIp = ownIP;
TCPClient client = new TCPClient(ip, Integer.parseInt(port), NetworkCodes.TIMEOUT);
String outType = "java.lang.String";
String outObj = Integer.toString(NetworkCodes.JOIN) + " " + ownIP + " " + ownPort;
client.sendObjectToServer(outType, outObj);
}
public List<Node> getNodes () {
return myNodes;
}
public synchronized void register (String iP, String port) {
myNodes.add(new Node(iP, port));
initNewClient(myNodes.get(myNodes.size()-1));
System.out.printf("Registered peer ip: %s, port: %s, into the network!\n", iP, port);
if (isHost) {
StringBuilder sb = new StringBuilder();
sb.append(Integer.toString(NetworkCodes.UPDATENODES));
sb.append(" ");
for (Node n : myNodes) {
sb.append(n.getIp());
sb.append(":");
sb.append(Integer.toString(n.getPort()));
sb.append(";");
}
sb.deleteCharAt(sb.length() - 1);
for (int i = 0; i < myNodes.size(); i++) {
sendMsgToNode(i, sb.toString());
}
}
}
public void updateNodeList (String listStr) {
String[] peers = listStr.split(";");
myNodes.clear();
for(TCPClient c : myClients){
c.quitClientThread();
}
myClients.clear();
System.out.println("Cleared Node List...");
for (String onePeer : peers) {
String[] ss = onePeer.split(":");
register(ss[0], ss[1]);
}
}
public boolean blockUntilNextAnswer () {
// TODO Auto-generated method stub
return false;
}
public int getNodeListSize () {
return myNodes.size();
}
public void sendMsgToNode (int index, String word) {
String outType = "java.lang.String";
myClients.get(index).sendObjToServerNonBlock(outType, word);
}
public void sendMsgToAll(String msg) {
for (TCPClient c: myClients) {
c.sendObjToServerNonBlock("java.lang.String", msg);
}
}
public void sendKVPToNode (int index, KeyValuePair<String, Integer> kvp) {
String outType = "keyvaluepair.KeyValuePair";
myClients.get(index).sendObjToServerNonBlock(outType, kvp);
System.out.println("Reduce " + kvp.getKey().toString() + "to reducer machine " + index);
}
public void sendKVPToPortAndIP (String IP, String port, KeyValuePair<String, Integer> kvp) {
TCPClient temp = new TCPClient(IP, Integer.parseInt(port), NetworkCodes.TIMEOUT);
temp.sendObjectToServer("keyvaluepair.KeyValuePair", kvp);
}
public void collectKVP (KeyValuePair<String, Integer> kvp) {
myOutput.collect(kvp);
System.out.println("Collected key "+kvp.getKey()+", value " + kvp.getValue().toString());
}
private void initNewClient (Node n) {
TCPClient client = new TCPClient(n.getIp(), n.getPort(), NetworkCodes.TIMEOUT);
new Thread(client).start();
myClients.add(client);
}
public int getPort() {
return myPort;
}
public boolean getIsHost() {
return isHost;
}
public String getHostIP() {
return myHostIp;
}
public String getHostPort() {
return myHostPort;
}
public String getIP() {
return myIp;
}
} |
package ljdp.minechem.common;
import java.util.Random;
import net.minecraft.world.World;
import net.minecraft.world.chunk.IChunkProvider;
import net.minecraft.world.gen.feature.WorldGenMinable;
import cpw.mods.fml.common.IWorldGenerator;
import cpw.mods.fml.common.Loader;
public class MinechemGeneration implements IWorldGenerator {
@Override
public void generate(Random random, int chunkX, int chunkZ, World world,
IChunkProvider chunkGenerator, IChunkProvider chunkProvider) {
if(!Loader.isModLoaded("AtomicScience")){
if(world.provider.dimensionId==0){
for(int k=0;k<2;k++){
int firstBlockXCoord = chunkX + random.nextInt(16);
int firstBlockYCoord = random.nextInt(30);
int firstBlockZCoord = chunkZ + random.nextInt(16);
WorldGenMinable mineable=new WorldGenMinable(MinechemBlocks.uranium.blockID, 4);
mineable.generate(world, random, firstBlockXCoord, firstBlockYCoord, firstBlockZCoord);
}
}
}
}
} |
package at.michael1011.backpacks;
import at.michael1011.backpacks.commads.Create;
import at.michael1011.backpacks.commads.Give;
import at.michael1011.backpacks.commads.Open;
import at.michael1011.backpacks.commads.Reload;
import at.michael1011.backpacks.listeners.*;
import at.michael1011.backpacks.tasks.Reconnect;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import static at.michael1011.backpacks.Updater.update;
public class Main extends JavaPlugin {
public static String version;
public static YamlConfiguration config, messages, furnaceGui;
public static String prefix = "";
public static List<String> availablePlayers = new ArrayList<>();
private static Main main;
// todo: verify backpacks with nbt tags
// todo: translations
@Override
public void onEnable() {
loadFiles(this);
prefix = ChatColor.translateAlternateColorCodes('&', messages.getString("prefix"));
updateConfig(this);
try {
new SQL(this);
SQL.createCon(config.getString("MySQL.host"), config.getString("MySQL.port"),
config.getString("MySQL.database"), config.getString("MySQL.username"),
config.getString("MySQL.password"));
if(SQL.checkCon()) {
Bukkit.getConsoleSender().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&',
messages.getString("MySQL.connected")));
main = this;
SQL.query("CREATE TABLE IF NOT EXISTS bp_users(name VARCHAR(100), uuid VARCHAR(100))", new SQL.Callback<Boolean>() {
@Override
public void onSuccess(Boolean rs) {
SQL.getResult("SELECT * FROM bp_users", new SQL.Callback<ResultSet>() {
@Override
public void onSuccess(ResultSet rs) {
try {
rs.beforeFirst();
while(rs.next()) {
availablePlayers.add(rs.getString("name"));
}
rs.close();
SQL.query("CREATE TABLE IF NOT EXISTS bp_furnaces(uuid VARCHAR(100), ores VARCHAR(100), food VARCHAR(100), " +
"autoFill VARCHAR(100), coal VARCHAR(100))", new SQL.Callback<Boolean>() {
@Override
public void onSuccess(Boolean rs) {
try {
EnchantGlow.getGlow();
} catch (IllegalArgumentException | IllegalStateException ignored) {}
Crafting.initCrafting(Bukkit.getConsoleSender());
version = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3];
new Join(main);
new RightClick(main);
new InventoryClose(main);
new BlockPlace(main);
new PlayerDeath(main);
new FurnaceGui(main);
new BlockBreak(main);
new EntityDeath(main);
new Give(main);
new Open(main);
new Create(main);
new Reload(main);
new Reconnect(main);
if(config.getBoolean("Updater.enabled")) {
update(main, Bukkit.getConsoleSender());
new Updater(main);
}
}
@Override
public void onFailure(Throwable e) {}
});
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Throwable e) {}
});
}
@Override
public void onFailure(Throwable e) {}
});
} else {
Bukkit.getConsoleSender().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&',
messages.getString("MySQL.failedToConnect")));
Bukkit.getConsoleSender().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&',
messages.getString("MySQL.failedToConnectCheck")));
}
} catch (SQLException e) {
e.printStackTrace();
Bukkit.getConsoleSender().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&',
messages.getString("MySQL.failedToConnect")));
Bukkit.getConsoleSender().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&',
messages.getString("MySQL.failedToConnectCheck")));
}
}
@Override
public void onDisable() {
Bukkit.getScheduler().cancelTasks(this);
if(SQL.checkCon()) {
try {
SQL.closeCon();
} catch (SQLException e) {
e.printStackTrace();
}
Bukkit.getConsoleSender().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&',
messages.getString("MySQL.closedConnection")));
}
}
private void updateConfig(Main main) {
try {
File folder = main.getDataFolder();
if(config.getInt("configVersion") == 0) {
if(new File(folder, "messages.yml").renameTo(new File(folder, "messages.old.yml"))) {
main.saveResource("messages.yml", false);
String updater = "Updater.";
config.set(updater+"enabled", true);
config.set(updater+"interval", 24);
config.set(updater+"autoUpdate", false);
config.set("configVersion", 1);
config.save(new File(folder, "config.yml"));
Bukkit.getConsoleSender().sendMessage(prefix+ChatColor.translateAlternateColorCodes('&',
"&cUpdated config files. &4Your old messages.yml file was renamed to messages.old.yml"));
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void loadFiles(Main main) {
try {
File folder = main.getDataFolder();
File configF = new File(folder, "config.yml");
File messagesF = new File(folder, "messages.yml");
File furnacesF = new File(folder, "furnaceBackPack.yml");
if(!configF.exists()) {
main.saveResource("config.yml", false);
}
if(!messagesF.exists()) {
main.saveResource("messages.yml", false);
}
if(!furnacesF.exists()) {
main.saveResource("furnaceBackPack.yml", false);
}
config = new YamlConfiguration();
messages = new YamlConfiguration();
furnaceGui = new YamlConfiguration();
config.load(configF);
messages.load(messagesF);
furnaceGui.load(furnacesF);
} catch (IOException | InvalidConfigurationException e) {
e.printStackTrace();
}
}
} |
package org.goobs.truth;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigValue;
import edu.stanford.nlp.util.Execution;
import edu.stanford.nlp.util.Execution.Option;
import edu.stanford.nlp.util.Function;
import edu.stanford.nlp.util.StringUtils;
import edu.stanford.nlp.util.logging.Redwood;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
/**
* A collection of properties
*
* @author Gabor Angeli
*/
public class Props {
private static final Redwood.RedwoodChannels logger = Redwood.channels("Exec");
@Option(name="psql.host", gloss="The hostname for the PSQL server")
public static String PSQL_HOST = "john0";
@Option(name="psql.host.tunnels", gloss="A list of hosts which don't have direct access, but tunnel through localhost")
public static String[] PSQL_HOST_TUNNELS = new String[]{"hal".intern()};
@Option(name="psql.port", gloss="The port at which postgres is running")
public static int PSQL_PORT = 4243;
@Option(name="psql.db", gloss="The database name")
public static String PSQL_DB = "truth";
@Option(name="psql.username", gloss="The username for the postgres session")
public static String PSQL_USERNAME = "gabor";
@Option(name="psql.password", gloss="The password for the postgres session")
public static String PSQL_PASSWORD = "gabor";
@Option(name="natlog.indexer.lazy", gloss="If true, do word indexing lazily rather than reading the indexer at once")
public static boolean NATLOG_INDEXER_LAZY = false;
@Option(name="server.host", gloss="The hostname for the inference server")
public static String SERVER_HOST = "localhost";
@Option(name="server.port", gloss="The hostname for the inference server")
public static int SERVER_PORT = 1337;
@Option(name="search.timeout", gloss="The maximum number of ticks to run for on the server")
public static long SEARCH_TIMEOUT = 100000;
@Option(name="script.wordnet.path", gloss="The path to the saved wordnet ontology (see sim.jar)")
public static String SCRIPT_WORDNET_PATH = "etc/ontology_wordnet3.1.ser.gz";
@Option(name="script.distsim.cos", gloss="The path to the cosine similarity nearest neighbors")
public static String SCRIPT_DISTSIM_COS = "/home/gabor/workspace/truth/etc/cosNN.tab";
@Option(name="script.distsim.jaccard", gloss="The path to the jaccard similarity nearest neighbors")
public static String SCRIPT_DISTSIM_JACCARD = "/home/gabor/workspace/truth/etc/cosNN.tab";
@Option(name="script.distsim.hellinger", gloss="The path to the hellinger similarity nearest neighbors")
public static String SCRIPT_DISTSIM_HELLINGER = "/home/gabor/workspace/truth/etc/cosNN.tab";
@Option(name="script.reverb.raw.dir", gloss="The raw directory where Reverb outputs are stored")
public static File SCRIPT_REVERB_RAW_DIR = new File("/scr/nlp/data/openie/output/reverb1.4/clueweb_english");
@Option(name="script.reverb.raw.gzip", gloss="If true, the input files are in gzip format")
public static boolean SCRIPT_REVERB_RAW_GZIP = true;
@Option(name="script.reverb.head.do", gloss="If true, compute the head word for each fact added")
public static boolean SCRIPT_REVERB_HEAD_DO = false;
@Option(name="script.freebase.raw.path", gloss="The location of the raw Freebase dump")
public static File SCRIPT_FREEBASE_RAW_PATH = new File("/u/nlp/data/semparse/rdf/scr/jackson/state/execs/93.exec/0.ttl");
@Option(name="script.freebase.path", gloss="The location of the processed Freebase dump")
public static File SCRIPT_FREEBASE_PATH = new File("etc/freebase.tab");
private static void initializeAndValidate() {
/* nothing yet */
}
public static void exec(final Function<Properties, Object> toRun, String[] args) {
// Set options classes
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
Execution.optionClasses = new Class<?>[stackTrace.length];
for (int i=0; i<stackTrace.length; ++i) {
try {
Execution.optionClasses[i] = Class.forName(stackTrace[i].getClassName());
} catch (ClassNotFoundException e) { logger.fatal(e); }
}
// Start Program
if (args.length == 1) {
// Case: Run with TypeSafe Config file
if (!new File(args[0]).canRead()) logger.fatal("Cannot read typesafe-config file: " + args[0]);
Config config = null;
try {
config = ConfigFactory.parseFile(new File(args[0]).getCanonicalFile()).resolve();
} catch (IOException e) {
System.err.println("Could not find config file: " + args[0]);
System.exit(1);
}
final Properties props = new Properties();
for (Map.Entry<String, ConfigValue> entry : config.entrySet()) {
String candidate = entry.getValue().unwrapped().toString();
if (candidate != null) {
props.setProperty(entry.getKey(), candidate);
}
}
Execution.exec(new Runnable() { @Override public void run() {
initializeAndValidate();
toRun.apply(props);
} }, props);
} else {
// Case: Run with Properties file or command line arguments
final Properties props = StringUtils.argsToProperties(args);
Execution.exec(new Runnable() { @Override public void run() {
Props.initializeAndValidate();
toRun.apply(props);
} }, props);
}
}
} |
package org.jgroups.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jgroups.*;
import org.jgroups.auth.AuthToken;
import org.jgroups.blocks.Connection;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.protocols.FD;
import org.jgroups.protocols.PingHeader;
import org.jgroups.stack.IpAddress;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import java.io.*;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import java.security.MessageDigest;
import java.text.NumberFormat;
import java.util.*;
/**
* Collection of various utility routines that can not be assigned to other classes.
* @author Bela Ban
* @version $Id: Util.java,v 1.172 2008/09/01 14:59:21 belaban Exp $
*/
public class Util {
private static NumberFormat f;
private static Map<Class,Byte> PRIMITIVE_TYPES=new HashMap<Class,Byte>(10);
private static final byte TYPE_NULL = 0;
private static final byte TYPE_STREAMABLE = 1;
private static final byte TYPE_SERIALIZABLE = 2;
private static final byte TYPE_BOOLEAN = 10;
private static final byte TYPE_BYTE = 11;
private static final byte TYPE_CHAR = 12;
private static final byte TYPE_DOUBLE = 13;
private static final byte TYPE_FLOAT = 14;
private static final byte TYPE_INT = 15;
private static final byte TYPE_LONG = 16;
private static final byte TYPE_SHORT = 17;
private static final byte TYPE_STRING = 18;
private static final byte TYPE_BYTEARRAY = 19;
// constants
public static final int MAX_PORT=65535; // highest port allocatable
static boolean resolve_dns=false;
static boolean JGROUPS_COMPAT=false;
/**
* Global thread group to which all (most!) JGroups threads belong
*/
private static ThreadGroup GLOBAL_GROUP=new ThreadGroup("JGroups") {
public void uncaughtException(Thread t, Throwable e) {
LogFactory.getLog("org.jgroups").error("uncaught exception in " + t + " (thread group=" + GLOBAL_GROUP + " )", e);
}
};
public static ThreadGroup getGlobalThreadGroup() {
return GLOBAL_GROUP;
}
static {
try {
resolve_dns=Boolean.valueOf(System.getProperty("resolve.dns", "false")).booleanValue();
}
catch (SecurityException ex){
resolve_dns=false;
}
f=NumberFormat.getNumberInstance();
f.setGroupingUsed(false);
f.setMaximumFractionDigits(2);
try {
String tmp=Util.getProperty(new String[]{Global.MARSHALLING_COMPAT}, null, null, false, "false");
JGROUPS_COMPAT=Boolean.valueOf(tmp).booleanValue();
}
catch (SecurityException ex){
}
PRIMITIVE_TYPES.put(Boolean.class, new Byte(TYPE_BOOLEAN));
PRIMITIVE_TYPES.put(Byte.class, new Byte(TYPE_BYTE));
PRIMITIVE_TYPES.put(Character.class, new Byte(TYPE_CHAR));
PRIMITIVE_TYPES.put(Double.class, new Byte(TYPE_DOUBLE));
PRIMITIVE_TYPES.put(Float.class, new Byte(TYPE_FLOAT));
PRIMITIVE_TYPES.put(Integer.class, new Byte(TYPE_INT));
PRIMITIVE_TYPES.put(Long.class, new Byte(TYPE_LONG));
PRIMITIVE_TYPES.put(Short.class, new Byte(TYPE_SHORT));
PRIMITIVE_TYPES.put(String.class, new Byte(TYPE_STRING));
PRIMITIVE_TYPES.put(byte[].class, new Byte(TYPE_BYTEARRAY));
}
public static void assertTrue(boolean condition) {
assert condition;
}
public static void assertTrue(String message, boolean condition) {
if(message != null)
assert condition : message;
else
assert condition;
}
public static void assertFalse(boolean condition) {
assertFalse(null, condition);
}
public static void assertFalse(String message, boolean condition) {
if(message != null)
assert !condition : message;
else
assert !condition;
}
public static void assertEquals(String message, Object val1, Object val2) {
if(message != null) {
assert val1.equals(val2) : message;
}
else {
assert val1.equals(val2);
}
}
public static void assertEquals(Object val1, Object val2) {
assertEquals(null, val1, val2);
}
public static void assertNotNull(String message, Object val) {
if(message != null)
assert val != null : message;
else
assert val != null;
}
public static void assertNotNull(Object val) {
assertNotNull(null, val);
}
public static void assertNull(String message, Object val) {
if(message != null)
assert val == null : message;
else
assert val == null;
}
public static void assertNull(Object val) {
assertNotNull(null, val);
}
/**
* Verifies that val is <= max memory
* @param buf_name
* @param val
*/
public static void checkBufferSize(String buf_name, long val) {
// sanity check that max_credits doesn't exceed memory allocated to VM by -Xmx
long max_mem=Runtime.getRuntime().maxMemory();
if(val > max_mem) {
throw new IllegalArgumentException(buf_name + "(" + Util.printBytes(val) + ") exceeds max memory allocated to VM (" +
Util.printBytes(max_mem) + ")");
}
}
public static void close(InputStream inp) {
if(inp != null)
try {inp.close();} catch(IOException e) {}
}
public static void close(OutputStream out) {
if(out != null) {
try {out.close();} catch(IOException e) {}
}
}
public static void close(Socket s) {
if(s != null) {
try {s.close();} catch(Exception ex) {}
}
}
public static void close(ServerSocket s) {
if(s != null) {
try {s.close();} catch(Exception ex) {}
}
}
public static void close(DatagramSocket my_sock) {
if(my_sock != null) {
try {my_sock.close();} catch(Throwable t) {}
}
}
public static void close(Channel ch) {
if(ch != null) {
try {ch.close();} catch(Throwable t) {}
}
}
public static void close(Channel ... channels) {
if(channels != null) {
for(Channel ch: channels)
Util.close(ch);
}
}
public static void close(Connection conn) {
if(conn != null) {
try {conn.close();} catch(Throwable t) {}
}
}
/**
* Creates an object from a byte buffer
*/
public static Object objectFromByteBuffer(byte[] buffer) throws Exception {
if(buffer == null) return null;
if(JGROUPS_COMPAT)
return oldObjectFromByteBuffer(buffer);
return objectFromByteBuffer(buffer, 0, buffer.length);
}
public static Object objectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception {
if(buffer == null) return null;
if(JGROUPS_COMPAT)
return oldObjectFromByteBuffer(buffer, offset, length);
Object retval=null;
InputStream in=null;
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length);
byte b=(byte)in_stream.read();
try {
switch(b) {
case TYPE_NULL:
return null;
case TYPE_STREAMABLE:
in=new DataInputStream(in_stream);
retval=readGenericStreamable((DataInputStream)in);
break;
case TYPE_SERIALIZABLE: // the object is Externalizable or Serializable
in=new ContextObjectInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=((ContextObjectInputStream)in).readObject();
break;
case TYPE_BOOLEAN:
in=new DataInputStream(in_stream);
retval=Boolean.valueOf(((DataInputStream)in).readBoolean());
break;
case TYPE_BYTE:
in=new DataInputStream(in_stream);
retval=new Byte(((DataInputStream)in).readByte());
break;
case TYPE_CHAR:
in=new DataInputStream(in_stream);
retval=new Character(((DataInputStream)in).readChar());
break;
case TYPE_DOUBLE:
in=new DataInputStream(in_stream);
retval=new Double(((DataInputStream)in).readDouble());
break;
case TYPE_FLOAT:
in=new DataInputStream(in_stream);
retval=new Float(((DataInputStream)in).readFloat());
break;
case TYPE_INT:
in=new DataInputStream(in_stream);
retval=new Integer(((DataInputStream)in).readInt());
break;
case TYPE_LONG:
in=new DataInputStream(in_stream);
retval=new Long(((DataInputStream)in).readLong());
break;
case TYPE_SHORT:
in=new DataInputStream(in_stream);
retval=new Short(((DataInputStream)in).readShort());
break;
case TYPE_STRING:
in=new DataInputStream(in_stream);
if(((DataInputStream)in).readBoolean()) { // large string
ObjectInputStream ois=new ObjectInputStream(in);
try {
return ois.readObject();
}
finally {
ois.close();
}
}
else {
retval=((DataInputStream)in).readUTF();
}
break;
case TYPE_BYTEARRAY:
int len=((DataInputStream)in).readInt();
byte[] tmp=new byte[len];
in.read(tmp, 0, tmp.length);
break;
default:
throw new IllegalArgumentException("type " + b + " is invalid");
}
return retval;
}
finally {
Util.close(in);
}
}
/**
* Serializes/Streams an object into a byte buffer.
* The object has to implement interface Serializable or Externalizable
* or Streamable. Only Streamable objects are interoperable w/ jgroups-me
*/
public static byte[] objectToByteBuffer(Object obj) throws Exception {
if(JGROUPS_COMPAT)
return oldObjectToByteBuffer(obj);
byte[] result=null;
final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512);
if(obj == null) {
out_stream.write(TYPE_NULL);
out_stream.flush();
return out_stream.toByteArray();
}
OutputStream out=null;
Byte type;
try {
if(obj instanceof Streamable) { // use Streamable if we can
out_stream.write(TYPE_STREAMABLE);
out=new DataOutputStream(out_stream);
writeGenericStreamable((Streamable)obj, (DataOutputStream)out);
}
else if((type=PRIMITIVE_TYPES.get(obj.getClass())) != null) {
out_stream.write(type.byteValue());
out=new DataOutputStream(out_stream);
switch(type.byteValue()) {
case TYPE_BOOLEAN:
((DataOutputStream)out).writeBoolean(((Boolean)obj).booleanValue());
break;
case TYPE_BYTE:
((DataOutputStream)out).writeByte(((Byte)obj).byteValue());
break;
case TYPE_CHAR:
((DataOutputStream)out).writeChar(((Character)obj).charValue());
break;
case TYPE_DOUBLE:
((DataOutputStream)out).writeDouble(((Double)obj).doubleValue());
break;
case TYPE_FLOAT:
((DataOutputStream)out).writeFloat(((Float)obj).floatValue());
break;
case TYPE_INT:
((DataOutputStream)out).writeInt(((Integer)obj).intValue());
break;
case TYPE_LONG:
((DataOutputStream)out).writeLong(((Long)obj).longValue());
break;
case TYPE_SHORT:
((DataOutputStream)out).writeShort(((Short)obj).shortValue());
break;
case TYPE_STRING:
String str=(String)obj;
if(str.length() > Short.MAX_VALUE) {
((DataOutputStream)out).writeBoolean(true);
ObjectOutputStream oos=new ObjectOutputStream(out);
try {
oos.writeObject(str);
}
finally {
oos.close();
}
}
else {
((DataOutputStream)out).writeBoolean(false);
((DataOutputStream)out).writeUTF(str);
}
break;
case TYPE_BYTEARRAY:
byte[] buf=(byte[])obj;
((DataOutputStream)out).writeInt(buf.length);
out.write(buf, 0, buf.length);
break;
default:
throw new IllegalArgumentException("type " + type + " is invalid");
}
}
else { // will throw an exception if object is not serializable
out_stream.write(TYPE_SERIALIZABLE);
out=new ObjectOutputStream(out_stream);
((ObjectOutputStream)out).writeObject(obj);
}
}
finally {
Util.close(out);
}
result=out_stream.toByteArray();
return result;
}
/** For backward compatibility in JBoss 4.0.2 */
public static Object oldObjectFromByteBuffer(byte[] buffer) throws Exception {
if(buffer == null) return null;
return oldObjectFromByteBuffer(buffer, 0, buffer.length);
}
public static Object oldObjectFromByteBuffer(byte[] buffer, int offset, int length) throws Exception {
if(buffer == null) return null;
Object retval=null;
try { // to read the object as an Externalizable
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length);
ObjectInputStream in=new ContextObjectInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=in.readObject();
in.close();
}
catch(StreamCorruptedException sce) {
try { // is it Streamable?
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length);
DataInputStream in=new DataInputStream(in_stream);
retval=readGenericStreamable(in);
in.close();
}
catch(Exception ee) {
IOException tmp=new IOException("unmarshalling failed");
tmp.initCause(ee);
throw tmp;
}
}
if(retval == null)
return null;
return retval;
}
/**
* Serializes/Streams an object into a byte buffer.
* The object has to implement interface Serializable or Externalizable
* or Streamable. Only Streamable objects are interoperable w/ jgroups-me
*/
public static byte[] oldObjectToByteBuffer(Object obj) throws Exception {
byte[] result=null;
final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512);
if(obj instanceof Streamable) { // use Streamable if we can
DataOutputStream out=new DataOutputStream(out_stream);
writeGenericStreamable((Streamable)obj, out);
out.close();
}
else {
ObjectOutputStream out=new ObjectOutputStream(out_stream);
out.writeObject(obj);
out.close();
}
result=out_stream.toByteArray();
return result;
}
public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer) throws Exception {
if(buffer == null) return null;
Streamable retval=null;
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer);
DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=(Streamable)cl.newInstance();
retval.readFrom(in);
in.close();
return retval;
}
public static Streamable streamableFromByteBuffer(Class cl, byte[] buffer, int offset, int length) throws Exception {
if(buffer == null) return null;
Streamable retval=null;
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer, offset, length);
DataInputStream in=new DataInputStream(in_stream); // changed Nov 29 2004 (bela)
retval=(Streamable)cl.newInstance();
retval.readFrom(in);
in.close();
return retval;
}
public static byte[] streamableToByteBuffer(Streamable obj) throws Exception {
byte[] result=null;
final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512);
DataOutputStream out=new DataOutputStream(out_stream);
obj.writeTo(out);
result=out_stream.toByteArray();
out.close();
return result;
}
public static byte[] collectionToByteBuffer(Collection<Address> c) throws Exception {
byte[] result=null;
final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512);
DataOutputStream out=new DataOutputStream(out_stream);
Util.writeAddresses(c, out);
result=out_stream.toByteArray();
out.close();
return result;
}
public static int size(Address addr) {
int retval=Global.BYTE_SIZE; // presence byte
if(addr != null)
retval+=addr.size() + Global.BYTE_SIZE; // plus type of address
return retval;
}
public static void writeAuthToken(AuthToken token, DataOutputStream out) throws IOException{
Util.writeString(token.getName(), out);
token.writeTo(out);
}
public static AuthToken readAuthToken(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
try{
String type = Util.readString(in);
Object obj = Class.forName(type).newInstance();
AuthToken token = (AuthToken) obj;
token.readFrom(in);
return token;
}
catch(ClassNotFoundException cnfe){
return null;
}
}
public static void writeAddress(Address addr, DataOutputStream out) throws IOException {
if(addr == null) {
out.writeBoolean(false);
return;
}
out.writeBoolean(true);
if(addr instanceof IpAddress) {
// regular case, we don't need to include class information about the type of Address, e.g. JmsAddress
out.writeBoolean(true);
addr.writeTo(out);
}
else {
out.writeBoolean(false);
writeOtherAddress(addr, out);
}
}
public static Address readAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
Address addr=null;
if(in.readBoolean() == false)
return null;
if(in.readBoolean()) {
addr=new IpAddress();
addr.readFrom(in);
}
else {
addr=readOtherAddress(in);
}
return addr;
}
private static Address readOtherAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
int b=in.read();
short magic_number;
String classname;
Class cl=null;
Address addr;
if(b == 1) {
magic_number=in.readShort();
cl=ClassConfigurator.get(magic_number);
}
else {
classname=in.readUTF();
cl=ClassConfigurator.get(classname);
}
addr=(Address)cl.newInstance();
addr.readFrom(in);
return addr;
}
private static void writeOtherAddress(Address addr, DataOutputStream out) throws IOException {
short magic_number=ClassConfigurator.getMagicNumber(addr.getClass());
// write the class info
if(magic_number == -1) {
out.write(0);
out.writeUTF(addr.getClass().getName());
}
else {
out.write(1);
out.writeShort(magic_number);
}
// write the data itself
addr.writeTo(out);
}
/**
* Writes a Vector of Addresses. Can contain 65K addresses at most
* @param v A Collection<Address>
* @param out
* @throws IOException
*/
public static void writeAddresses(Collection<Address> v, DataOutputStream out) throws IOException {
if(v == null) {
out.writeShort(-1);
return;
}
out.writeShort(v.size());
for(Address addr: v) {
Util.writeAddress(addr, out);
}
}
public static Collection<Address> readAddresses(DataInputStream in, Class cl) throws IOException, IllegalAccessException, InstantiationException {
short length=in.readShort();
if(length < 0) return null;
Collection<Address> retval=(Collection<Address>)cl.newInstance();
Address addr;
for(int i=0; i < length; i++) {
addr=Util.readAddress(in);
retval.add(addr);
}
return retval;
}
/**
* Returns the marshalled size of a Collection of Addresses.
* <em>Assumes elements are of the same type !</em>
* @param addrs Collection<Address>
* @return long size
*/
public static long size(Collection<Address> addrs) {
int retval=Global.SHORT_SIZE; // number of elements
if(addrs != null && !addrs.isEmpty()) {
Address addr=addrs.iterator().next();
retval+=size(addr) * addrs.size();
}
return retval;
}
public static void writeStreamable(Streamable obj, DataOutputStream out) throws IOException {
if(obj == null) {
out.writeBoolean(false);
return;
}
out.writeBoolean(true);
obj.writeTo(out);
}
public static Streamable readStreamable(Class clazz, DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
Streamable retval=null;
if(in.readBoolean() == false)
return null;
retval=(Streamable)clazz.newInstance();
retval.readFrom(in);
return retval;
}
public static void writeGenericStreamable(Streamable obj, DataOutputStream out) throws IOException {
short magic_number;
String classname;
if(obj == null) {
out.write(0);
return;
}
out.write(1);
magic_number=ClassConfigurator.getMagicNumber(obj.getClass());
// write the magic number or the class name
if(magic_number == -1) {
out.writeBoolean(false);
classname=obj.getClass().getName();
out.writeUTF(classname);
}
else {
out.writeBoolean(true);
out.writeShort(magic_number);
}
// write the contents
obj.writeTo(out);
}
public static Streamable readGenericStreamable(DataInputStream in) throws IOException {
Streamable retval=null;
int b=in.read();
if(b == 0)
return null;
boolean use_magic_number=in.readBoolean();
String classname;
Class clazz;
try {
if(use_magic_number) {
short magic_number=in.readShort();
clazz=ClassConfigurator.get(magic_number);
if (clazz==null) {
throw new ClassNotFoundException("Class for magic number "+magic_number+" cannot be found.");
}
}
else {
classname=in.readUTF();
clazz=ClassConfigurator.get(classname);
if (clazz==null) {
throw new ClassNotFoundException(classname);
}
}
retval=(Streamable)clazz.newInstance();
retval.readFrom(in);
return retval;
}
catch(Exception ex) {
throw new IOException("failed reading object: " + ex.toString());
}
}
public static void writeObject(Object obj, DataOutputStream out) throws Exception {
if(obj == null || !(obj instanceof Streamable)) {
byte[] buf=objectToByteBuffer(obj);
out.writeShort(buf.length);
out.write(buf, 0, buf.length);
}
else {
out.writeShort(-1);
writeGenericStreamable((Streamable)obj, out);
}
}
public static Object readObject(DataInputStream in) throws Exception {
short len=in.readShort();
Object retval=null;
if(len == -1) {
retval=readGenericStreamable(in);
}
else {
byte[] buf=new byte[len];
in.readFully(buf, 0, len);
retval=objectFromByteBuffer(buf);
}
return retval;
}
public static void writeString(String s, DataOutputStream out) throws IOException {
if(s != null) {
out.write(1);
out.writeUTF(s);
}
else {
out.write(0);
}
}
public static void writeString(DataOutputStream out, String s) throws IOException {
out.write(s.getBytes());
}
public static String readString(DataInputStream in) throws IOException {
int b=in.read();
if(b == 1)
return in.readUTF();
return null;
}
public static String parseString(DataInputStream in) {
return parseString(in, false);
}
public static String parseString(DataInputStream in, boolean break_on_newline) {
StringBuilder sb=new StringBuilder();
int ch;
// read white space
while(true) {
try {
ch=in.read();
if(ch == -1) {
return null; // eof
}
if(Character.isWhitespace(ch)) {
if(break_on_newline && ch == '\n')
return null;
}
else {
sb.append((char)ch);
break;
}
}
catch(IOException e) {
break;
}
}
while(true) {
try {
ch=in.read();
if(ch == -1)
break;
if(Character.isWhitespace(ch))
break;
else {
sb.append((char)ch);
}
}
catch(IOException e) {
break;
}
}
return sb.toString();
}
public static void writeByteBuffer(byte[] buf, DataOutputStream out) throws IOException {
if(buf != null) {
out.write(1);
out.writeInt(buf.length);
out.write(buf, 0, buf.length);
}
else {
out.write(0);
}
}
public static byte[] readByteBuffer(DataInputStream in) throws IOException {
int b=in.read();
if(b == 1) {
b=in.readInt();
byte[] buf=new byte[b];
in.read(buf, 0, buf.length);
return buf;
}
return null;
}
public static Buffer messageToByteBuffer(Message msg) throws IOException {
ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512);
DataOutputStream out=new DataOutputStream(output);
out.writeBoolean(msg != null);
if(msg != null)
msg.writeTo(out);
out.flush();
Buffer retval=new Buffer(output.getRawBuffer(), 0, output.size());
out.close();
output.close();
return retval;
}
public static Message byteBufferToMessage(byte[] buffer, int offset, int length) throws Exception {
ByteArrayInputStream input=new ByteArrayInputStream(buffer, offset, length);
DataInputStream in=new DataInputStream(input);
if(!in.readBoolean())
return null;
Message msg=new Message(false); // don't create headers, readFrom() will do this
msg.readFrom(in);
return msg;
}
/**
* Marshalls a list of messages.
* @param xmit_list LinkedList<Message>
* @return Buffer
* @throws IOException
*/
public static Buffer msgListToByteBuffer(List<Message> xmit_list) throws IOException {
ExposedByteArrayOutputStream output=new ExposedByteArrayOutputStream(512);
DataOutputStream out=new DataOutputStream(output);
Buffer retval=null;
out.writeInt(xmit_list.size());
for(Message msg: xmit_list) {
msg.writeTo(out);
}
out.flush();
retval=new Buffer(output.getRawBuffer(), 0, output.size());
out.close();
output.close();
return retval;
}
public static List<Message> byteBufferToMessageList(byte[] buffer, int offset, int length) throws Exception {
List<Message> retval=null;
ByteArrayInputStream input=new ByteArrayInputStream(buffer, offset, length);
DataInputStream in=new DataInputStream(input);
int size=in.readInt();
if(size == 0)
return null;
Message msg;
retval=new LinkedList<Message>();
for(int i=0; i < size; i++) {
msg=new Message(false); // don't create headers, readFrom() will do this
msg.readFrom(in);
retval.add(msg);
}
return retval;
}
public static boolean match(Object obj1, Object obj2) {
if(obj1 == null && obj2 == null)
return true;
if(obj1 != null)
return obj1.equals(obj2);
else
return obj2.equals(obj1);
}
public static boolean match(long[] a1, long[] a2) {
if(a1 == null && a2 == null)
return true;
if(a1 == null || a2 == null)
return false;
if(a1 == a2) // identity
return true;
// at this point, a1 != null and a2 != null
if(a1.length != a2.length)
return false;
for(int i=0; i < a1.length; i++) {
if(a1[i] != a2[i])
return false;
}
return true;
}
/** Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted */
public static void sleep(long timeout) {
try {
Thread.sleep(timeout);
}
catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void sleep(long timeout, int nanos) {
try {
Thread.sleep(timeout,nanos);
}
catch(InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/**
* On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will
* sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the
* thread never relinquishes control and therefore the sleep(x) is exactly x ms long.
*/
public static void sleep(long msecs, boolean busy_sleep) {
if(!busy_sleep) {
sleep(msecs);
return;
}
long start=System.currentTimeMillis();
long stop=start + msecs;
while(stop > start) {
start=System.currentTimeMillis();
}
}
public static int keyPress(String msg) {
System.out.println(msg);
try {
return System.in.read();
}
catch(IOException e) {
return 0;
}
}
/** Returns a random value in the range [1 - range] */
public static long random(long range) {
return (long)((Math.random() * range) % range) + 1;
}
/** Sleeps between 1 and timeout milliseconds, chosen randomly. Timeout must be > 1 */
public static void sleepRandom(long timeout) {
if(timeout <= 0) {
return;
}
long r=(int)((Math.random() * 100000) % timeout) + 1;
sleep(r);
}
/**
Tosses a coin weighted with probability and returns true or false. Example: if probability=0.8,
chances are that in 80% of all cases, true will be returned and false in 20%.
*/
public static boolean tossWeightedCoin(double probability) {
long r=random(100);
long cutoff=(long)(probability * 100);
return r < cutoff;
}
public static String getHostname() {
try {
return InetAddress.getLocalHost().getHostName();
}
catch(Exception ex) {
}
return "localhost";
}
public static void dumpStack(boolean exit) {
try {
throw new Exception("Dumping stack:");
}
catch(Exception e) {
e.printStackTrace();
if(exit)
System.exit(0);
}
}
public static String dumpThreads() {
StringBuilder sb=new StringBuilder();
ThreadMXBean bean=ManagementFactory.getThreadMXBean();
long[] ids=bean.getAllThreadIds();
ThreadInfo[] threads=bean.getThreadInfo(ids, 20);
for(int i=0; i < threads.length; i++) {
ThreadInfo info=threads[i];
if(info == null)
continue;
sb.append(info.getThreadName()).append(":\n");
StackTraceElement[] stack_trace=info.getStackTrace();
for(int j=0; j < stack_trace.length; j++) {
StackTraceElement el=stack_trace[j];
sb.append(" at ").append(el.getClassName()).append(".").append(el.getMethodName());
sb.append("(").append(el.getFileName()).append(":").append(el.getLineNumber()).append(")");
sb.append("\n");
}
sb.append("\n\n");
}
return sb.toString();
}
public static boolean interruptAndWaitToDie(Thread t) {
return interruptAndWaitToDie(t, Global.THREAD_SHUTDOWN_WAIT_TIME);
}
public static boolean interruptAndWaitToDie(Thread t, long timeout) {
if(t == null)
throw new IllegalArgumentException("Thread can not be null");
t.interrupt(); // interrupts the sleep()
try {
t.join(timeout);
}
catch(InterruptedException e){
Thread.currentThread().interrupt(); // set interrupt flag again
}
return t.isAlive();
}
/**
* Debugging method used to dump the content of a protocol queue in a
* condensed form. Useful to follow the evolution of the queue's content in
* time.
*/
public static String dumpQueue(Queue q) {
StringBuilder sb=new StringBuilder();
LinkedList values=q.values();
if(values.isEmpty()) {
sb.append("empty");
}
else {
for(Iterator it=values.iterator(); it.hasNext();) {
Object o=it.next();
String s=null;
if(o instanceof Event) {
Event event=(Event)o;
int type=event.getType();
s=Event.type2String(type);
if(type == Event.VIEW_CHANGE)
s+=" " + event.getArg();
if(type == Event.MSG)
s+=" " + event.getArg();
if(type == Event.MSG) {
s+="[";
Message m=(Message)event.getArg();
Map<String,Header> headers=new HashMap<String,Header>(m.getHeaders());
for(Iterator i=headers.keySet().iterator(); i.hasNext();) {
Object headerKey=i.next();
Object value=headers.get(headerKey);
String headerToString=null;
if(value instanceof FD.FdHeader) {
headerToString=value.toString();
}
else
if(value instanceof PingHeader) {
headerToString=headerKey + "-";
if(((PingHeader)value).type == PingHeader.GET_MBRS_REQ) {
headerToString+="GMREQ";
}
else
if(((PingHeader)value).type == PingHeader.GET_MBRS_RSP) {
headerToString+="GMRSP";
}
else {
headerToString+="UNKNOWN";
}
}
else {
headerToString=headerKey + "-" + (value == null ? "null" : value.toString());
}
s+=headerToString;
if(i.hasNext()) {
s+=",";
}
}
s+="]";
}
}
else {
s=o.toString();
}
sb.append(s).append("\n");
}
}
return sb.toString();
}
/**
* Use with caution: lots of overhead
*/
public static String printStackTrace(Throwable t) {
StringWriter s=new StringWriter();
PrintWriter p=new PrintWriter(s);
t.printStackTrace(p);
return s.toString();
}
public static String getStackTrace(Throwable t) {
return printStackTrace(t);
}
public static String print(Throwable t) {
return printStackTrace(t);
}
public static void crash() {
System.exit(-1);
}
public static String printEvent(Event evt) {
Message msg;
if(evt.getType() == Event.MSG) {
msg=(Message)evt.getArg();
if(msg != null) {
if(msg.getLength() > 0)
return printMessage(msg);
else
return msg.printObjectHeaders();
}
}
return evt.toString();
}
/** Tries to read an object from the message's buffer and prints it */
public static String printMessage(Message msg) {
if(msg == null)
return "";
if(msg.getLength() == 0)
return null;
try {
return msg.getObject().toString();
}
catch(Exception e) { // it is not an object
return "";
}
}
/** Tries to read a <code>MethodCall</code> object from the message's buffer and prints it.
Returns empty string if object is not a method call */
public static String printMethodCall(Message msg) {
Object obj;
if(msg == null)
return "";
if(msg.getLength() == 0)
return "";
try {
obj=msg.getObject();
return obj.toString();
}
catch(Exception e) { // it is not an object
return "";
}
}
public static void printThreads() {
Thread threads[]=new Thread[Thread.activeCount()];
Thread.enumerate(threads);
System.out.println("
for(int i=0; i < threads.length; i++) {
System.out.println("#" + i + ": " + threads[i]);
}
System.out.println("
}
public static String activeThreads() {
StringBuilder sb=new StringBuilder();
Thread threads[]=new Thread[Thread.activeCount()];
Thread.enumerate(threads);
sb.append("
for(int i=0; i < threads.length; i++) {
sb.append("#").append(i).append(": ").append(threads[i]).append('\n');
}
sb.append("
return sb.toString();
}
public static String printBytes(long bytes) {
double tmp;
if(bytes < 1000)
return bytes + "b";
if(bytes < 1000000) {
tmp=bytes / 1000.0;
return f.format(tmp) + "KB";
}
if(bytes < 1000000000) {
tmp=bytes / 1000000.0;
return f.format(tmp) + "MB";
}
else {
tmp=bytes / 1000000000.0;
return f.format(tmp) + "GB";
}
}
public static String printBytes(double bytes) {
double tmp;
if(bytes < 1000)
return bytes + "b";
if(bytes < 1000000) {
tmp=bytes / 1000.0;
return f.format(tmp) + "KB";
}
if(bytes < 1000000000) {
tmp=bytes / 1000000.0;
return f.format(tmp) + "MB";
}
else {
tmp=bytes / 1000000000.0;
return f.format(tmp) + "GB";
}
}
/**
Fragments a byte buffer into smaller fragments of (max.) frag_size.
Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments
of 248 bytes each and 1 fragment of 32 bytes.
@return An array of byte buffers (<code>byte[]</code>).
*/
public static byte[][] fragmentBuffer(byte[] buf, int frag_size, final int length) {
byte[] retval[];
int accumulated_size=0;
byte[] fragment;
int tmp_size=0;
int num_frags;
int index=0;
num_frags=length % frag_size == 0 ? length / frag_size : length / frag_size + 1;
retval=new byte[num_frags][];
while(accumulated_size < length) {
if(accumulated_size + frag_size <= length)
tmp_size=frag_size;
else
tmp_size=length - accumulated_size;
fragment=new byte[tmp_size];
System.arraycopy(buf, accumulated_size, fragment, 0, tmp_size);
retval[index++]=fragment;
accumulated_size+=tmp_size;
}
return retval;
}
public static byte[][] fragmentBuffer(byte[] buf, int frag_size) {
return fragmentBuffer(buf, frag_size, buf.length);
}
/**
* Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and
* return them in a list. Example:<br/>
* Buffer is 10 bytes, frag_size is 4 bytes. Return value will be ({0,4}, {4,4}, {8,2}).
* This is a total of 3 fragments: the first fragment starts at 0, and has a length of 4 bytes, the second fragment
* starts at offset 4 and has a length of 4 bytes, and the last fragment starts at offset 8 and has a length
* of 2 bytes.
* @param frag_size
* @return List. A List<Range> of offset/length pairs
*/
public static List<Range> computeFragOffsets(int offset, int length, int frag_size) {
List<Range> retval=new ArrayList<Range>();
long total_size=length + offset;
int index=offset;
int tmp_size=0;
Range r;
while(index < total_size) {
if(index + frag_size <= total_size)
tmp_size=frag_size;
else
tmp_size=(int)(total_size - index);
r=new Range(index, tmp_size);
retval.add(r);
index+=tmp_size;
}
return retval;
}
public static List<Range> computeFragOffsets(byte[] buf, int frag_size) {
return computeFragOffsets(0, buf.length, frag_size);
}
/**
Concatenates smaller fragments into entire buffers.
@param fragments An array of byte buffers (<code>byte[]</code>)
@return A byte buffer
*/
public static byte[] defragmentBuffer(byte[] fragments[]) {
int total_length=0;
byte[] ret;
int index=0;
if(fragments == null) return null;
for(int i=0; i < fragments.length; i++) {
if(fragments[i] == null) continue;
total_length+=fragments[i].length;
}
ret=new byte[total_length];
for(int i=0; i < fragments.length; i++) {
if(fragments[i] == null) continue;
System.arraycopy(fragments[i], 0, ret, index, fragments[i].length);
index+=fragments[i].length;
}
return ret;
}
public static void printFragments(byte[] frags[]) {
for(int i=0; i < frags.length; i++)
System.out.println('\'' + new String(frags[i]) + '\'');
}
public static <T> String printListWithDelimiter(Collection<T> list, String delimiter) {
boolean first=true;
StringBuilder sb=new StringBuilder();
for(T el: list) {
if(first) {
first=false;
}
else {
sb.append(delimiter);
}
sb.append(el);
}
return sb.toString();
}
// /**
// Peeks for view on the channel until n views have been received or timeout has elapsed.
// Used to determine the view in which we want to start work. Usually, we start as only
// member in our own view (1st view) and the next view (2nd view) will be the full view
// of all members, or a timeout if we're the first member. If a non-view (a message or
// block) is received, the method returns immediately.
// @param channel The channel used to peek for views. Has to be operational.
// @param number_of_views The number of views to wait for. 2 is a good number to ensure that,
// if there are other members, we start working with them included in our view.
// @param timeout Number of milliseconds to wait until view is forced to return. A value
// of <= 0 means wait forever.
// */
// public static View peekViews(Channel channel, int number_of_views, long timeout) {
// View retval=null;
// Object obj=null;
// int num=0;
// long start_time=System.currentTimeMillis();
// if(timeout <= 0) {
// while(true) {
// try {
// obj=channel.peek(0);
// if(obj == null || !(obj instanceof View))
// break;
// else {
// retval=(View)channel.receive(0);
// num++;
// if(num >= number_of_views)
// break;
// catch(Exception ex) {
// break;
// else {
// while(timeout > 0) {
// try {
// obj=channel.peek(timeout);
// if(obj == null || !(obj instanceof View))
// break;
// else {
// retval=(View)channel.receive(timeout);
// num++;
// if(num >= number_of_views)
// break;
// catch(Exception ex) {
// break;
// timeout=timeout - (System.currentTimeMillis() - start_time);
// return retval;
public static String array2String(long[] array) {
StringBuilder ret=new StringBuilder("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(short[] array) {
StringBuilder ret=new StringBuilder("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(int[] array) {
StringBuilder ret=new StringBuilder("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(boolean[] array) {
StringBuilder ret=new StringBuilder("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(Object[] array) {
StringBuilder ret=new StringBuilder("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i]).append(" ");
}
ret.append(']');
return ret.toString();
}
/** Returns true if all elements of c match obj */
public static boolean all(Collection c, Object obj) {
for(Iterator iterator=c.iterator(); iterator.hasNext();) {
Object o=iterator.next();
if(!o.equals(obj))
return false;
}
return true;
}
/**
* Selects a random subset of members according to subset_percentage and returns them.
* Picks no member twice from the same membership. If the percentage is smaller than 1 -> picks 1 member.
*/
public static Vector<Address> pickSubset(Vector<Address> members, double subset_percentage) {
Vector<Address> ret=new Vector<Address>(), tmp_mbrs;
int num_mbrs=members.size(), subset_size, index;
if(num_mbrs == 0) return ret;
subset_size=(int)Math.ceil(num_mbrs * subset_percentage);
tmp_mbrs=(Vector<Address>)members.clone();
for(int i=subset_size; i > 0 && !tmp_mbrs.isEmpty(); i
index=(int)((Math.random() * num_mbrs) % tmp_mbrs.size());
ret.addElement(tmp_mbrs.elementAt(index));
tmp_mbrs.removeElementAt(index);
}
return ret;
}
public static Object pickRandomElement(List list) {
if(list == null) return null;
int size=list.size();
int index=(int)((Math.random() * size * 10) % size);
return list.get(index);
}
public static Object pickRandomElement(Object[] array) {
if(array == null) return null;
int size=array.length;
int index=(int)((Math.random() * size * 10) % size);
return array[index];
}
/**
* Returns all members that left between 2 views. All members that are element of old_mbrs but not element of
* new_mbrs are returned.
*/
public static Vector<Address> determineLeftMembers(Vector<Address> old_mbrs, Vector<Address> new_mbrs) {
Vector<Address> retval=new Vector<Address>();
Address mbr;
if(old_mbrs == null || new_mbrs == null)
return retval;
for(int i=0; i < old_mbrs.size(); i++) {
mbr=old_mbrs.elementAt(i);
if(!new_mbrs.contains(mbr))
retval.addElement(mbr);
}
return retval;
}
public static String printMembers(Vector v) {
StringBuilder sb=new StringBuilder("(");
boolean first=true;
Object el;
if(v != null) {
for(int i=0; i < v.size(); i++) {
if(!first)
sb.append(", ");
else
first=false;
el=v.elementAt(i);
sb.append(el);
}
}
sb.append(')');
return sb.toString();
}
/**
Makes sure that we detect when a peer connection is in the closed state (not closed while we send data,
but before we send data). Two writes ensure that, if the peer closed the connection, the first write
will send the peer from FIN to RST state, and the second will cause a signal (IOException).
*/
public static void doubleWrite(byte[] buf, OutputStream out) throws Exception {
if(buf.length > 1) {
out.write(buf, 0, 1);
out.write(buf, 1, buf.length - 1);
}
else {
out.write(buf, 0, 0);
out.write(buf);
}
}
/**
Makes sure that we detect when a peer connection is in the closed state (not closed while we send data,
but before we send data). Two writes ensure that, if the peer closed the connection, the first write
will send the peer from FIN to RST state, and the second will cause a signal (IOException).
*/
public static void doubleWrite(byte[] buf, int offset, int length, OutputStream out) throws Exception {
if(length > 1) {
out.write(buf, offset, 1);
out.write(buf, offset+1, length - 1);
}
else {
out.write(buf, offset, 0);
out.write(buf, offset, length);
}
}
/**
* if we were to register for OP_WRITE and send the remaining data on
* readyOps for this channel we have to either block the caller thread or
* queue the message buffers that may arrive while waiting for OP_WRITE.
* Instead of the above approach this method will continuously write to the
* channel until the buffer sent fully.
*/
public static void writeFully(ByteBuffer buf, WritableByteChannel out) throws IOException {
int written = 0;
int toWrite = buf.limit();
while (written < toWrite) {
written += out.write(buf);
}
}
// /* double writes are not required.*/
// public static void doubleWriteBuffer(
// ByteBuffer buf,
// WritableByteChannel out)
// throws Exception
// if (buf.limit() > 1)
// int actualLimit = buf.limit();
// buf.limit(1);
// writeFully(buf,out);
// buf.limit(actualLimit);
// writeFully(buf,out);
// else
// buf.limit(0);
// writeFully(buf,out);
// buf.limit(1);
// writeFully(buf,out);
public static long sizeOf(String classname) {
Object inst;
byte[] data;
try {
inst=Util.loadClass(classname, null).newInstance();
data=Util.objectToByteBuffer(inst);
return data.length;
}
catch(Exception ex) {
return -1;
}
}
public static long sizeOf(Object inst) {
byte[] data;
try {
data=Util.objectToByteBuffer(inst);
return data.length;
}
catch(Exception ex) {
return -1;
}
}
public static int sizeOf(Streamable inst) {
byte[] data;
ByteArrayOutputStream output;
DataOutputStream out;
try {
output=new ByteArrayOutputStream();
out=new DataOutputStream(output);
inst.writeTo(out);
out.flush();
data=output.toByteArray();
return data.length;
}
catch(Exception ex) {
return -1;
}
}
/**
* Tries to load the class from the current thread's context class loader. If
* not successful, tries to load the class from the current instance.
* @param classname Desired class.
* @param clazz Class object used to obtain a class loader
* if no context class loader is available.
* @return Class, or null on failure.
*/
public static Class loadClass(String classname, Class clazz) throws ClassNotFoundException {
ClassLoader loader;
try {
loader=Thread.currentThread().getContextClassLoader();
if(loader != null) {
return loader.loadClass(classname);
}
}
catch(Throwable t) {
}
if(clazz != null) {
try {
loader=clazz.getClassLoader();
if(loader != null) {
return loader.loadClass(classname);
}
}
catch(Throwable t) {
}
}
try {
loader=ClassLoader.getSystemClassLoader();
if(loader != null) {
return loader.loadClass(classname);
}
}
catch(Throwable t) {
}
throw new ClassNotFoundException(classname);
}
public static InputStream getResourceAsStream(String name, Class clazz) {
ClassLoader loader;
InputStream retval=null;
try {
loader=Thread.currentThread().getContextClassLoader();
if(loader != null) {
retval=loader.getResourceAsStream(name);
if(retval != null)
return retval;
}
}
catch(Throwable t) {
}
if(clazz != null) {
try {
loader=clazz.getClassLoader();
if(loader != null) {
retval=loader.getResourceAsStream(name);
if(retval != null)
return retval;
}
}
catch(Throwable t) {
}
}
try {
loader=ClassLoader.getSystemClassLoader();
if(loader != null) {
return loader.getResourceAsStream(name);
}
}
catch(Throwable t) {
}
return retval;
}
/** Checks whether 2 Addresses are on the same host */
public static boolean sameHost(Address one, Address two) {
InetAddress a, b;
String host_a, host_b;
if(one == null || two == null) return false;
if(!(one instanceof IpAddress) || !(two instanceof IpAddress)) {
return false;
}
a=((IpAddress)one).getIpAddress();
b=((IpAddress)two).getIpAddress();
if(a == null || b == null) return false;
host_a=a.getHostAddress();
host_b=b.getHostAddress();
// System.out.println("host_a=" + host_a + ", host_b=" + host_b);
return host_a.equals(host_b);
}
public static boolean fileExists(String fname) {
return (new File(fname)).exists();
}
/**
* Parses comma-delimited longs; e.g., 2000,4000,8000.
* Returns array of long, or null.
*/
public static long[] parseCommaDelimitedLongs(String s) {
StringTokenizer tok;
Vector<Long> v=new Vector<Long>();
Long l;
long[] retval=null;
if(s == null) return null;
tok=new StringTokenizer(s, ",");
while(tok.hasMoreTokens()) {
l=new Long(tok.nextToken());
v.addElement(l);
}
if(v.isEmpty()) return null;
retval=new long[v.size()];
for(int i=0; i < v.size(); i++)
retval[i]=v.elementAt(i).longValue();
return retval;
}
/** e.g. "bela,jeannette,michelle" --> List{"bela", "jeannette", "michelle"} */
public static List<String> parseCommaDelimitedStrings(String l) {
return parseStringList(l, ",");
}
/**
* Input is "daddy[8880],sindhu[8880],camille[5555]. Return List of
* IpAddresses
*/
public static List<IpAddress> parseCommaDelimetedHosts(String hosts, int port_range) throws UnknownHostException {
StringTokenizer tok=new StringTokenizer(hosts, ",");
String t;
IpAddress addr;
Set<IpAddress> retval=new HashSet<IpAddress>();
while(tok.hasMoreTokens()) {
t=tok.nextToken().trim();
String host=t.substring(0, t.indexOf('['));
host=host.trim();
int port=Integer.parseInt(t.substring(t.indexOf('[') + 1, t.indexOf(']')));
for(int i=port;i < port + port_range;i++) {
addr=new IpAddress(host, i);
retval.add(addr);
}
}
return Collections.unmodifiableList(new LinkedList<IpAddress>(retval));
}
public static List<String> parseStringList(String l, String separator) {
List<String> tmp=new LinkedList<String>();
StringTokenizer tok=new StringTokenizer(l, separator);
String t;
while(tok.hasMoreTokens()) {
t=tok.nextToken();
tmp.add(t.trim());
}
return tmp;
}
public static String parseString(ByteBuffer buf) {
return parseString(buf, true);
}
public static String parseString(ByteBuffer buf, boolean discard_whitespace) {
StringBuilder sb=new StringBuilder();
char ch;
// read white space
while(buf.remaining() > 0) {
ch=(char)buf.get();
if(!Character.isWhitespace(ch)) {
buf.position(buf.position() -1);
break;
}
}
if(buf.remaining() == 0)
return null;
while(buf.remaining() > 0) {
ch=(char)buf.get();
if(!Character.isWhitespace(ch)) {
sb.append(ch);
}
else
break;
}
// read white space
if(discard_whitespace) {
while(buf.remaining() > 0) {
ch=(char)buf.get();
if(!Character.isWhitespace(ch)) {
buf.position(buf.position() -1);
break;
}
}
}
return sb.toString();
}
public static int readNewLine(ByteBuffer buf) {
char ch;
int num=0;
while(buf.remaining() > 0) {
ch=(char)buf.get();
num++;
if(ch == '\n')
break;
}
return num;
}
/**
* Reads and discards all characters from the input stream until a \r\n or EOF is encountered
* @param in
* @return
*/
public static int discardUntilNewLine(InputStream in) {
int ch;
int num=0;
while(true) {
try {
ch=in.read();
if(ch == -1)
break;
num++;
if(ch == '\n')
break;
}
catch(IOException e) {
break;
}
}
return num;
}
/**
* Reads a line of text. A line is considered to be terminated by any one
* of a line feed ('\n'), a carriage return ('\r'), or a carriage return
* followed immediately by a linefeed.
*
* @return A String containing the contents of the line, not including
* any line-termination characters, or null if the end of the
* stream has been reached
*
* @exception IOException If an I/O error occurs
*/
public static String readLine(InputStream in) throws IOException {
StringBuilder sb=new StringBuilder(35);
int ch;
while(true) {
ch=in.read();
if(ch == -1)
return null;
if(ch == '\r') {
;
}
else {
if(ch == '\n')
break;
else {
sb.append((char)ch);
}
}
}
return sb.toString();
}
public static void writeString(ByteBuffer buf, String s) {
for(int i=0; i < s.length(); i++)
buf.put((byte)s.charAt(i));
}
/**
*
* @param s
* @return List<NetworkInterface>
*/
public static List<NetworkInterface> parseInterfaceList(String s) throws Exception {
List<NetworkInterface> interfaces=new ArrayList<NetworkInterface>(10);
if(s == null)
return null;
StringTokenizer tok=new StringTokenizer(s, ",");
String interface_name;
NetworkInterface intf;
while(tok.hasMoreTokens()) {
interface_name=tok.nextToken();
// try by name first (e.g. (eth0")
intf=NetworkInterface.getByName(interface_name);
// next try by IP address or symbolic name
if(intf == null)
intf=NetworkInterface.getByInetAddress(InetAddress.getByName(interface_name));
if(intf == null)
throw new Exception("interface " + interface_name + " not found");
if(!interfaces.contains(intf)) {
interfaces.add(intf);
}
}
return interfaces;
}
public static String print(List<NetworkInterface> interfaces) {
StringBuilder sb=new StringBuilder();
boolean first=true;
for(NetworkInterface intf: interfaces) {
if(first) {
first=false;
}
else {
sb.append(", ");
}
sb.append(intf.getName());
}
return sb.toString();
}
public static String shortName(String hostname) {
int index;
StringBuilder sb=new StringBuilder();
if(hostname == null) return null;
index=hostname.indexOf('.');
if(index > 0 && !Character.isDigit(hostname.charAt(0)))
sb.append(hostname.substring(0, index));
else
sb.append(hostname);
return sb.toString();
}
public static String shortName(InetAddress hostname) {
if(hostname == null) return null;
StringBuilder sb=new StringBuilder();
if(resolve_dns)
sb.append(hostname.getHostName());
else
sb.append(hostname.getHostAddress());
return sb.toString();
}
/** Finds first available port starting at start_port and returns server socket */
public static ServerSocket createServerSocket(int start_port) {
ServerSocket ret=null;
while(true) {
try {
ret=new ServerSocket(start_port);
}
catch(BindException bind_ex) {
start_port++;
continue;
}
catch(IOException io_ex) {
}
break;
}
return ret;
}
public static ServerSocket createServerSocket(InetAddress bind_addr, int start_port) {
ServerSocket ret=null;
while(true) {
try {
ret=new ServerSocket(start_port, 50, bind_addr);
}
catch(BindException bind_ex) {
start_port++;
continue;
}
catch(IOException io_ex) {
}
break;
}
return ret;
}
/**
* Creates a DatagramSocket bound to addr. If addr is null, socket won't be bound. If address is already in use,
* start_port will be incremented until a socket can be created.
* @param addr The InetAddress to which the socket should be bound. If null, the socket will not be bound.
* @param port The port which the socket should use. If 0, a random port will be used. If > 0, but port is already
* in use, it will be incremented until an unused port is found, or until MAX_PORT is reached.
*/
public static DatagramSocket createDatagramSocket(InetAddress addr, int port) throws Exception {
DatagramSocket sock=null;
if(addr == null) {
if(port == 0) {
return new DatagramSocket();
}
else {
while(port < MAX_PORT) {
try {
return new DatagramSocket(port);
}
catch(BindException bind_ex) { // port already used
port++;
}
}
}
}
else {
if(port == 0) port=1024;
while(port < MAX_PORT) {
try {
return new DatagramSocket(port, addr);
}
catch(BindException bind_ex) { // port already used
port++;
}
}
}
return sock; // will never be reached, but the stupid compiler didn't figure it out...
}
public static MulticastSocket createMulticastSocket(int port) throws IOException {
return createMulticastSocket(null, port, null);
}
public static MulticastSocket createMulticastSocket(InetAddress mcast_addr, int port, Log log) throws IOException {
if(mcast_addr != null && !mcast_addr.isMulticastAddress()) {
if(log != null && log.isWarnEnabled())
log.warn("mcast_addr (" + mcast_addr + ") is not a multicast address, will be ignored");
return new MulticastSocket(port);
}
SocketAddress saddr=new InetSocketAddress(mcast_addr, port);
MulticastSocket retval=null;
try {
retval=new MulticastSocket(saddr);
}
catch(IOException ex) {
if(log != null && log.isWarnEnabled()) {
StringBuilder sb=new StringBuilder();
String type=mcast_addr != null ? mcast_addr instanceof Inet4Address? "IPv4" : "IPv6" : "n/a";
sb.append("could not bind to " + mcast_addr + " (" + type + " address)");
sb.append("; make sure your mcast_addr is of the same type as the IP stack (IPv4 or IPv6).");
sb.append("\nWill ignore mcast_addr, but this may lead to cross talking " +
"(see http:
sb.append("\nException was: " + ex);
log.warn(sb);
}
}
if(retval == null)
retval=new MulticastSocket(port);
return retval;
}
/**
* Returns the address of the interface to use defined by bind_addr and bind_interface
* @param props
* @return
* @throws UnknownHostException
* @throws SocketException
*/
public static InetAddress getBindAddress(Properties props) throws UnknownHostException, SocketException {
boolean ignore_systemprops=Util.isBindAddressPropertyIgnored();
String bind_addr=Util.getProperty(new String[]{Global.BIND_ADDR, Global.BIND_ADDR_OLD}, props, "bind_addr",
ignore_systemprops, null);
String bind_interface=Util.getProperty(new String[]{Global.BIND_INTERFACE, null}, props, "bind_interface",
ignore_systemprops, null);
InetAddress retval=null, bind_addr_host=null;
if(bind_addr != null) {
bind_addr_host=InetAddress.getByName(bind_addr);
}
if(bind_interface != null) {
NetworkInterface intf=NetworkInterface.getByName(bind_interface);
if(intf != null) {
for(Enumeration<InetAddress> addresses=intf.getInetAddresses(); addresses.hasMoreElements();) {
InetAddress addr=addresses.nextElement();
if(bind_addr == null) {
retval=addr;
break;
}
else {
if(bind_addr_host != null) {
if(bind_addr_host.equals(addr)) {
retval=addr;
break;
}
}
else if(addr.getHostAddress().trim().equalsIgnoreCase(bind_addr)) {
retval=addr;
break;
}
}
}
}
else {
throw new UnknownHostException("network interface " + bind_interface + " not found");
}
}
if(retval == null) {
retval=bind_addr != null? InetAddress.getByName(bind_addr) : InetAddress.getLocalHost();
}
//check all bind_address against NetworkInterface.getByInetAddress() to see if it exists on the machine
if(NetworkInterface.getByInetAddress(retval) == null) {
throw new UnknownHostException("Invalid bind address " + retval);
}
if(props != null) {
props.remove("bind_addr");
props.remove("bind_interface");
}
return retval;
}
public static boolean checkForLinux() {
String os=System.getProperty("os.name");
return os != null && os.toLowerCase().startsWith("linux");
}
public static boolean checkForSolaris() {
String os=System.getProperty("os.name");
return os != null && os.toLowerCase().startsWith("sun");
}
public static boolean checkForWindows() {
String os=System.getProperty("os.name");
return os != null && os.toLowerCase().startsWith("win");
}
public static void prompt(String s) {
System.out.println(s);
System.out.flush();
try {
while(System.in.available() > 0)
System.in.read();
System.in.read();
}
catch(IOException e) {
e.printStackTrace();
}
}
public static int getJavaVersion() {
String version=System.getProperty("java.version");
int retval=0;
if(version != null) {
if(version.startsWith("1.2"))
return 12;
if(version.startsWith("1.3"))
return 13;
if(version.startsWith("1.4"))
return 14;
if(version.startsWith("1.5"))
return 15;
if(version.startsWith("5"))
return 15;
if(version.startsWith("1.6"))
return 16;
if(version.startsWith("6"))
return 16;
}
return retval;
}
public static <T> Vector<T> unmodifiableVector(Vector<? extends T> v) {
if(v == null) return null;
return new UnmodifiableVector(v);
}
public static String memStats(boolean gc) {
StringBuilder sb=new StringBuilder();
Runtime rt=Runtime.getRuntime();
if(gc)
rt.gc();
long free_mem, total_mem, used_mem;
free_mem=rt.freeMemory();
total_mem=rt.totalMemory();
used_mem=total_mem - free_mem;
sb.append("Free mem: ").append(free_mem).append("\nUsed mem: ").append(used_mem);
sb.append("\nTotal mem: ").append(total_mem);
return sb.toString();
}
// public static InetAddress getFirstNonLoopbackAddress() throws SocketException {
// Enumeration en=NetworkInterface.getNetworkInterfaces();
// while(en.hasMoreElements()) {
// NetworkInterface i=(NetworkInterface)en.nextElement();
// for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
// InetAddress addr=(InetAddress)en2.nextElement();
// if(!addr.isLoopbackAddress())
// return addr;
// return null;
public static InetAddress getFirstNonLoopbackAddress() throws SocketException {
Enumeration en=NetworkInterface.getNetworkInterfaces();
boolean preferIpv4=Boolean.getBoolean(Global.IPv4);
boolean preferIPv6=Boolean.getBoolean(Global.IPv6);
while(en.hasMoreElements()) {
NetworkInterface i=(NetworkInterface)en.nextElement();
for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
InetAddress addr=(InetAddress)en2.nextElement();
if(!addr.isLoopbackAddress()) {
if(addr instanceof Inet4Address) {
if(preferIPv6)
continue;
return addr;
}
if(addr instanceof Inet6Address) {
if(preferIpv4)
continue;
return addr;
}
}
}
}
return null;
}
public static boolean isIPv4Stack() {
return getIpStack()== 4;
}
public static boolean isIPv6Stack() {
return getIpStack() == 6;
}
public static short getIpStack() {
short retval=2;
if(Boolean.getBoolean(Global.IPv4)) {
retval=4;
}
if(Boolean.getBoolean(Global.IPv6)) {
retval=6;
}
return retval;
}
public static InetAddress getFirstNonLoopbackIPv6Address() throws SocketException {
Enumeration en=NetworkInterface.getNetworkInterfaces();
while(en.hasMoreElements()) {
NetworkInterface i=(NetworkInterface)en.nextElement();
for(Enumeration en2=i.getInetAddresses(); en2.hasMoreElements();) {
InetAddress addr=(InetAddress)en2.nextElement();
if(!addr.isLoopbackAddress()) {
if(addr instanceof Inet4Address) {
continue;
}
if(addr instanceof Inet6Address) {
return addr;
}
}
}
}
return null;
}
public static List<NetworkInterface> getAllAvailableInterfaces() throws SocketException {
List<NetworkInterface> retval=new ArrayList<NetworkInterface>(10);
NetworkInterface intf;
for(Enumeration en=NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
intf=(NetworkInterface)en.nextElement();
retval.add(intf);
}
return retval;
}
/**
* Returns a value associated wither with one or more system properties, or found in the props map
* @param system_props
* @param props List of properties read from the configuration file
* @param prop_name The name of the property, will be removed from props if found
* @param ignore_sysprops If true, system properties are not used and the values will only be retrieved from
* props (not system_props)
* @param default_value Used to return a default value if the properties or system properties didn't have the value
* @return The value, or null if not found
*/
public static String getProperty(String[] system_props, Properties props, String prop_name,
boolean ignore_sysprops, String default_value) {
String retval=null;
if(props != null && prop_name != null) {
retval=props.getProperty(prop_name);
props.remove(prop_name);
}
if(!ignore_sysprops) {
String tmp, prop;
if(system_props != null) {
for(int i=0; i < system_props.length; i++) {
prop=system_props[i];
if(prop != null) {
try {
tmp=System.getProperty(prop);
if(tmp != null)
return tmp; // system properties override config file definitions
}
catch(SecurityException ex) {}
}
}
}
}
if(retval == null)
return default_value;
return retval;
}
public static boolean isBindAddressPropertyIgnored() {
try {
String tmp=System.getProperty(Global.IGNORE_BIND_ADDRESS_PROPERTY);
if(tmp == null) {
tmp=System.getProperty(Global.IGNORE_BIND_ADDRESS_PROPERTY_OLD);
if(tmp == null)
return false;
}
tmp=tmp.trim().toLowerCase();
return !(tmp.equals("false") || tmp.equals("no") || tmp.equals("off")) && (tmp.equals("true") || tmp.equals("yes") || tmp.equals("on"));
}
catch(SecurityException ex) {
return false;
}
}
public static MBeanServer getMBeanServer() {
ArrayList servers=MBeanServerFactory.findMBeanServer(null);
if(servers == null || servers.isEmpty())
return null;
// return 'jboss' server if available
for(int i=0; i < servers.size(); i++) {
MBeanServer srv=(MBeanServer)servers.get(i);
if("jboss".equalsIgnoreCase(srv.getDefaultDomain()))
return srv;
}
// return first available server
return (MBeanServer)servers.get(0);
}
public static void main(String args[]) throws Exception {
System.out.println("IPv4: " + isIPv4Stack());
System.out.println("IPv6: " + isIPv6Stack());
}
public static String generateList(Collection c, String separator) {
if(c == null) return null;
StringBuilder sb=new StringBuilder();
boolean first=true;
for(Iterator it=c.iterator(); it.hasNext();) {
if(first) {
first=false;
}
else {
sb.append(separator);
}
sb.append(it.next());
}
return sb.toString();
}
/**
* Replaces variables of ${var:default} with System.getProperty(var, default). If no variables are found, returns
* the same string, otherwise a copy of the string with variables substituted
* @param val
* @return A string with vars replaced, or the same string if no vars found
*/
public static String substituteVariable(String val) {
if(val == null)
return val;
String retval=val, prev;
while(retval.contains("${")) { // handle multiple variables in val
prev=retval;
retval=_substituteVar(retval);
if(retval.equals(prev))
break;
}
return retval;
}
private static String _substituteVar(String val) {
int start_index, end_index;
start_index=val.indexOf("${");
if(start_index == -1)
return val;
end_index=val.indexOf("}", start_index+2);
if(end_index == -1)
throw new IllegalArgumentException("missing \"}\" in " + val);
String tmp=getProperty(val.substring(start_index +2, end_index));
if(tmp == null)
return val;
StringBuilder sb=new StringBuilder();
sb.append(val.substring(0, start_index));
sb.append(tmp);
sb.append(val.substring(end_index+1));
return sb.toString();
}
private static String getProperty(String s) {
String var, default_val, retval=null;
int index=s.indexOf(":");
if(index >= 0) {
var=s.substring(0, index);
default_val=s.substring(index+1);
retval=System.getProperty(var, default_val);
}
else {
var=s;
retval=System.getProperty(var);
}
return retval;
}
/**
* Used to convert a byte array in to a java.lang.String object
* @param bytes the bytes to be converted
* @return the String representation
*/
private static String getString(byte[] bytes) {
StringBuilder sb=new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
sb.append(0x00FF & b);
if (i + 1 < bytes.length) {
sb.append("-");
}
}
return sb.toString();
}
/**
* Converts a java.lang.String in to a MD5 hashed String
* @param source the source String
* @return the MD5 hashed version of the string
*/
public static String md5(String source) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytes = md.digest(source.getBytes());
return getString(bytes);
} catch (Exception e) {
return null;
}
}
/**
* Converts a java.lang.String in to a SHA hashed String
* @param source the source String
* @return the MD5 hashed version of the string
*/
public static String sha(String source) {
try {
MessageDigest md = MessageDigest.getInstance("SHA");
byte[] bytes = md.digest(source.getBytes());
return getString(bytes);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
} |
package com.algolia.search.saas;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import org.json.JSONArray;
public class Query {
public enum QueryType
{
/// all query words are interpreted as prefixes.
PREFIX_ALL,
/// only the last word is interpreted as a prefix (default behavior).
PREFIX_LAST,
/// no query word is interpreted as a prefix. This option is not recommended.
PREFIX_NONE
}
public enum RemoveWordsType
{
// when a query does not return any result, the final word will be removed until there is results. This option is particulary useful on e-commerce websites
REMOVE_LAST_WORDS,
// when a query does not return any result, the first word will be removed until there is results. This option is useful on adress search.
REMOVE_FIRST_WORDS,
// No specific processing is done when a query does not return any result.
REMOVE_NONE,
/// When a query does not return any result, a second trial will be made with all words as optional (which is equivalent to transforming the AND operand between query terms in a OR operand)
REMOVE_ALLOPTIONAL
}
protected List<String> attributes;
protected List<String> attributesToHighlight;
protected List<String> attributesToSnippet;
protected int minWordSizeForApprox1;
protected int minWordSizeForApprox2;
protected boolean getRankingInfo;
protected boolean ignorePlural;
protected boolean distinct;
protected boolean advancedSyntax;
protected int page;
protected int hitsPerPage;
protected String restrictSearchableAttributes;
protected String tags;
protected String numerics;
protected String insideBoundingBox;
protected String aroundLatLong;
protected boolean aroundLatLongViaIP;
protected String query;
protected QueryType queryType;
protected String optionalWords;
protected String facets;
protected String facetFilters;
protected int maxNumberOfFacets;
protected boolean analytics;
protected boolean synonyms;
protected boolean replaceSynonyms;
protected boolean typoTolerance;
protected boolean allowTyposOnNumericTokens;
protected RemoveWordsType removeWordsIfNoResult;
public Query(String query) {
minWordSizeForApprox1 = 3;
minWordSizeForApprox2 = 7;
getRankingInfo = false;
ignorePlural = false;
distinct = false;
page = 0;
hitsPerPage = 20;
this.query = query;
queryType = QueryType.PREFIX_LAST;
maxNumberOfFacets = -1;
advancedSyntax = false;
analytics = synonyms = replaceSynonyms = typoTolerance = allowTyposOnNumericTokens = true;
removeWordsIfNoResult = RemoveWordsType.REMOVE_NONE;
}
public Query() {
minWordSizeForApprox1 = 3;
minWordSizeForApprox2 = 7;
getRankingInfo = false;
ignorePlural = false;
distinct = false;
page = 0;
hitsPerPage = 20;
queryType = QueryType.PREFIX_ALL;
maxNumberOfFacets = -1;
advancedSyntax = false;
analytics = synonyms = replaceSynonyms = typoTolerance = allowTyposOnNumericTokens = true;
removeWordsIfNoResult = RemoveWordsType.REMOVE_NONE;
}
/**
* Select the strategy to adopt when a query does not return any result.
*/
public Query removeWordsIfNoResult(RemoveWordsType type)
{
this.removeWordsIfNoResult = type;
return this;
}
/**
* List of attributes you want to use for textual search (must be a subset of the attributesToIndex
* index setting). Attributes are separated with a comma (for example @"name,address").
* You can also use a JSON string array encoding (for example encodeURIComponent("[\"name\",\"address\"]")).
* By default, all attributes specified in attributesToIndex settings are used to search.
*/
public Query restrictSearchableAttributes(String attributes)
{
this.restrictSearchableAttributes = attributes;
return this;
}
/**
* Select how the query words are interpreted:
*/
public Query setQueryType(QueryType type)
{
this.queryType = type;
return this;
}
/**
* Set the full text query
*/
public Query setQueryString(String query)
{
this.query = query;
return this;
}
/**
* Specify the list of attribute names to retrieve.
* By default all attributes are retrieved.
*/
public Query setAttributesToRetrieve(List<String> attributes) {
this.attributes = attributes;
return this;
}
/**
* Specify the list of attribute names to highlight.
* By default indexed attributes are highlighted.
*/
public Query setAttributesToHighlight(List<String> attributes) {
this.attributesToHighlight = attributes;
return this;
}
/**
* Specify the list of attribute names to Snippet alongside the number of words to return (syntax is 'attributeName:nbWords').
* By default no snippet is computed.
*/
public Query setAttributesToSnippet(List<String> attributes) {
this.attributesToSnippet = attributes;
return this;
}
/**
*
* @param If set to true, enable the distinct feature (disabled by default) if the attributeForDistinct index setting is set.
* This feature is similar to the SQL "distinct" keyword: when enabled in a query with the distinct=1 parameter,
* all hits containing a duplicate value for the attributeForDistinct attribute are removed from results.
* For example, if the chosen attribute is show_name and several hits have the same value for show_name, then only the best
* one is kept and others are removed.
*/
public Query enableDistinct(boolean distinct) {
this.distinct = distinct;
return this;
}
/**
* @param If set to false, this query will not be taken into account in analytics feature. Default to true.
*/
public Query enableAnalytics(boolean enabled) {
this.analytics = enabled;
return this;
}
/**
* @param If set to false, this query will not use synonyms defined in configuration. Default to true.
*/
public Query enableSynonyms(boolean enabled) {
this.synonyms = enabled;
return this;
}
/**
* @param If set to false, words matched via synonyms expansion will not be replaced by the matched synonym in highlight result. Default to true.
*/
public Query enableReplaceSynonymsInHighlight(boolean enabled) {
this.replaceSynonyms = enabled;
return this;
}
/**
* @param If set to false, disable typo-tolerance. Default to true.
*/
public Query enableTypoTolerance(boolean enabled) {
this.typoTolerance = enabled;
return this;
}
/**
* Specify the minimum number of characters in a query word to accept one typo in this word.
* Defaults to 3.
*/
public Query setMinWordSizeToAllowOneTypo(int nbChars) {
minWordSizeForApprox1 = nbChars;
return this;
}
/**
* Specify the minimum number of characters in a query word to accept two typos in this word.
* Defaults to 7.
*/
public Query setMinWordSizeToAllowTwoTypos(int nbChars) {
minWordSizeForApprox2 = nbChars;
return this;
}
/**
* @param If set to false, disable typo-tolerance on numeric tokens. Default to true.
*/
public Query enableTyposOnNumericTokens(boolean enabled) {
this.allowTyposOnNumericTokens = enabled;
return this;
}
/**
* if set, the result hits will contain ranking information in _rankingInfo attribute.
*/
public Query getRankingInfo(boolean enabled) {
this.getRankingInfo = enabled;
return this;
}
/**
* If set to true, plural won't be considered as a typo (for example car/cars will be considered as equals). Default to false.
*/
public Query ignorePlural(boolean enabled) {
this.ignorePlural = enabled;
return this;
}
/**
* Set the page to retrieve (zero base). Defaults to 0.
*/
public Query setPage(int page) {
this.page = page;
return this;
}
/**
* Set the number of hits per page. Defaults to 10.
*/
public Query setHitsPerPage(int nbHitsPerPage) {
this.hitsPerPage = nbHitsPerPage;
return this;
}
/**
* Set the number of hits per page. Defaults to 10.
* @deprecated Use {@code setHitsPerPage}
*/
@Deprecated
public Query setNbHitsPerPage(int nbHitsPerPage) {
return setHitsPerPage(nbHitsPerPage);
}
/**
* Search for entries around a given latitude/longitude.
* @param radius set the maximum distance in meters.
* Note: at indexing, geoloc of an object should be set with _geoloc attribute containing lat and lng attributes (for example {"_geoloc":{"lat":48.853409, "lng":2.348800}})
*/
public Query aroundLatitudeLongitude(float latitude, float longitude, int radius) {
aroundLatLong = "aroundLatLng=" + latitude + "," + longitude + "&aroundRadius=" + radius;
return this;
}
/**
* Search for entries around a given latitude/longitude.
* @param radius set the maximum distance in meters.
* @param precision set the precision for ranking (for example if you set precision=100, two objects that are distant of less than 100m will be considered as identical for "geo" ranking parameter).
* Note: at indexing, geoloc of an object should be set with _geoloc attribute containing lat and lng attributes (for example {"_geoloc":{"lat":48.853409, "lng":2.348800}})
*/
public Query aroundLatitudeLongitude(float latitude, float longitude, int radius, int precision) {
aroundLatLong = "aroundLatLng=" + latitude + "," + longitude + "&aroundRadius=" + radius + "&aroundPrecision=" + precision;
return this;
}
/**
* Search for entries around the latitude/longitude of user (using IP geolocation)
* @param radius set the maximum distance in meters.
* Note: at indexing, geoloc of an object should be set with _geoloc attribute containing lat and lng attributes (for example {"_geoloc":{"lat":48.853409, "lng":2.348800}})
*/
public Query aroundLatitudeLongitudeViaIP(boolean enabled, int radius) {
aroundLatLong = "aroundRadius=" + radius;
aroundLatLongViaIP = enabled;
return this;
}
/**
* Search for entries around the latitude/longitude of user (using IP geolocation)
* @param radius set the maximum distance in meters.
* @param precision set the precision for ranking (for example if you set precision=100, two objects that are distant of less than 100m will be considered as identical for "geo" ranking parameter).
* Note: at indexing, geoloc of an object should be set with _geoloc attribute containing lat and lng attributes (for example {"_geoloc":{"lat":48.853409, "lng":2.348800}})
*/
public Query aroundLatitudeLongitudeViaIP(boolean enabled, int radius, int precision) {
aroundLatLong = "aroundRadius=" + radius + "&aroundPrecision=" + precision;
aroundLatLongViaIP = enabled;
return this;
}
/**
* Search for entries inside a given area defined by the two extreme points of a rectangle.
* At indexing, geoloc of an object should be set with _geoloc attribute containing lat and lng attributes (for example {"_geoloc":{"lat":48.853409, "lng":2.348800}})
*/
public Query insideBoundingBox(float latitudeP1, float longitudeP1, float latitudeP2, float longitudeP2) {
insideBoundingBox = "insideBoundingBox=" + latitudeP1 + "," + longitudeP1 + "," + latitudeP2 + "," + longitudeP2;
return this;
}
/**
* Set the list of words that should be considered as optional when found in the query.
* @param words The list of optional words, comma separated.
*/
public Query setOptionalWords(String words) {
this.optionalWords = words;
return this;
}
/**
* Set the list of words that should be considered as optional when found in the query.
* @param words The list of optional words.
*/
public Query setOptionalWords(List<String> words) {
StringBuilder builder = new StringBuilder();
for (String word : words) {
builder.append(word);
builder.append(",");
}
this.optionalWords = builder.toString();
return this;
}
/**
* Filter the query by a list of facets. Each filter is encoded as `attributeName:value`.
*/
public Query setFacetFilters(List<String> facets) {
JSONArray obj = new JSONArray();
for (String facet : facets) {
obj.put(facet);
}
this.facetFilters = obj.toString();
return this;
}
public Query setFacetFilters(String facetsFilter) {
this.facetFilters = facetsFilter;
return this;
}
/**
* List of object attributes that you want to use for faceting. <br/>
* Only attributes that have been added in **attributesForFaceting** index setting can be used in this parameter.
* You can also use `*` to perform faceting on all attributes specified in **attributesForFaceting**.
*/
public Query setFacets(List<String> facets) {
JSONArray obj = new JSONArray();
for (String facet : facets) {
obj.put(facet);
}
this.facets = obj.toString();
return this;
}
/**
* Limit the number of facet values returned for each facet.
*/
public Query setMaxNumberOfFacets(int n) {
this.maxNumberOfFacets = n;
return this;
}
/**
* Filter the query by a set of tags. You can AND tags by separating them by commas. To OR tags, you must add parentheses. For example tag1,(tag2,tag3) means tag1 AND (tag2 OR tag3).
* At indexing, tags should be added in the _tags attribute of objects (for example {"_tags":["tag1","tag2"]} )
*/
public Query setTagFilters(String tags) {
this.tags = tags;
return this;
}
/**
* Add a list of numeric filters separated by a comma.
* The syntax of one filter is `attributeName` followed by `operand` followed by `value. Supported operands are `<`, `<=`, `=`, `>` and `>=`.
* You can have multiple conditions on one attribute like for example `numerics=price>100,price<1000`.
*/
public Query setNumericFilters(String numerics) {
this.numerics = numerics;
return this;
}
/**
* Add a list of numeric filters separated by a comma.
* The syntax of one filter is `attributeName` followed by `operand` followed by `value. Supported operands are `<`, `<=`, `=`, `>` and `>=`.
* You can have multiple conditions on one attribute like for example `numerics=price>100,price<1000`.
*/
public Query setNumericFilters(List<String> numerics) {
StringBuilder builder = new StringBuilder();
boolean first = true;
for (String n : numerics) {
if (!first)
builder.append(",");
builder.append(n);
first = false;
}
this.numerics = builder.toString();
return this;
}
/**
* Enable the advanced query syntax. Defaults to false.
* - Phrase query: a phrase query defines a particular sequence of terms.
* A phrase query is build by Algolia's query parser for words surrounded by ".
* For example, "search engine" will retrieve records having search next to engine only.
* Typo-tolerance is disabled on phrase queries.
* - Prohibit operator: The prohibit operator excludes records that contain the term after the - symbol.
* For example search -engine will retrieve records containing search but not engine.
*/
public Query enableAvancedSyntax(boolean advancedSyntax) {
this.advancedSyntax = advancedSyntax;
return this;
}
protected String getQueryString() {
StringBuilder stringBuilder = new StringBuilder();
try {
if (attributes != null) {
stringBuilder.append("attributes=");
boolean first = true;
for (String attr : this.attributes) {
if (!first)
stringBuilder.append(",");
stringBuilder.append(URLEncoder.encode(attr, "UTF-8"));
first = false;
}
}
if (attributesToHighlight != null) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("attributesToHighlight=");
boolean first = true;
for (String attr : this.attributesToHighlight) {
if (!first)
stringBuilder.append(',');
stringBuilder.append(URLEncoder.encode(attr, "UTF-8"));
first = false;
}
}
if (attributesToSnippet != null) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("attributesToSnippet=");
boolean first = true;
for (String attr : this.attributesToSnippet) {
if (!first)
stringBuilder.append(',');
stringBuilder.append(URLEncoder.encode(attr, "UTF-8"));
first = false;
}
}
if (!typoTolerance) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("typoTolerance=false");
}
if (!allowTyposOnNumericTokens) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("allowTyposOnNumericTokens=false");
}
if (minWordSizeForApprox1 != 3) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("minWordSizefor1Typo=");
stringBuilder.append(minWordSizeForApprox1);
}
if (minWordSizeForApprox2 != 7) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("minWordSizefor2Typos=");
stringBuilder.append(minWordSizeForApprox2);
}
if (getRankingInfo) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("getRankingInfo=1");
}
if (ignorePlural) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("ignorePlural=true");
}
if (!analytics) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("analytics=0");
}
if (!synonyms) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("synonyms=0");
}
if (!replaceSynonyms) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("replaceSynonymsInHighlight=0");
}
if (distinct) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("distinct=1");
}
if (advancedSyntax) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("advancedSyntax=1");
}
if (page > 0) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("page=");
stringBuilder.append(page);
}
if (hitsPerPage != 20 && hitsPerPage > 0) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("hitsPerPage=");
stringBuilder.append(hitsPerPage);
}
if (tags != null) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("tagFilters=");
stringBuilder.append(URLEncoder.encode(tags, "UTF-8"));
}
if (numerics != null) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("numericFilters=");
stringBuilder.append(URLEncoder.encode(numerics, "UTF-8"));
}
if (insideBoundingBox != null) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append(insideBoundingBox);
} else if (aroundLatLong != null) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append(aroundLatLong);
}
if (aroundLatLongViaIP) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("aroundLatLngViaIP=true");
}
if (query != null) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("query=");
stringBuilder.append(URLEncoder.encode(query, "UTF-8"));
}
if (facets != null) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("facets=");
stringBuilder.append(URLEncoder.encode(facets, "UTF-8"));
}
if (facetFilters != null) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("facetFilters=");
stringBuilder.append(URLEncoder.encode(facetFilters, "UTF-8"));
}
if (maxNumberOfFacets > 0) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("maxNumberOfFacets=");
stringBuilder.append(maxNumberOfFacets);
}
if (optionalWords != null) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("optionalWords=");
stringBuilder.append(URLEncoder.encode(optionalWords, "UTF-8"));
}
if (restrictSearchableAttributes != null) {
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("restrictSearchableAttributes=");
stringBuilder.append(URLEncoder.encode(restrictSearchableAttributes, "UTF-8"));
}
switch (removeWordsIfNoResult) {
case REMOVE_LAST_WORDS:
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("removeWordsIfNoResult=LastWords");
break;
case REMOVE_FIRST_WORDS:
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("removeWordsIfNoResult=FirstWords");
break;
case REMOVE_ALLOPTIONAL:
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("removeWordsIfNoResult=allOptional");
break;
case REMOVE_NONE:
break;
}
switch (queryType) {
case PREFIX_ALL:
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("queryType=prefixAll");
break;
case PREFIX_LAST:
break;
case PREFIX_NONE:
if (stringBuilder.length() > 0)
stringBuilder.append('&');
stringBuilder.append("queryType=prefixNone");
break;
}
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return stringBuilder.toString();
}
} |
// $Id: Util.java,v 1.19 2004/10/05 16:04:20 belaban Exp $
package org.jgroups.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jgroups.Address;
import org.jgroups.Event;
import org.jgroups.Message;
import org.jgroups.conf.ClassConfigurator;
import org.jgroups.stack.IpAddress;
import java.io.*;
import java.net.BindException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.Vector;
/**
* Collection of various utility routines that can not be assigned to other classes.
*/
public class Util {
private static final Object mutex=new Object();
private static final ByteArrayOutputStream out_stream=new ByteArrayOutputStream(512);
protected static final Log log=LogFactory.getLog(Util.class);
// constants
public static final int MAX_PORT=65535; // highest port allocatable
public static final String DIAG_GROUP="DIAG_GROUP-BELA-322649"; // unique
/**
* Creates an object from a byte buffer
*/
public static Object objectFromByteBuffer(byte[] buffer) throws Exception {
synchronized(mutex) {
if(buffer == null) return null;
Object retval=null;
ByteArrayInputStream in_stream=new ByteArrayInputStream(buffer);
ObjectInputStream in=new ObjectInputStream(in_stream);
retval=in.readObject();
in.close();
if(retval == null)
return null;
return retval;
}
}
/**
* Serializes an object into a byte buffer.
* The object has to implement interface Serializable or Externalizable
*/
public static byte[] objectToByteBuffer(Object obj) throws Exception {
byte[] result=null;
synchronized(out_stream) {
out_stream.reset();
ObjectOutputStream out=new ObjectOutputStream(out_stream);
out.writeObject(obj);
result=out_stream.toByteArray();
out.close();
}
return result;
}
public static void writeAddress(Address addr, DataOutputStream out) throws IOException {
if(addr == null) {
out.write(0);
return;
}
out.write(1);
if(addr instanceof IpAddress) {
// regular case, we don't need to include class information about the type of Address, e.g. JmsAddress
out.write(1);
addr.writeTo(out);
}
else {
out.write(0);
writeOtherAddress(addr, out);
}
}
private static void writeOtherAddress(Address addr, DataOutputStream out) throws IOException {
ClassConfigurator conf=null;
try {conf=ClassConfigurator.getInstance(false);} catch(Exception e) {}
int magic_number=conf != null? conf.getMagicNumber(addr.getClass()) : -1;
// write the class info
if(magic_number == -1) {
out.write(0);
out.writeUTF(addr.getClass().getName());
}
else {
out.write(1);
out.writeInt(magic_number);
}
// write the data itself
addr.writeTo(out);
}
public static Address readAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
Address addr=null;
int b=in.read();
if(b == 0)
return null;
b=in.read();
if(b == 1) {
addr=new IpAddress();
addr.readFrom(in);
}
else {
addr=readOtherAddress(in);
}
return addr;
}
private static Address readOtherAddress(DataInputStream in) throws IOException, IllegalAccessException, InstantiationException {
ClassConfigurator conf=null;
try {conf=ClassConfigurator.getInstance(false);} catch(Exception e) {}
int b=in.read();
int magic_number;
String classname;
Class cl=null;
Address addr;
if(b == 1) {
magic_number=in.readInt();
cl=conf.get(magic_number);
}
else {
classname=in.readUTF();
cl=conf.get(classname);
}
addr=(Address)cl.newInstance();
addr.readFrom(in);
return addr;
}
public static void writeString(String s, DataOutputStream out) throws IOException {
if(s != null) {
out.write(1);
out.writeUTF(s);
}
else {
out.write(0);
}
}
public static String readString(DataInputStream in) throws IOException {
int b=in.read();
if(b == 1)
return in.readUTF();
return null;
}
/** Sleep for timeout msecs. Returns when timeout has elapsed or thread was interrupted */
public static void sleep(long timeout) {
try {
Thread.sleep(timeout);
}
catch(Exception e) {
}
}
/**
* On most UNIX systems, the minimum sleep time is 10-20ms. Even if we specify sleep(1), the thread will
* sleep for at least 10-20ms. On Windows, sleep() seems to be implemented as a busy sleep, that is the
* thread never relinquishes control and therefore the sleep(x) is exactly x ms long.
*/
public static void sleep(long msecs, boolean busy_sleep) {
if(!busy_sleep) {
sleep(msecs);
return;
}
long start=System.currentTimeMillis();
long stop=start + msecs;
while(stop > start) {
start=System.currentTimeMillis();
}
}
/** Returns a random value in the range [1 - range] */
public static long random(long range) {
return (long)((Math.random() * 100000) % range) + 1;
}
/** Sleeps between 1 and timeout milliseconds, chosen randomly. Timeout must be > 1 */
public static void sleepRandom(long timeout) {
if(timeout <= 0) {
log.error("timeout must be > 0 !");
return;
}
long r=(int)((Math.random() * 100000) % timeout) + 1;
sleep(r);
}
/**
Tosses a coin weighted with probability and returns true or false. Example: if probability=0.8,
chances are that in 80% of all cases, true will be returned and false in 20%.
*/
public static boolean tossWeightedCoin(double probability) {
long r=random(100);
long cutoff=(long)(probability * 100);
if(r < cutoff)
return true;
else
return false;
}
public static String getHostname() {
try {
return InetAddress.getLocalHost().getHostName();
}
catch(Exception ex) {
}
return "localhost";
}
public static void dumpStack(boolean exit) {
try {
throw new Exception("Dumping stack:");
}
catch(Exception e) {
e.printStackTrace();
if(exit)
System.exit(0);
}
}
/**
* Use with caution: lots of overhead
*/
public static String printStackTrace(Throwable t) {
StringWriter s=new StringWriter();
PrintWriter p=new PrintWriter(s);
t.printStackTrace(p);
return s.toString();
}
public static String getStackTrace(Throwable t) {
return printStackTrace(t);
}
/**
* Use with caution: lots of overhead
*/
public static String printStackTrace() {
try {
throw new Exception("Dumping stack:");
}
catch(Throwable t) {
StringWriter s=new StringWriter();
PrintWriter p=new PrintWriter(s);
t.printStackTrace(p);
return s.toString();
}
}
public static String print(Throwable t) {
return printStackTrace(t);
}
public static void crash() {
System.exit(-1);
}
public static String printEvent(Event evt) {
Message msg;
if(evt.getType() == Event.MSG) {
msg=(Message)evt.getArg();
if(msg != null) {
if(msg.getLength() > 0)
return printMessage(msg);
else
return msg.printObjectHeaders();
}
}
return evt.toString();
}
/** Tries to read an object from the message's buffer and prints it */
public static String printMessage(Message msg) {
if(msg == null)
return "";
if(msg.getLength() == 0)
return null;
try {
return msg.getObject().toString();
}
catch(Exception e) { // it is not an object
return "";
}
}
/** Tries to read a <code>MethodCall</code> object from the message's buffer and prints it.
Returns empty string if object is not a method call */
public static String printMethodCall(Message msg) {
Object obj;
if(msg == null)
return "";
if(msg.getLength() == 0)
return "";
try {
obj=msg.getObject();
return obj.toString();
}
catch(Exception e) { // it is not an object
return "";
}
}
public static void printThreads() {
Thread threads[]=new Thread[Thread.activeCount()];
Thread.enumerate(threads);
System.out.println("
for(int i=0; i < threads.length; i++) {
System.out.println("#" + i + ": " + threads[i]);
}
System.out.println("
}
public static String activeThreads() {
StringBuffer sb=new StringBuffer();
Thread threads[]=new Thread[Thread.activeCount()];
Thread.enumerate(threads);
sb.append("
for(int i=0; i < threads.length; i++) {
sb.append("#" + i + ": " + threads[i] + '\n');
}
sb.append("
return sb.toString();
}
/**
Fragments a byte buffer into smaller fragments of (max.) frag_size.
Example: a byte buffer of 1024 bytes and a frag_size of 248 gives 4 fragments
of 248 bytes each and 1 fragment of 32 bytes.
@return An array of byte buffers (<code>byte[]</code>).
*/
public static byte[][] fragmentBuffer(byte[] buf, int frag_size) {
byte[] retval[];
long total_size=buf.length;
int accumulated_size=0;
byte[] fragment;
int tmp_size=0;
int num_frags;
int index=0;
num_frags=buf.length % frag_size == 0 ? buf.length / frag_size : buf.length / frag_size + 1;
retval=new byte[num_frags][];
while(accumulated_size < total_size) {
if(accumulated_size + frag_size <= total_size)
tmp_size=frag_size;
else
tmp_size=(int)(total_size - accumulated_size);
fragment=new byte[tmp_size];
System.arraycopy(buf, accumulated_size, fragment, 0, tmp_size);
retval[index++]=fragment;
accumulated_size+=tmp_size;
}
return retval;
}
/**
* Given a buffer and a fragmentation size, compute a list of fragmentation offset/length pairs, and
* return them in a list. Example:<br/>
* Buffer is 10 bytes, frag_size is 4 bytes. Return value will be ({0,4}, {4,4}, {8,2}).
* This is a total of 3 fragments: the first fragment starts at 0, and has a length of 4 bytes, the second fragment
* starts at offset 4 and has a length of 4 bytes, and the last fragment starts at offset 8 and has a length
* of 2 bytes.
* @param frag_size
* @return List. A List<Range> of offset/length pairs
*/
public static java.util.List computeFragOffsets(int offset, int length, int frag_size) {
java.util.List retval=new ArrayList();
long total_size=length + offset;
int index=offset;
int tmp_size=0;
Range r;
while(index < total_size) {
if(index + frag_size <= total_size)
tmp_size=frag_size;
else
tmp_size=(int)(total_size - index);
r=new Range(index, tmp_size);
retval.add(r);
index+=tmp_size;
}
return retval;
}
public static java.util.List computeFragOffsets(byte[] buf, int frag_size) {
return computeFragOffsets(0, buf.length, frag_size);
}
/**
Concatenates smaller fragments into entire buffers.
@param fragments An array of byte buffers (<code>byte[]</code>)
@return A byte buffer
*/
public static byte[] defragmentBuffer(byte[] fragments[]) {
int total_length=0;
byte[] ret;
int index=0;
if(fragments == null) return null;
for(int i=0; i < fragments.length; i++) {
if(fragments[i] == null) continue;
total_length+=fragments[i].length;
}
ret=new byte[total_length];
for(int i=0; i < fragments.length; i++) {
if(fragments[i] == null) continue;
System.arraycopy(fragments[i], 0, ret, index, fragments[i].length);
index+=fragments[i].length;
}
return ret;
}
public static void printFragments(byte[] frags[]) {
for(int i=0; i < frags.length; i++)
System.out.println('\'' + new String(frags[i]) + '\'');
}
// /**
// Peeks for view on the channel until n views have been received or timeout has elapsed.
// Used to determine the view in which we want to start work. Usually, we start as only
// member in our own view (1st view) and the next view (2nd view) will be the full view
// of all members, or a timeout if we're the first member. If a non-view (a message or
// block) is received, the method returns immediately.
// @param channel The channel used to peek for views. Has to be operational.
// @param number_of_views The number of views to wait for. 2 is a good number to ensure that,
// if there are other members, we start working with them included in our view.
// @param timeout Number of milliseconds to wait until view is forced to return. A value
// of <= 0 means wait forever.
// */
// public static View peekViews(Channel channel, int number_of_views, long timeout) {
// View retval=null;
// Object obj=null;
// int num=0;
// long start_time=System.currentTimeMillis();
// if(timeout <= 0) {
// while(true) {
// try {
// obj=channel.peek(0);
// if(obj == null || !(obj instanceof View))
// break;
// else {
// retval=(View)channel.receive(0);
// num++;
// if(num >= number_of_views)
// break;
// catch(Exception ex) {
// break;
// else {
// while(timeout > 0) {
// try {
// obj=channel.peek(timeout);
// if(obj == null || !(obj instanceof View))
// break;
// else {
// retval=(View)channel.receive(timeout);
// num++;
// if(num >= number_of_views)
// break;
// catch(Exception ex) {
// break;
// timeout=timeout - (System.currentTimeMillis() - start_time);
// return retval;
public static String array2String(long[] array) {
StringBuffer ret=new StringBuffer("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i] + " ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(int[] array) {
StringBuffer ret=new StringBuffer("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i] + " ");
}
ret.append(']');
return ret.toString();
}
public static String array2String(boolean[] array) {
StringBuffer ret=new StringBuffer("[");
if(array != null) {
for(int i=0; i < array.length; i++)
ret.append(array[i] + " ");
}
ret.append(']');
return ret.toString();
}
/**
* Selects a random subset of members according to subset_percentage and returns them.
* Picks no member twice from the same membership. If the percentage is smaller than 1 -> picks 1 member.
*/
public static Vector pickSubset(Vector members, double subset_percentage) {
Vector ret=new Vector(), tmp_mbrs;
int num_mbrs=members.size(), subset_size, index;
if(num_mbrs == 0) return ret;
subset_size=(int)Math.ceil(num_mbrs * subset_percentage);
tmp_mbrs=(Vector)members.clone();
for(int i=subset_size; i > 0 && tmp_mbrs.size() > 0; i
index=(int)((Math.random() * num_mbrs) % tmp_mbrs.size());
ret.addElement(tmp_mbrs.elementAt(index));
tmp_mbrs.removeElementAt(index);
}
return ret;
}
/**
* Returns all members that left between 2 views. All members that are element of old_mbrs but not element of
* new_mbrs are returned.
*/
public static Vector determineLeftMembers(Vector old_mbrs, Vector new_mbrs) {
Vector retval=new Vector();
Object mbr;
if(old_mbrs == null || new_mbrs == null)
return retval;
for(int i=0; i < old_mbrs.size(); i++) {
mbr=old_mbrs.elementAt(i);
if(!new_mbrs.contains(mbr))
retval.addElement(mbr);
}
return retval;
}
public static String printMembers(Vector v) {
StringBuffer sb=new StringBuffer("(");
boolean first=true;
Object el;
if(v != null) {
for(int i=0; i < v.size(); i++) {
if(!first)
sb.append(", ");
else
first=false;
el=v.elementAt(i);
if(el instanceof Address)
sb.append(el);
else
sb.append(el);
}
}
sb.append(')');
return sb.toString();
}
/**
Makes sure that we detect when a peer connection is in the closed state (not closed while we send data,
but before we send data). 2 writes ensure that, if the peer closed the connection, the first write
will send the peer from FIN to RST state, and the second will cause a signal (IOException).
*/
public static void doubleWrite(byte[] buf, OutputStream out) throws Exception {
if(buf.length > 1) {
out.write(buf, 0, 1);
out.write(buf, 1, buf.length - 1);
}
else {
out.write(buf, 0, 0);
out.write(buf);
}
}
public static long sizeOf(String classname) {
Object inst;
byte[] data;
try {
// use thread context class loader
ClassLoader loader=Thread.currentThread().getContextClassLoader();
inst=loader.loadClass(classname).newInstance();
data=Util.objectToByteBuffer(inst);
return data.length;
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("exception=" + ex);
return 0;
}
}
public static long sizeOf(Object inst) {
byte[] data;
try {
data=Util.objectToByteBuffer(inst);
return data.length;
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("exception+" + ex);
return 0;
}
}
/** Checks whether 2 Addresses are on the same host */
public static boolean sameHost(Address one, Address two) {
InetAddress a, b;
String host_a, host_b;
if(one == null || two == null) return false;
if(!(one instanceof IpAddress) || !(two instanceof IpAddress)) {
if(log.isErrorEnabled()) log.error("addresses have to be of type IpAddress to be compared");
return false;
}
a=((IpAddress)one).getIpAddress();
b=((IpAddress)two).getIpAddress();
if(a == null || b == null) return false;
host_a=a.getHostAddress();
host_b=b.getHostAddress();
// System.out.println("host_a=" + host_a + ", host_b=" + host_b);
return host_a.equals(host_b);
}
public static void removeFile(String fname) {
if(fname == null) return;
try {
new File(fname).delete();
}
catch(Exception ex) {
if(log.isErrorEnabled()) log.error("exception=" + ex);
}
}
public static boolean fileExists(String fname) {
return (new File(fname)).exists();
}
/**
E.g. 2000,4000,8000
*/
public static long[] parseCommaDelimitedLongs(String s) {
StringTokenizer tok;
Vector v=new Vector();
Long l;
long[] retval=null;
if(s == null) return null;
tok=new StringTokenizer(s, ",");
while(tok.hasMoreTokens()) {
l=new Long(tok.nextToken());
v.addElement(l);
}
if(v.size() == 0) return null;
retval=new long[v.size()];
for(int i=0; i < v.size(); i++)
retval[i]=((Long)v.elementAt(i)).longValue();
return retval;
}
/** e.g. "bela,jeannette,michelle" --> List{"bela", "jeannette", "michelle"} */
public static java.util.List parseCommaDelimitedStrings(String l) {
java.util.List tmp=new ArrayList();
StringTokenizer tok=new StringTokenizer(l, ",");
String t;
while(tok.hasMoreTokens()) {
t=tok.nextToken();
tmp.add(t);
}
return tmp;
}
public static String shortName(String hostname) {
int index;
StringBuffer sb=new StringBuffer();
if(hostname == null) return null;
index=hostname.indexOf('.');
if(index > 0 && !Character.isDigit(hostname.charAt(0)))
sb.append(hostname.substring(0, index));
else
sb.append(hostname);
return sb.toString();
}
/** Finds first available port starting at start_port and returns server socket */
public static ServerSocket createServerSocket(int start_port) {
ServerSocket ret=null;
while(true) {
try {
ret=new ServerSocket(start_port);
}
catch(BindException bind_ex) {
start_port++;
continue;
}
catch(IOException io_ex) {
if(log.isErrorEnabled()) log.error("exception is " + io_ex);
}
break;
}
return ret;
}
public static ServerSocket createServerSocket(InetAddress bind_addr, int start_port) {
ServerSocket ret=null;
while(true) {
try {
ret=new ServerSocket(start_port, 50, bind_addr);
}
catch(BindException bind_ex) {
start_port++;
continue;
}
catch(IOException io_ex) {
if(log.isErrorEnabled()) log.error("exception is " + io_ex);
}
break;
}
return ret;
}
/**
* Creates a DatagramSocket bound to addr. If addr is null, socket won't be bound. If address is already in use,
* start_port will be incremented until a socket can be created.
* @param addr The InetAddress to which the socket should be bound. If null, the socket will not be bound.
* @param port The port which the socket should use. If 0, a random port will be used. If > 0, but port is already
* in use, it will be incremented until an unused port is found, or until MAX_PORT is reached.
*/
public static DatagramSocket createDatagramSocket(InetAddress addr, int port) throws Exception {
DatagramSocket sock=null;
if(addr == null) {
if(port == 0) {
return new DatagramSocket();
}
else {
while(port < MAX_PORT) {
try {
return new DatagramSocket(port);
}
catch(BindException bind_ex) { // port already used
port++;
continue;
}
catch(Exception ex) {
throw ex;
}
}
}
}
else {
if(port == 0) port=1024;
while(port < MAX_PORT) {
try {
return new DatagramSocket(port, addr);
}
catch(BindException bind_ex) { // port already used
port++;
continue;
}
catch(Exception ex) {
throw ex;
}
}
}
return sock; // will never be reached, but the stupid compiler didn't figure it out...
}
public static boolean checkForLinux() {
String os=System.getProperty("os.name");
return os != null && os.toLowerCase().startsWith("linux") ? true : false;
}
public static boolean checkForSolaris() {
String os=System.getProperty("os.name");
return os != null && os.toLowerCase().startsWith("sun") ? true : false;
}
public static boolean checkForWindows() {
String os=System.getProperty("os.name");
return os != null && os.toLowerCase().startsWith("win") ? true : false;
}
public static void prompt(String s) {
System.out.println(s);
System.out.flush();
try {
while(System.in.available() > 0)
System.in.read();
System.in.read();
}
catch(IOException e) {
e.printStackTrace();
}
}
public static String memStats(boolean gc) {
StringBuffer sb=new StringBuffer();
Runtime rt=Runtime.getRuntime();
if(gc)
rt.gc();
long free_mem, total_mem, used_mem;
free_mem=rt.freeMemory();
total_mem=rt.totalMemory();
used_mem=total_mem - free_mem;
sb.append("Free mem: ").append(free_mem).append("\nUsed mem: ").append(used_mem);
sb.append("\nTotal mem: ").append(total_mem);
return sb.toString();
}
/*
public static void main(String[] args) {
DatagramSocket sock;
InetAddress addr=null;
int port=0;
for(int i=0; i < args.length; i++) {
if(args[i].equals("-help")) {
System.out.println("Util [-help] [-addr] [-port]");
return;
}
if(args[i].equals("-addr")) {
try {
addr=InetAddress.getByName(args[++i]);
continue;
}
catch(Exception ex) {
System.err.println(ex);
return;
}
}
if(args[i].equals("-port")) {
port=Integer.parseInt(args[++i]);
continue;
}
System.out.println("Util [-help] [-addr] [-port]");
return;
}
try {
sock=createDatagramSocket(addr, port);
System.out.println("sock: local address is " + sock.getLocalAddress() + ":" + sock.getLocalPort() +
", remote address is " + sock.getInetAddress() + ":" + sock.getPort());
System.in.read();
}
catch(Exception ex) {
System.err.println(ex);
}
}
*/
public static void main(String args[]) {
System.out.println("Check for Linux: " + checkForLinux());
System.out.println("Check for Solaris: " + checkForSolaris());
System.out.println("Check for Windows: " + checkForWindows());
}
} |
package com.areen.jlib.api;
import java.io.File;
/**
* An interface for every kind of file (virtual).
*
* @author Dejan
*/
public interface RemoteFile {
String getPath();
void setPath(String argPath);
boolean exists();
boolean canWrite();
String getDescription();
void setDescription(String argDesc);
boolean upload(File argFile);
boolean delete();
void open();
boolean newVersion(File argFile);
String getExtension();
String getMimeType();
String[] getAllowedExtensions();
void setAllowedExtensions(String[] extensions);
void showProperties();
String getToolTip();
} // RemoteFile class |
package org.mapyrus;
import java.util.ArrayList;
import java.util.HashMap;
/**
* A parsed statement.
* Can be one of several types. A conditional statement,
* a block of statements making a procedure or just a plain command.
*/
public class Statement
{
/*
* Possible types of statements.
*/
public static final int CONDITIONAL = 2;
public static final int REPEAT_LOOP = 3;
public static final int WHILE_LOOP = 4;
public static final int FOR_LOOP = 5;
public static final int BLOCK = 6;
public static final int COLOR = 9;
public static final int BLEND = 10;
public static final int LINESTYLE = 11;
public static final int FONT = 12;
public static final int JUSTIFY = 13;
public static final int MOVE = 14;
public static final int DRAW = 15;
public static final int RDRAW = 16;
public static final int ARC = 17;
public static final int CIRCLE = 18;
public static final int ELLIPSE = 19;
public static final int CYLINDER = 20;
public static final int RAINDROP = 21;
public static final int BEZIER = 22;
public static final int SINEWAVE = 23;
public static final int WEDGE = 24;
public static final int SPIRAL = 25;
public static final int BOX = 26;
public static final int ROUNDEDBOX = 27;
public static final int BOX3D = 28;
public static final int CHESSBOARD = 29;
public static final int HEXAGON = 30;
public static final int PENTAGON = 31;
public static final int TRIANGLE = 32;
public static final int STAR = 33;
public static final int ADDPATH = 34;
public static final int CLEARPATH = 35;
public static final int CLOSEPATH = 36;
public static final int SAMPLEPATH = 37;
public static final int STRIPEPATH = 38;
public static final int SHIFTPATH = 39;
public static final int PARALLELPATH = 40;
public static final int SELECTPATH = 41;
public static final int SINKHOLE = 42;
public static final int GUILLOTINE = 43;
public static final int STROKE = 44;
public static final int FILL = 45;
public static final int GRADIENTFILL = 46;
public static final int EVENTSCRIPT = 47;
public static final int PROTECT = 48;
public static final int UNPROTECT = 49;
public static final int CLIP = 50;
public static final int LABEL = 51;
public static final int FLOWLABEL = 52;
public static final int TABLE = 53;
public static final int TREE = 54;
public static final int ICON = 55;
public static final int GEOIMAGE = 56;
public static final int EPS = 57;
public static final int SVG = 58;
public static final int SVGCODE = 59;
public static final int PDF = 60;
public static final int SCALE = 61;
public static final int ROTATE = 62;
public static final int WORLDS = 63;
public static final int PROJECT = 64;
public static final int DATASET = 65;
public static final int FETCH = 66;
public static final int NEWPAGE = 67;
public static final int ENDPAGE = 68;
public static final int SETOUTPUT = 69;
public static final int PRINT = 70;
public static final int LOCAL = 71;
public static final int LET = 72;
public static final int EVAL = 73;
public static final int KEY = 74;
public static final int LEGEND = 75;
public static final int MIMETYPE = 76;
public static final int HTTPRESPONSE = 77;
/*
* Statement type for call and return to/from user defined procedure block.
*/
public static final int CALL = 1000;
public static final int RETURN = 1001;
private int mType;
/*
* Statements in an if-then-else statement.
*/
private ArrayList mThenStatements;
private ArrayList mElseStatements;
/*
* Statements in a while loop statement.
*/
private ArrayList mLoopStatements;
/*
* Name of procedure block,
* variable names of parameters to this procedure
* and block of statements in a procedure in order of execution
*/
private String mBlockName;
private ArrayList mStatementBlock;
private ArrayList mParameters;
private Expression []mExpressions;
/*
* HashMap to walk through for a 'for' loop.
*/
private Expression mForHashMapExpression;
/*
* Filename and line number within file that this
* statement was read from.
*/
private String mFilename;
private int mLineNumber;
/*
* Static statement type lookup table for fast lookup.
*/
private static HashMap mStatementTypeLookup;
static
{
mStatementTypeLookup = new HashMap();
mStatementTypeLookup.put("color", new Integer(COLOR));
mStatementTypeLookup.put("colour", new Integer(COLOR));
mStatementTypeLookup.put("blend", new Integer(BLEND));
mStatementTypeLookup.put("linestyle", new Integer(LINESTYLE));
mStatementTypeLookup.put("font", new Integer(FONT));
mStatementTypeLookup.put("justify", new Integer(JUSTIFY));
mStatementTypeLookup.put("move", new Integer(MOVE));
mStatementTypeLookup.put("draw", new Integer(DRAW));
mStatementTypeLookup.put("rdraw", new Integer(RDRAW));
mStatementTypeLookup.put("arc", new Integer(ARC));
mStatementTypeLookup.put("circle", new Integer(CIRCLE));
mStatementTypeLookup.put("ellipse", new Integer(ELLIPSE));
mStatementTypeLookup.put("cylinder", new Integer(CYLINDER));
mStatementTypeLookup.put("raindrop", new Integer(RAINDROP));
mStatementTypeLookup.put("bezier", new Integer(BEZIER));
mStatementTypeLookup.put("sinewave", new Integer(SINEWAVE));
mStatementTypeLookup.put("wedge", new Integer(WEDGE));
mStatementTypeLookup.put("spiral", new Integer(SPIRAL));
mStatementTypeLookup.put("box", new Integer(BOX));
mStatementTypeLookup.put("roundedbox", new Integer(ROUNDEDBOX));
mStatementTypeLookup.put("box3d", new Integer(BOX3D));
mStatementTypeLookup.put("chessboard", new Integer(CHESSBOARD));
mStatementTypeLookup.put("hexagon", new Integer(HEXAGON));
mStatementTypeLookup.put("pentagon", new Integer(PENTAGON));
mStatementTypeLookup.put("triangle", new Integer(TRIANGLE));
mStatementTypeLookup.put("star", new Integer(STAR));
mStatementTypeLookup.put("addpath", new Integer(ADDPATH));
mStatementTypeLookup.put("clearpath", new Integer(CLEARPATH));
mStatementTypeLookup.put("closepath", new Integer(CLOSEPATH));
mStatementTypeLookup.put("samplepath", new Integer(SAMPLEPATH));
mStatementTypeLookup.put("stripepath", new Integer(STRIPEPATH));
mStatementTypeLookup.put("shiftpath", new Integer(SHIFTPATH));
mStatementTypeLookup.put("parallelpath", new Integer(PARALLELPATH));
mStatementTypeLookup.put("selectpath", new Integer(SELECTPATH));
mStatementTypeLookup.put("sinkhole", new Integer(SINKHOLE));
mStatementTypeLookup.put("guillotine", new Integer(GUILLOTINE));
mStatementTypeLookup.put("stroke", new Integer(STROKE));
mStatementTypeLookup.put("fill", new Integer(FILL));
mStatementTypeLookup.put("gradientfill", new Integer(GRADIENTFILL));
mStatementTypeLookup.put("eventscript", new Integer(EVENTSCRIPT));
mStatementTypeLookup.put("protect", new Integer(PROTECT));
mStatementTypeLookup.put("unprotect", new Integer(UNPROTECT));
mStatementTypeLookup.put("clip", new Integer(CLIP));
mStatementTypeLookup.put("label", new Integer(LABEL));
mStatementTypeLookup.put("flowlabel", new Integer(FLOWLABEL));
mStatementTypeLookup.put("table", new Integer(TABLE));
mStatementTypeLookup.put("tree", new Integer(TREE));
mStatementTypeLookup.put("icon", new Integer(ICON));
mStatementTypeLookup.put("geoimage", new Integer(GEOIMAGE));
mStatementTypeLookup.put("eps", new Integer(EPS));
mStatementTypeLookup.put("svg", new Integer(SVG));
mStatementTypeLookup.put("svgcode", new Integer(SVGCODE));
mStatementTypeLookup.put("pdf", new Integer(PDF));
mStatementTypeLookup.put("scale", new Integer(SCALE));
mStatementTypeLookup.put("rotate", new Integer(ROTATE));
mStatementTypeLookup.put("worlds", new Integer(WORLDS));
mStatementTypeLookup.put("project", new Integer(PROJECT));
mStatementTypeLookup.put("dataset", new Integer(DATASET));
mStatementTypeLookup.put("fetch", new Integer(FETCH));
mStatementTypeLookup.put("newpage", new Integer(NEWPAGE));
mStatementTypeLookup.put("endpage", new Integer(ENDPAGE));
mStatementTypeLookup.put("setoutput", new Integer(SETOUTPUT));
mStatementTypeLookup.put("print", new Integer(PRINT));
mStatementTypeLookup.put("local", new Integer(LOCAL));
mStatementTypeLookup.put("let", new Integer(LET));
mStatementTypeLookup.put("eval", new Integer(EVAL));
mStatementTypeLookup.put("key", new Integer(KEY));
mStatementTypeLookup.put("legend", new Integer(LEGEND));
mStatementTypeLookup.put("mimetype", new Integer(MIMETYPE));
mStatementTypeLookup.put("httpresponse", new Integer(HTTPRESPONSE));
mStatementTypeLookup.put("return", new Integer(RETURN));
}
/**
* Looks up identifier for a statement name.
* @param s is the name of the statement.
* @returns numeric code for this statement, or -1 if statement
* is unknown.
*/
private int getStatementType(String s)
{
int retval;
Integer type = (Integer)mStatementTypeLookup.get(s.toLowerCase());
if (type == null)
retval = CALL;
else
retval = type.intValue();
return(retval);
}
/**
* Creates a plain statement, either a built-in command or
* a call to a procedure block that the user has defined.
* @param keyword is the name statement.
* @param expressions are the arguments for this statement.
*/
public Statement(String keyword, Expression []expressions)
{
mType = getStatementType(keyword);
if (mType == CALL)
mBlockName = keyword;
mExpressions = expressions;
}
/**
* Creates a procedure, a block of statements to be executed together.
* @param blockName is name of procedure block.
* @param parameters variable names of parameters to this procedure.
* @param statements list of statements that make up this procedure block.
*/
public Statement(String blockName, ArrayList parameters, ArrayList statements)
{
mBlockName = blockName;
mParameters = parameters;
mStatementBlock = statements;
mType = BLOCK;
}
/**
* Create an if, then, else, endif block of statements.
* @param test is expression to test.
* @param thenStatements is statements to execute if expression is true.
* @param elseStatements is statements to execute if expression is false,
* or null if there is no statement to execute.
*/
public Statement(Expression test, ArrayList thenStatements,
ArrayList elseStatements)
{
mType = CONDITIONAL;
mExpressions = new Expression[1];
mExpressions[0] = test;
mThenStatements = thenStatements;
mElseStatements = elseStatements;
}
/**
* Create a repeat or while loop block of statements.
* @param test is expression to test before each iteration of loop.
* @param loopStatements is statements to execute for each loop iteration.
* @param isWhileLoop true for a while loop, false for a repeat loop.
*/
public Statement(Expression test, ArrayList loopStatements,
boolean isWhileLoop)
{
mType = isWhileLoop ? WHILE_LOOP : REPEAT_LOOP;
mExpressions = new Expression[1];
mExpressions[0] = test;
mLoopStatements = loopStatements;
}
/**
* Create a for loop block of statements.
* @param test is expression to test before each iteration of loop.
* @param loopStatements is statements to execute for each loop iteration.
*/
public Statement(Expression var, Expression arrayVar, ArrayList loopStatements)
{
mType = FOR_LOOP;
mExpressions = new Expression[1];
mExpressions[0] = var;
mForHashMapExpression = arrayVar;
mLoopStatements = loopStatements;
}
/**
* Sets the filename and line number that this statement was read from.
* This is for use in any error message for this statement.
* @param filename is name of file this statement was read from.
* @param lineNumber is line number within file containing this statement.
*/
public void setFilenameAndLineNumber(String filename, int lineNumber)
{
mFilename = filename;
mLineNumber = lineNumber;
}
/**
* Returns filename and line number that this statement was read from.
* @return string containing filename and line number.
*/
public String getFilenameAndLineNumber()
{
return(mFilename + ":" + mLineNumber);
}
/**
* Returns filename that this statement was read from.
* @return string containing filename.
*/
public String getFilename()
{
return(mFilename);
}
/**
* Returns the type of this statement.
* @return statement type.
*/
public int getType()
{
return(mType);
}
public Expression []getExpressions()
{
return(mExpressions);
}
/**
* Returns list of statements in "then" section of "if" statement.
* @return list of statements.
*/
public ArrayList getThenStatements()
{
return(mThenStatements);
}
/**
* Returns list of statements in "else" section of "if" statement.
* @return list of statements.
*/
public ArrayList getElseStatements()
{
return(mElseStatements);
}
/**
* Returns list of statements in while or for loop statement.
* @return list of statements.
*/
public ArrayList getLoopStatements()
{
return(mLoopStatements);
}
/**
* Returns hashmap expression to walk through in a for loop statement.
* @return expression evaluating to a hashmap.
*/
public Expression getForHashMap()
{
return(mForHashMapExpression);
}
/**
* Return name of procedure block.
* @return name of procedure.
*/
public String getBlockName()
{
return(mBlockName);
}
/**
* Return variable names of parameters to a procedure.
* @return list of parameter names.
*/
public ArrayList getBlockParameters()
{
return(mParameters);
}
/**
* Return statements in a procedure.
* @return ArrayList of statements that make up the procedure.
*/
public ArrayList getStatementBlock()
{
return(mStatementBlock);
}
} |
package org.mapyrus;
import java.util.ArrayList;
import java.util.HashMap;
/**
* A parsed statement.
* Can be one of several types. A conditional statement,
* a block of statements making a procedure or just a plain command.
*/
public class Statement
{
/*
* Possible types of statements.
*/
public static final int CONDITIONAL = 2;
public static final int REPEAT_LOOP = 3;
public static final int WHILE_LOOP = 4;
public static final int FOR_LOOP = 5;
public static final int BLOCK = 6;
public static final int COLOR = 9;
public static final int BLEND = 10;
public static final int LINESTYLE = 11;
public static final int FONT = 12;
public static final int JUSTIFY = 13;
public static final int MOVE = 14;
public static final int DRAW = 15;
public static final int RDRAW = 16;
public static final int ARC = 17;
public static final int CIRCLE = 18;
public static final int ELLIPSE = 19;
public static final int CYLINDER = 20;
public static final int RAINDROP = 21;
public static final int BEZIER = 22;
public static final int SINEWAVE = 23;
public static final int WEDGE = 24;
public static final int SPIRAL = 25;
public static final int BOX = 26;
public static final int ROUNDEDBOX = 27;
public static final int BOX3D = 28;
public static final int HEXAGON = 29;
public static final int PENTAGON = 30;
public static final int TRIANGLE = 31;
public static final int STAR = 32;
public static final int ADDPATH = 33;
public static final int CLEARPATH = 34;
public static final int CLOSEPATH = 35;
public static final int SAMPLEPATH = 36;
public static final int STRIPEPATH = 37;
public static final int SHIFTPATH = 38;
public static final int PARALLELPATH = 39;
public static final int SELECTPATH = 40;
public static final int SINKHOLE = 41;
public static final int GUILLOTINE = 42;
public static final int STROKE = 43;
public static final int FILL = 44;
public static final int GRADIENTFILL = 45;
public static final int EVENTSCRIPT = 46;
public static final int PROTECT = 47;
public static final int UNPROTECT = 48;
public static final int CLIP = 49;
public static final int LABEL = 50;
public static final int FLOWLABEL = 51;
public static final int TABLE = 52;
public static final int ICON = 53;
public static final int GEOIMAGE = 54;
public static final int EPS = 55;
public static final int SCALE = 56;
public static final int ROTATE = 57;
public static final int WORLDS = 58;
public static final int PROJECT = 59;
public static final int DATASET = 60;
public static final int FETCH = 61;
public static final int NEWPAGE = 62;
public static final int ENDPAGE = 63;
public static final int SETOUTPUT = 64;
public static final int PRINT = 65;
public static final int LOCAL = 66;
public static final int LET = 67;
public static final int EVAL = 68;
public static final int KEY = 69;
public static final int LEGEND = 70;
public static final int MIMETYPE = 71;
public static final int RESPONSE = 72;
/*
* Statement type for call and return to/from user defined procedure block.
*/
public static final int CALL = 1000;
public static final int RETURN = 1001;
private int mType;
/*
* Statements in an if-then-else statement.
*/
private ArrayList mThenStatements;
private ArrayList mElseStatements;
/*
* Statements in a while loop statement.
*/
private ArrayList mLoopStatements;
/*
* Name of procedure block,
* variable names of parameters to this procedure
* and block of statements in a procedure in order of execution
*/
private String mBlockName;
private ArrayList mStatementBlock;
private ArrayList mParameters;
private Expression []mExpressions;
/*
* HashMap to walk through for a 'for' loop.
*/
private Expression mForHashMapExpression;
/*
* Filename and line number within file that this
* statement was read from.
*/
private String mFilename;
private int mLineNumber;
/*
* Static statement type lookup table for fast lookup.
*/
private static HashMap mStatementTypeLookup;
static
{
mStatementTypeLookup = new HashMap();
mStatementTypeLookup.put("color", new Integer(COLOR));
mStatementTypeLookup.put("colour", new Integer(COLOR));
mStatementTypeLookup.put("blend", new Integer(BLEND));
mStatementTypeLookup.put("linestyle", new Integer(LINESTYLE));
mStatementTypeLookup.put("font", new Integer(FONT));
mStatementTypeLookup.put("justify", new Integer(JUSTIFY));
mStatementTypeLookup.put("move", new Integer(MOVE));
mStatementTypeLookup.put("draw", new Integer(DRAW));
mStatementTypeLookup.put("rdraw", new Integer(RDRAW));
mStatementTypeLookup.put("arc", new Integer(ARC));
mStatementTypeLookup.put("circle", new Integer(CIRCLE));
mStatementTypeLookup.put("ellipse", new Integer(ELLIPSE));
mStatementTypeLookup.put("cylinder", new Integer(CYLINDER));
mStatementTypeLookup.put("raindrop", new Integer(RAINDROP));
mStatementTypeLookup.put("bezier", new Integer(BEZIER));
mStatementTypeLookup.put("sinewave", new Integer(SINEWAVE));
mStatementTypeLookup.put("wedge", new Integer(WEDGE));
mStatementTypeLookup.put("spiral", new Integer(SPIRAL));
mStatementTypeLookup.put("box", new Integer(BOX));
mStatementTypeLookup.put("roundedbox", new Integer(ROUNDEDBOX));
mStatementTypeLookup.put("box3d", new Integer(BOX3D));
mStatementTypeLookup.put("hexagon", new Integer(HEXAGON));
mStatementTypeLookup.put("pentagon", new Integer(PENTAGON));
mStatementTypeLookup.put("triangle", new Integer(TRIANGLE));
mStatementTypeLookup.put("star", new Integer(STAR));
mStatementTypeLookup.put("addpath", new Integer(ADDPATH));
mStatementTypeLookup.put("clearpath", new Integer(CLEARPATH));
mStatementTypeLookup.put("closepath", new Integer(CLOSEPATH));
mStatementTypeLookup.put("samplepath", new Integer(SAMPLEPATH));
mStatementTypeLookup.put("stripepath", new Integer(STRIPEPATH));
mStatementTypeLookup.put("shiftpath", new Integer(SHIFTPATH));
mStatementTypeLookup.put("parallelpath", new Integer(PARALLELPATH));
mStatementTypeLookup.put("selectpath", new Integer(SELECTPATH));
mStatementTypeLookup.put("sinkhole", new Integer(SINKHOLE));
mStatementTypeLookup.put("guillotine", new Integer(GUILLOTINE));
mStatementTypeLookup.put("stroke", new Integer(STROKE));
mStatementTypeLookup.put("fill", new Integer(FILL));
mStatementTypeLookup.put("gradientfill", new Integer(GRADIENTFILL));
mStatementTypeLookup.put("eventscript", new Integer(EVENTSCRIPT));
mStatementTypeLookup.put("protect", new Integer(PROTECT));
mStatementTypeLookup.put("unprotect", new Integer(UNPROTECT));
mStatementTypeLookup.put("clip", new Integer(CLIP));
mStatementTypeLookup.put("label", new Integer(LABEL));
mStatementTypeLookup.put("flowlabel", new Integer(FLOWLABEL));
mStatementTypeLookup.put("table", new Integer(TABLE));
mStatementTypeLookup.put("icon", new Integer(ICON));
mStatementTypeLookup.put("geoimage", new Integer(GEOIMAGE));
mStatementTypeLookup.put("eps", new Integer(EPS));
mStatementTypeLookup.put("scale", new Integer(SCALE));
mStatementTypeLookup.put("rotate", new Integer(ROTATE));
mStatementTypeLookup.put("worlds", new Integer(WORLDS));
mStatementTypeLookup.put("project", new Integer(PROJECT));
mStatementTypeLookup.put("dataset", new Integer(DATASET));
mStatementTypeLookup.put("fetch", new Integer(FETCH));
mStatementTypeLookup.put("newpage", new Integer(NEWPAGE));
mStatementTypeLookup.put("endpage", new Integer(ENDPAGE));
mStatementTypeLookup.put("setoutput", new Integer(SETOUTPUT));
mStatementTypeLookup.put("print", new Integer(PRINT));
mStatementTypeLookup.put("local", new Integer(LOCAL));
mStatementTypeLookup.put("let", new Integer(LET));
mStatementTypeLookup.put("eval", new Integer(EVAL));
mStatementTypeLookup.put("key", new Integer(KEY));
mStatementTypeLookup.put("legend", new Integer(LEGEND));
mStatementTypeLookup.put("mimetype", new Integer(MIMETYPE));
mStatementTypeLookup.put("response", new Integer(RESPONSE));
}
/**
* Constant for 'return' statement.
*/
public static final Statement RETURN_STATEMENT;
static
{
RETURN_STATEMENT = new Statement("", null);
RETURN_STATEMENT.mType = RETURN;
}
/**
* Looks up identifier for a statement name.
* @param s is the name of the statement.
* @returns numeric code for this statement, or -1 if statement
* is unknown.
*/
private int getStatementType(String s)
{
int retval;
Integer type = (Integer)mStatementTypeLookup.get(s.toLowerCase());
if (type == null)
retval = CALL;
else
retval = type.intValue();
return(retval);
}
/**
* Creates a plain statement, either a built-in command or
* a call to a procedure block that the user has defined.
* @param keyword is the name statement.
* @param expressions are the arguments for this statement.
*/
public Statement(String keyword, Expression []expressions)
{
mType = getStatementType(keyword);
if (mType == CALL)
mBlockName = keyword;
mExpressions = expressions;
}
/**
* Creates a procedure, a block of statements to be executed together.
* @param blockName is name of procedure block.
* @param parameters variable names of parameters to this procedure.
* @param statements list of statements that make up this procedure block.
*/
public Statement(String blockName, ArrayList parameters, ArrayList statements)
{
mBlockName = blockName;
mParameters = parameters;
mStatementBlock = statements;
mType = BLOCK;
}
/**
* Create an if, then, else, endif block of statements.
* @param test is expression to test.
* @param thenStatements is statements to execute if expression is true.
* @param elseStatements is statements to execute if expression is false,
* or null if there is no statement to execute.
*/
public Statement(Expression test, ArrayList thenStatements,
ArrayList elseStatements)
{
mType = CONDITIONAL;
mExpressions = new Expression[1];
mExpressions[0] = test;
mThenStatements = thenStatements;
mElseStatements = elseStatements;
}
/**
* Create a repeat or while loop block of statements.
* @param test is expression to test before each iteration of loop.
* @param loopStatements is statements to execute for each loop iteration.
* @param isWhileLoop true for a while loop, false for a repeat loop.
*/
public Statement(Expression test, ArrayList loopStatements,
boolean isWhileLoop)
{
mType = isWhileLoop ? WHILE_LOOP : REPEAT_LOOP;
mExpressions = new Expression[1];
mExpressions[0] = test;
mLoopStatements = loopStatements;
}
/**
* Create a for loop block of statements.
* @param test is expression to test before each iteration of loop.
* @param loopStatements is statements to execute for each loop iteration.
*/
public Statement(Expression var, Expression arrayVar, ArrayList loopStatements)
{
mType = FOR_LOOP;
mExpressions = new Expression[1];
mExpressions[0] = var;
mForHashMapExpression = arrayVar;
mLoopStatements = loopStatements;
}
/**
* Sets the filename and line number that this statement was read from.
* This is for use in any error message for this statement.
* @param filename is name of file this statement was read from.
* @param lineNumber is line number within file containing this statement.
*/
public void setFilenameAndLineNumber(String filename, int lineNumber)
{
mFilename = filename;
mLineNumber = lineNumber;
}
/**
* Returns filename and line number that this statement was read from.
* @return string containing filename and line number.
*/
public String getFilenameAndLineNumber()
{
return(mFilename + ":" + mLineNumber);
}
/**
* Returns filename that this statement was read from.
* @return string containing filename.
*/
public String getFilename()
{
return(mFilename);
}
/**
* Returns the type of this statement.
* @return statement type.
*/
public int getType()
{
return(mType);
}
public Expression []getExpressions()
{
return(mExpressions);
}
/**
* Returns list of statements in "then" section of "if" statement.
* @return list of statements.
*/
public ArrayList getThenStatements()
{
return(mThenStatements);
}
/**
* Returns list of statements in "else" section of "if" statement.
* @return list of statements.
*/
public ArrayList getElseStatements()
{
return(mElseStatements);
}
/**
* Returns list of statements in while or for loop statement.
* @return list of statements.
*/
public ArrayList getLoopStatements()
{
return(mLoopStatements);
}
/**
* Returns hashmap expression to walk through in a for loop statement.
* @return expression evaluating to a hashmap.
*/
public Expression getForHashMap()
{
return(mForHashMapExpression);
}
/**
* Return name of procedure block.
* @return name of procedure.
*/
public String getBlockName()
{
return(mBlockName);
}
/**
* Return variable names of parameters to a procedure.
* @return list of parameter names.
*/
public ArrayList getBlockParameters()
{
return(mParameters);
}
/**
* Return statements in a procedure.
* @return ArrayList of statements that make up the procedure.
*/
public ArrayList getStatementBlock()
{
return(mStatementBlock);
}
} |
package com.clinichelper.Entity;
import com.clinichelper.Tools.Enums.Repeat;
import com.clinichelper.Tools.Enums.Task;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.UUID;
@Entity
public class Chore implements Serializable{
// Attributes
@Id
private String choreId;
@NotNull
private String title;
@NotNull
private Task type;
@NotNull
@Column(length = 500)
private String description;
@ManyToOne
private User user;
private boolean completed;
private Timestamp nextReminder;
private ArrayList<Repeat> reminders;
// Constructors
public Chore(){
}
public Chore(User user, String title, Task type, String description, ArrayList<Repeat> reminders){
this.setChoreId(user.getClinic().getClinicPrefix() + "-TASK-" + UUID.randomUUID().toString().split("-")[0].toUpperCase());
this.setTitle(title);
this.setType(type);
this.setDescription(description);
this.setCompleted(false);
this.setUser(user);
this.setReminders(reminders);
this.setNextReminder();
}
// Getters and Setters
public String getChoreId() {
return choreId;
}
public void setChoreId(String choreId) {
this.choreId = choreId;
}
public Task getType() {
return type;
}
public String getTypeString() {
switch (type){
case PATIENT_BIRTHDAY:
return "Patient's Birthday";
case STAFF_BIRTHDAY:
return "Staff's Birthday";
case REGISTRATIONDATE:
return "Registration Birthday";
case MEETING:
return "Meeting";
case SURGERY:
return "Surgery";
default:
return "Reminder";
}
}
@Transient
public String getColorHtml() {
switch (type){
case PATIENT_BIRTHDAY:
return "AntiqueWhite";
case STAFF_BIRTHDAY:
return "Khaki";
case REGISTRATIONDATE:
return "DarkSeaGreen";
case MEETING:
return "LightCoral";
case SURGERY:
return "Aqua ";
default:
return "LightSkyBlue";
}
}
public void setType(Task type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
public Timestamp getNextReminder() {
return nextReminder;
}
public void setNextReminder() {
this.nextReminder = setFirstNextReminder(this.reminders.get(0));
}
public ArrayList<Repeat> getReminders() {
return reminders;
}
public void setReminders(ArrayList<Repeat> reminders) {
this.reminders = reminders;
}
// Auxiliary Functions
private Timestamp setFirstNextReminder(Repeat repeat){
Calendar today = Calendar.getInstance();
today.setTime(Calendar.getInstance().getTime());
switch (repeat){
case EVERY_DAY:
today.add(Calendar.DATE, 1); // Tomorrow
break;
case MONTHLY:
today.add(Calendar.MONTH, 1); // Next Month
break;
case MONDAY:
do{
today.add(Calendar.DATE, 1);
} while (today.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY);
break;
case TUESDAY:
do{
today.add(Calendar.DATE, 1);
} while (today.get(Calendar.DAY_OF_WEEK) != Calendar.TUESDAY);
break;
case WEDNESDAY:
do{
today.add(Calendar.DATE, 1);
} while (today.get(Calendar.DAY_OF_WEEK) != Calendar.WEDNESDAY);
break;
case THURSDAY:
do{
today.add(Calendar.DATE, 1);
} while (today.get(Calendar.DAY_OF_WEEK) != Calendar.THURSDAY);
break;
case FRIDAY:
do{
today.add(Calendar.DATE, 1);
} while (today.get(Calendar.DAY_OF_WEEK) != Calendar.FRIDAY);
break;
case SATURDAY:
do{
today.add(Calendar.DATE, 1);
} while (today.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY);
break;
case YEARLY: // every year
today.add(Calendar.YEAR, 1); // Next Year
break;
default:
return new Timestamp(Calendar.getInstance().getTime().getTime());
}
return new Timestamp(today.getTime().getTime());
}
} |
// $Id: MarcReader.java,v 1.14 2003/01/16 21:29:17 ceyates Exp $
package org.marc4j;
import java.io.Reader;
import java.io.InputStreamReader;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.IOException;
import org.marc4j.marc.MarcConstants;
import org.marc4j.marc.Tag;
import org.marc4j.marc.Leader;
import org.marc4j.marc.MarcException;
/**
* <p>Parses MARC records and reports events to the <code>MarcHandler</code>
* and optionally the <code>ErrorHandler</code>. </p>
*
* @author <a href="mailto:mail@bpeters.com">Bas Peters</a>
* @version $Revision: 1.14 $
*
* @see MarcHandler
* @see ErrorHandler
*/
public class MarcReader {
/** The record terminator */
private static final int RT = MarcConstants.RT;
/** The field terminator */
private static final int FT = MarcConstants.FT;
/** The data element identifier */
private static final int US = MarcConstants.US;
/** The blank character */
private static final int BLANK = MarcConstants.BLANK;
int fileCounter = 0;
int recordCounter = 0;
String controlNumber = null;
String tag = null;
String fileName = null;
/** The MarcHandler object. */
private MarcHandler mh;
/** The ErrorHandler object. */
private ErrorHandler eh;
/**
* <p>Registers the <code>MarcHandler</code> implementation.</p>
*
* @param marcHandler the {@link MarcHandler} implementation
*/
public void setMarcHandler(MarcHandler mh) {
this.mh = mh;
}
/**
* <p>Registers the <code>ErrorHandler</code> implementation.</p>
*
* @param errorHandler the {@link ErrorHandler} implementation
*/
public void setErrorHandler(ErrorHandler eh) {
this.eh = eh;
}
/**
* <p>Sends a file to the MARC parser.</p>
*
* @param fileName the filename
*/
public void parse(String fileName)
throws IOException {
setFileName(fileName);
parse(new BufferedReader(new FileReader(fileName)));
}
/**
* <p>Sends an input stream to the MARC parser.</p>
*
* @param input the input stream
*/
public void parse(InputStream input)
throws IOException {
parse(new BufferedReader(new InputStreamReader(input)));
}
/**
* <p>Sends an input stream reader to the MARC parser.</p>
*
* @param input the input stream reader
*/
public void parse(InputStreamReader input)
throws IOException {
parse(new BufferedReader(input));
}
public void parse(Reader input)
throws IOException {
int ldrLength = 24;
if (mh != null)
mh.startCollection();
while(true) {
Leader leader = null;
char[] ldr = new char[24];
int charsRead = input.read(ldr);
if (charsRead == -1)
break;
while (charsRead != -1 && charsRead != ldr.length)
charsRead += input.read(ldr, charsRead, ldr.length - charsRead);
try {
leader = new Leader(new String(ldr));
} catch (MarcException e) {
if (eh != null)
reportFatalError("Unable to parse leader");
return;
}
int baseAddress = leader.getBaseAddressOfData();
recordCounter += 24;
if (mh != null)
mh.startRecord(leader);
int dirLength = leader.getBaseAddressOfData() - (24 + 1);
int dirEntries = dirLength / 12;
String[] tag = new String[dirEntries];
int[] length = new int[dirEntries];
if ((dirLength % 12) != 0 && eh != null)
reportError("Invalid directory length");
for (int i = 0; i < dirEntries; i++) {
char[] d = new char[3];
charsRead = input.read(d);
while (charsRead != -1 && charsRead != d.length)
charsRead += input.read(d, charsRead, d.length - charsRead);
char[] e = new char[4];
charsRead = input.read(e);
while (charsRead != -1 && charsRead != e.length)
charsRead += input.read(e, charsRead, e.length - charsRead);
char[] f = new char[5];
charsRead = input.read(f);
while (charsRead != -1 && charsRead != f.length)
charsRead += input.read(f, charsRead, f.length - charsRead);
recordCounter += 12;
tag[i] = new String(d);
try {
length[i] = Integer.parseInt(new String(e));
} catch (NumberFormatException nfe) {
if (eh != null)
reportError("Invalid directory entry");
}
}
if (input.read() != FT && eh != null)
reportError("Directory not terminated");
recordCounter++;
for (int i = 0; i < dirEntries; i++) {
char field[] = new char[length[i]];
charsRead = input.read(field);
while (charsRead != -1 && charsRead != field.length)
charsRead += input.read(field, charsRead, field.length - charsRead);
if (field[field.length -1] != FT && eh != null)
reportError("Field not terminated");
recordCounter += length[i];
if (Tag.isControlField(tag[i])) {
parseControlField(tag[i], field);
} else {
parseDataField(tag[i], field);
}
}
if (input.read() != RT && eh != null)
reportError("Record not terminated");
recordCounter++;
if (recordCounter != leader.getRecordLength() && eh != null)
reportError("Record length not equal to characters read");
fileCounter += recordCounter;
recordCounter = 0;
if (mh != null)
mh.endRecord();
}
input.close();
if (mh != null)
mh.endCollection();
}
private void parseControlField(String tag, char[] field) {
if (field.length < 2 && eh != null)
reportWarning("Control Field contains no data elements for tag " + tag);
if (Tag.isControlNumberField(tag))
setControlNumber(trimFT(field));
if (mh != null)
mh.controlField(tag, trimFT(field));
}
private void parseDataField(String tag, char[] field)
throws IOException {
// indicators defaulting to a blank value
char ind1 = BLANK;
char ind2 = BLANK;
char code = BLANK;
StringBuffer data = null;
if (field.length < 4 && eh != null) {
reportWarning("Data field contains no data elements for tag " + tag);
} else {
ind1 = field[0];
ind2 = field[1];
}
if (mh != null)
mh.startDataField(tag, ind1, ind2);
if (field[2] != US && field.length > 3 && eh != null)
reportWarning("Expected a data element identifier");
for (int i = 2; i < field.length; i++) {
char c = field[i];
switch(c) {
case US :
if (data != null)
reportSubfield(code, data);
code = field[i+1];
i++;
data = new StringBuffer();
break;
case FT :
if (data != null)
reportSubfield(code, data);
break;
default :
if (data != null)
data.append(c);
}
}
if (mh != null)
mh.endDataField(tag);
}
private void reportSubfield(char code, StringBuffer data) {
if (mh != null)
mh.subfield(code, new String(data).toCharArray());
}
private void reportWarning(String message) {
if (eh != null)
eh.warning(new MarcReaderException(message, getFileName(),
getPosition(),
getControlNumber()));
}
private void reportError(String message) {
if (eh != null)
eh.error(new MarcReaderException(message, getFileName(),
getPosition(),
getControlNumber()));
}
private void reportFatalError(String message) {
if (eh != null)
eh.fatalError(new MarcReaderException(message, getFileName(),
getPosition(),
getControlNumber()));
}
private void setControlNumber(String controlNumber) {
this.controlNumber = controlNumber;
}
private void setControlNumber(char[] controlNumber) {
this.controlNumber = new String(controlNumber);
}
private void setFileName(String fileName) {
this.fileName = fileName;
}
private String getControlNumber() {
return controlNumber;
}
private int getPosition() {
return fileCounter + recordCounter;
}
private String getFileName() {
return fileName;
}
private char[] trimFT(char[] field) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < field.length; i++) {
char c = field[i];
switch(c) {
case FT :
break;
default :
sb.append(c);
}
}
return sb.toString().toCharArray();
}
} |
package com.doctor.esper.event;
import java.util.Objects;
import java.util.UUID;
import com.alibaba.fastjson.JSON;
/**
* @author doctor
*
* @time 201563 4:37:08
*/
public class Person {
private UUID id;
private String name;
private String firstName;
private String sex;
private int age;
public Person(String name, String firstName, String sex, int age) {
this.name = name;
this.firstName = firstName;
this.sex = sex;
this.age = age;
}
public Person(UUID id, String name, String firstName, String sex, int age) {
this.id = id;
this.name = name;
this.firstName = firstName;
this.sex = sex;
this.age = age;
}
public void setId(UUID id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setAge(int age) {
this.age = age;
}
public UUID getId() {
return id;
}
public String getName() {
return name;
}
public String getFirstName() {
return firstName;
}
public String getSex() {
return sex;
}
public int getAge() {
return age;
}
@Override
public int hashCode() {
return Objects.hash(getId(), getName(), getFirstName(), getSex(), getAge());
}
@Override
public boolean equals(Object obj) {
return this.hashCode() == obj.hashCode();
}
@Override
public String toString() {
return JSON.toJSONString(this);
}
} |
package org.nutz.http;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.nutz.json.Json;
public class Request {
public static enum METHOD {
GET, POST, OPTIONS, PUT, DELETE, TRACE, CONNECT, MULTIPART
}
private static HashMap<String, Object> EMPTY = new HashMap<String, Object>();
public static Request get(String url) {
return create(url, METHOD.GET, new HashMap<String, Object>());
}
public static Request get(String url, Header header) {
return Request.create(url, METHOD.GET, EMPTY, header);
}
public static Request create(String url, METHOD method) {
return create(url, method, EMPTY);
}
@SuppressWarnings("unchecked")
public static Request create(String url, METHOD method, String paramsAsJson, Header header) {
return create(url, method, (Map<String, Object>) Json.fromJson(paramsAsJson), header);
}
@SuppressWarnings("unchecked")
public static Request create(String url, METHOD method, String paramsAsJson) {
return create(url, method, (Map<String, Object>) Json.fromJson(paramsAsJson));
}
public static Request create(String url, METHOD method, Map<String, Object> params) {
return Request.create(url, method, params, Header.create());
}
public static Request create(String url, METHOD method, Map<String, Object> params, Header header) {
return new Request().setMethod(method).setParams(params).setUrl(url).setHeader(header);
}
private Request() {}
private String url;
private METHOD method;
private Header header;
private Map<String, Object> params;
public URL getUrl() {
StringBuilder sb = new StringBuilder(url);
try {
if (this.isGet() && null != params && params.size() > 0) {
sb.append(url.indexOf('?') > 0 ? '&' : '?');
sb.append(getURLEncodedParams());
}
return new URL(sb.toString());
}
catch (Exception e) {
throw new HttpException(sb.toString(), e);
}
}
public Map<String, Object> getParams() {
return params;
}
public String getURLEncodedParams() {
StringBuilder sb = new StringBuilder();
for (Iterator<String> it = params.keySet().iterator(); it.hasNext();) {
String key = it.next();
sb.append(Http.encode(key)).append('=').append(Http.encode(params.get(key)));
if (it.hasNext())
sb.append('&');
}
return sb.toString();
}
private Request setParams(Map<String, Object> params) {
this.params = params;
return this;
}
public Request setUrl(String url) {
this.url = url;
return this;
}
public METHOD getMethod() {
return method;
}
public boolean isMultipart() {
return METHOD.MULTIPART == method;
}
public boolean isGet() {
return METHOD.GET == method;
}
public boolean isPost() {
return METHOD.POST == method;
}
public Request setMethod(METHOD method) {
this.method = method;
return this;
}
public Header getHeader() {
return header;
}
public Request setHeader(Header header) {
this.header = header;
return this;
}
public Request setCookie(Cookie cookie) {
header.set("Cookie", cookie.toString());
return this;
}
public Cookie getCookie() {
String s = header.get("Cookie");
if (null == s)
return new Cookie();
return new Cookie(s);
}
} |
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class _18 {
public static class Solution1 {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> result = new ArrayList();
if (nums == null || nums.length == 0) {
return result;
}
Arrays.sort(nums);
for (int i = 0; i < nums.length - 3; i++) {
if (i > 0 && nums[i - 1] == nums[i]) {
continue;
}
for (int j = i + 1; j < nums.length - 2; j++) {
if (j > i + 1 && nums[j - 1] == nums[j]) {
continue;
}
int left = j + 1;
int right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
while (left + 1 < right && nums[left] == nums[left + 1]) {
left++;
}
while (right - 1 > left && nums[right] == nums[right - 1]) {
right
}
left++;
right
} else if (sum > target) {
right
} else {
left++;
}
}
}
}
return result;
}
}
} |
/**
* The TrieST class holds an symbol table of key-value pairs, with string keys
* and generic values. Implements all of the basic tree operations, including
* size, isEmpty, retrieve, contains, insert, and delete.
*
* For safty reasons, this implementation uses the convention that values cannot
* be null. Furthermore, when associating a value with an already existing key,
* the old value will be replaced with the new (given) value.
*
* This implementation uses a 256-way trie.
*/
public class TrieST<Value> {
/**
* Extendeed ASCII
*/
private static short R = 256;
/**
* The root of the trie
*/
private Node root;
/**
* The size of this symbol table (the number of key-value pairs it contains).
*/
private int size;
/**
* Distance means the number of letters separating the first and the current
* letters of a word (key) in this symbol table.
*/
private static int DISTANCE_FROM_FIRST_CHAR = 0;
/**
* R-way trie node.
*
* The value in Node has to be an Object because Java does not support arrays
* of generics. Thus, the method get() casts values back to Value.
*/
private static class Node {
private Object value;
private Node[] next = new Node[R];
}
/**
* Initializes an empty string symbol table.
*
* By Java's default, int size will be initialized to 0.
*/
public TrieST() { }
/**
* Returns the number of key-value pairs in this symbol table.
*
* @return the number of key-value pairs in this symbol table
*/
public int size() {
return size;
}
/**
* Increases by one the size of this symbol table.
*/
private void _increaseSize() {
size++;
}
/**
* Decreases by one the size of this symbol table.
*/
private void _decreaseSize() {
size
}
/**
* Returns true if this symbol table contains no key-value pairs.
*
* @return true if this symbol table contains no key-value pairs
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Returns the value associated with the given key.
*
* @param key the key
* @return the value associated with the given key if it is in this symbol
table; null otherwise
* @throws NullPointerException if key is null
*/
@SuppressWarnings("unchecked")
public Value get(String key) {
Node x = _get(root, key, DISTANCE_FROM_FIRST_CHAR);
if (x == null) {
return null;
}
return (Value) x.value;
}
/*
* Each node has a link corresponding to each possible char. Thus, for each
* char, starting at the root, we follow the link associated with the dth
* (distance) char in the key, until the last char of the key or a null link
* is reached.
*/
private Node _get(Node x, String key, int distance) {
// Search miss
if (x == null) {
return null;
}
// Search hit
if (distance == key.length()) {
return x;
}
char c = key.charAt(distance);
return _get(x.next[c], key, distance + 1);
}
/**
* Returns true if this symbol table contains the specified key.
*
* @param key element whose presence in this symbol table is to be tested
* @return true if this symbol table contains the specified key
*/
public boolean contains(String key) {
return get(key) != null;
}
public void put(String key, Value value) {
if (value == null) {
throw new IllegalArgumentException("Value cannot be null");
}
root = _put(root, key, value, DISTANCE_FROM_FIRST_CHAR);
}
/*
* In a trie an insertion is performed using the chars of the key as an
* pathfinder down the trie until the last char of the key or a null link is
* reached. At this point, one of the following scenarios applies:
* - A null link is found before reaching the last char of the key. This
* requires us to create nodes for each of the chars in the key not yet
* encountered and set the value of the last one with the given value;
* - The last char was encountered before reaching a null link and we set
* that node's value with the given value.
*/
private Node _put(Node x, String key, Value value, int distance) {
if (x == null) {
x = new Node();
}
if (distance == key.length()) {
if (x.value == null) {
_increaseSize();
}
x.value = value;
return x;
}
char c = key.charAt(distance);
x.next[c] = _put(x.next[c], key, value, distance + 1);
return x;
}
/**
* Deletes the specified key (and its associated value) from this symbol
* table if the key is present.
*
* @param key the key to remove
*/
public void delete(String key) {
// TODO: handle null key? maybe throw NullPointerException ???
root = _delete(root, key, DISTANCE_FROM_FIRST_CHAR);
}
/*
* The first step is to find the node that corresponds to the given key and
* then set its associated value to null.
* If node has null value and all null links, remove that node (and recur).
*
* Returns null if the value and all of the links in a node are null.
* Otherwise, returns the node x itself.
*/
private Node _delete(Node x, String key, int distance) {
if (x == null) {
return null;
}
if (distance == key.length()) {
if (x.value != null) {
_decreaseSize();
}
x.value = null;
} else {
char c = key.charAt(distance);
x.next[c] = _delete(x.next[c], key, distance + 1);
}
// Remove the subtree rooted at x if it is completely empty
if (x.value != null) {
return x;
}
for (short c = 0; c < R; c++) {
if (x.next[c] != null) {
return x;
}
}
return null;
}
} |
package com.fishercoder.solutions;
import com.fishercoder.common.classes.ListNode;
/**
* 24. Swap Nodes in Pairs
*
* Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
*/
public class _24 {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode second = head.next;
ListNode third = second.next;
second.next = head;
head.next = swapPairs(third);
return second;
}
} |
package com.fishercoder.solutions;
/**
* 45. Jump Game II
*
* Given an array of non-negative integers, you are initially positioned at the first index of the array.
* Each element in the array represents your maximum jump length at that position.
* Your goal is to reach the last index in the minimum number of jumps.
For example:
Given array A = [2,3,1,1,4]
The minimum number of jumps to reach the last index is 2. (Jump 1 step from index 0 to 1, then 3 steps to the last index.)
Note:
You can assume that you can always reach the last index.
*/
public class _45 {
public static class Solution1 {
public int jump(int[] nums) {
int stepCount = 0;
int lastJumpMax = 0;
int currentJumpMax = 0;
for (int i = 0; i < nums.length - 1; i++) {
currentJumpMax = Math.max(currentJumpMax, i + nums[i]);
if (i == lastJumpMax) {
stepCount++;
lastJumpMax = currentJumpMax;
}
}
return stepCount;
}
}
} |
package com.fishercoder.solutions;
import com.fishercoder.common.classes.ListNode;
public class _92 {
public static class Solution1 {
public ListNode reverseBetween(ListNode head, int m, int n) {
// use four nodes, pre, start, then, dummy
// just reverse the nodes along the way
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode pre = dummy;
for (int i = 0; i < m - 1; i++) {
pre = pre.next;
}
ListNode start = pre.next;// start is the node prior to reversing, in the given example,
// start is node with value 1
ListNode then = start.next;// then is the node that we'll start to reverse, in the given
// example, it's 2
for (int i = 0; i < n - m; i++) {
// pay special attention to this for loop, it's assigning then.next to start.next, it
// didn't initialize a new node
// this does exactly what I desired to do, but I just didn't figure out how to implement
// it, thumbs up to the OP!
start.next = then.next;
then.next = pre.next;
pre.next = then;
then = start.next;
}
return dummy.next;
}
}
} |
package com.guilherme.charRNN;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import org.nd4j.linalg.api.iter.NdIndexIterator;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import org.nd4j.linalg.ops.transforms.Transforms;
/**
* This is the generative single layer RNN
*/
public class CharRNN {
public static void main(String[] args) {
try {
new CharRNN();
} catch (IOException e) {
System.out.print(e.toString());
}
}
// Hyperparameters
private int hiddenSize = 100;
private int seqLength = 25;
private double learningRate = 0.1;
private String readFile(String fileLocation) throws IOException {
File file = new File(fileLocation);
return Files.toString(file, Charsets.UTF_8);
}
private ArrayList<Character> getUniqueChars( String arg ) {
ArrayList<Character> unique = new ArrayList<Character>();
for( int i = 0; i < arg.length(); i++)
if( !unique.contains( arg.charAt( i ) ) )
unique.add( arg.charAt( i ) );
return unique;
}
private CharRNN() throws IOException {
// Read in file
String data = readFile("input.txt");
ArrayList<Character> chars = getUniqueChars(data);
// Sizes
int dataSize = data.length();
int vocabSize = chars.size();
System.out.println("Size of data: " + dataSize);
System.out.println("Size of vocabulary: " + vocabSize);
// Maps
HashMap<Character, Integer> CharToIx = new HashMap<Character, Integer>();
HashMap<Integer, Character> IxToChar = new HashMap<Integer, Character>();
for (int i = 0; i < chars.size(); i++) {
CharToIx.put(chars.get(i), i);
IxToChar.put(i, chars.get(i));
}
// Model parameters
INDArray Wxh = Nd4j.rand(hiddenSize, vocabSize).mul(0.01);
INDArray Whh = Nd4j.rand(hiddenSize, hiddenSize).mul(0.01);
INDArray Why = Nd4j.rand(vocabSize, hiddenSize).mul(0.01);
INDArray bh = Nd4j.zeros(hiddenSize, 1);
INDArray by = Nd4j.zeros(vocabSize, 1);
int n = 0;
int p = 0;
// Adagrad memory
INDArray mWxh = Nd4j.zeros(hiddenSize, vocabSize);
INDArray mWhh = Nd4j.zeros(hiddenSize, hiddenSize);
INDArray mWhy = Nd4j.zeros(vocabSize, hiddenSize);
INDArray mbh = Nd4j.zeros(hiddenSize, 1);
INDArray mby = Nd4j.zeros(vocabSize, 1);
// Loss at iteration 0
double smoothLoss = - Math.log(1.0/vocabSize) * seqLength;
INDArray hprev = Nd4j.zeros(hiddenSize, 1);
while (true) {
// prepare inputs (we're sweeping from left to right in steps seq_length long)
if (p + seqLength+1 >= data.length() || n == 0) {
// Reset the RNN memory
hprev = Nd4j.zeros(hiddenSize, 1);
// Start from the beggining of the data
p = 0;
}
int[] inputs = new int[seqLength];
int[] targets = new int[seqLength];
// Create inputs and trage array
for (int i = p; i < p + seqLength; i++) {
inputs[i - p] = CharToIx.get(data.charAt(i));
targets[i - p] = CharToIx.get(data.charAt(i+1));
}
// Sample from the model every 100 iterations
if (n % 100 == 0) {
int[] sampleIx = sample(hprev, inputs[0], n, Wxh, Whh, Why, bh, by, vocabSize);
char[] generatedText = new char[sampleIx.length];
int i = 0;
for(int ix: sampleIx) {
generatedText[i] = IxToChar.get(ix);
i++;
}
System.out.println("Generated text: ");
System.out.println(new String(generatedText));
}
// forward seq_length characters through the net and fetch gradient
Container propagation = lossFun(inputs, targets, hprev, Wxh, Whh, Why, bh, by, vocabSize, hiddenSize);
// Update loss after forward and backprop
smoothLoss = smoothLoss * 0.999 + propagation.loss * 0.001;
if (n % 100 == 0) {
System.out.println("Iteration: " + n + " Loss: " + smoothLoss);
}
// parameter update with Adagrad
mWxh = mWxh.add(Wxh.muli(Wxh));
mWhh = mWhh.add(Whh.muli(Whh));
mWhy = mWhy.add(Why.muli(Why));
mbh = mbh.add(bh.muli(bh));
mby = mby.add(by.muli(by));
// Adagrad update
Wxh = propagation.dWxh.mul(- learningRate).div(Transforms.sqrt(mWxh.add(0.00000001)));
Whh = propagation.dWhh.mul(- learningRate).div(Transforms.sqrt(mWhh.add(0.00000001)));
Why = propagation.dWhy.mul(- learningRate).div(Transforms.sqrt(mWhy.add(0.00000001)));
bh = propagation.dbh.mul(- learningRate).div(Transforms.sqrt(mbh.add(0.00000001)));
by = propagation.dby.mul(- learningRate).div(Transforms.sqrt(mby.add(0.00000001)));
// move data pointer
p += seqLength;
// iteration counter
n++;
}
}
private static Container lossFun(int[] inputs, int[] targets, INDArray hprev, INDArray Wxh, INDArray Whh,
INDArray Why, INDArray bh, INDArray by, int vocabSize, int hiddenSize) {
HashMap<Integer, INDArray> xs = new HashMap<Integer, INDArray>();
HashMap<Integer, INDArray> hs = new HashMap<Integer, INDArray>();
HashMap<Integer, INDArray> ys = new HashMap<Integer, INDArray>();
HashMap<Integer, INDArray> ps = new HashMap<Integer, INDArray>();
// Put in the previous state
hs.put(-1, hprev);
double loss = 0;
// Forward pass
for(int t = 0; t < inputs.length; t++) {
// Input - X
// Generate oneHot representation
int idx = inputs[t];
float[] oneHotArray = new float[vocabSize];
for (int j = 0; j < oneHotArray.length; j++) {
if ( j == idx ) {
oneHotArray[j] = 1;
}
}
xs.put(t, Nd4j.create(oneHotArray).transpose());
// Hidden - H
// Input layer to hidden
INDArray dot1 = Wxh.mmul(xs.get(t));
// Hidden layer to hidden
INDArray dot2 = Whh.mmul(hs.get(t - 1)).add(bh);
INDArray tmp = dot1.add(dot2);
// Hidden state step, squash between -1 and 1 with hyperbolic tan
hs.put(t, Transforms.tanh(tmp));
// Output - Y
// Dot product between weights from h to y and hidden state, plus bias
ys.put(t, Why.mmul(hs.get(t)).add(by));
// Probabilities - P
INDArray exp = Transforms.exp(ys.get(t));
INDArray cumExp = exp.cumsum(0);
ps.put(t, exp.div(cumExp));
System.out.println(ps.get(t).toString());
// Calculate the cross-entropy loss
INDArray psState = ps.get(t);
loss += - Math.log(psState.getDouble(targets[t], 0));
}
// Backward pass
// Gradients
INDArray dWxh = Nd4j.zeros(hiddenSize, vocabSize);
INDArray dWhh = Nd4j.zeros(hiddenSize, hiddenSize);
INDArray dWhy = Nd4j.zeros(vocabSize, hiddenSize);
INDArray dbh = Nd4j.zeros(hiddenSize, 1);
INDArray dby = Nd4j.zeros(vocabSize, 1);
INDArray dhnext = Nd4j.zeros(hs.get(0).shape()[0], 1);
// backward pass: compute gradients going backwards
for (int t = inputs.length - 1; t >= 0; t
// P to y
INDArray dy = ps.get(t);
int idx = targets[t];
double newValue = dy.getDouble(idx) - 1;
dy.putScalar(new int[]{idx, 0}, newValue);
// Y to H
INDArray dot1 = dy.mmul(hs.get(t).transpose());
dWhy.add(dot1);
dby.add(dy);
//Backprop into h
dot1 = Why.transpose().mmul(dy);
INDArray dh = dot1.add(dhnext);
INDArray squaredH = hs.get(t).muli(hs.get(t));
INDArray ones = Nd4j.ones(squaredH.shape());
INDArray dhraw = dh.muli(ones.sub(squaredH));
dbh.add(dhraw);
// Update gradients
dWxh.add(dhraw.mmul(xs.get(t).transpose()));
dWhh.add(dhraw.mmul(hs.get(t-1).transpose()));
dhnext = Whh.transpose().mmul(dhraw);
}
// Clip to avoid exploding gradients
dWxh = clipMatrix(dWxh);
dWhy = clipMatrix(dWhy);
dbh = clipMatrix(dbh);
dby = clipMatrix(dby);
return new Container(loss, dWxh, dWhh, dWhy, dbh, dby, hs.get(inputs.length - 1));
}
/**
* Clip the values within a matrix to -5 to 5 range, to avoid exploding gradients
* @param matrix
* @return
*/
private static INDArray clipMatrix(INDArray matrix) {
NdIndexIterator iter = new NdIndexIterator(matrix.shape());
while (iter.hasNext()) {
int[] nextIndex = iter.next();
double nextVal = matrix.getDouble(nextIndex);
if (nextVal < -5) {
nextVal = -5;
}
if (nextVal > 5) {
nextVal = 5;
}
matrix.putScalar(nextIndex, nextVal);
}
return matrix;
}
/**
* sample a sequence of integers from the model
* h is memory state, seed_ix is seed letter for first time step
* @param h
* @param seedIdx
* @param n
* @return
*/
private static int[] sample(INDArray h, int seedIdx, int n, INDArray Wxh, INDArray Whh,
INDArray Why, INDArray bh, INDArray by, int vocabSize) {
float[] oneHotArray = new float[vocabSize];
for (int j = 0; j < oneHotArray.length; j++) {
if ( j == seedIdx ) {
oneHotArray[j] = 1;
}
}
INDArray x = Nd4j.create(oneHotArray).transpose();
System.out.println(x.toString());
int[] ixes = new int[n];
for (int t = 0; t < n; t++) {
INDArray dot1 = Wxh.mmul(x);
// Hidden layer to hidden
INDArray dot2 = Whh.mmul(h).add(bh);
INDArray tmp = dot1.add(dot2);
// Hidden state step, squash between -1 and 1 with hyperbolic tan
h = Transforms.tanh(tmp);
// Output - Y
// Dot product between weights from h to y and hidden state, plus bias
INDArray y = Why.mmul(h).add(by);
// Probabilities - P
INDArray exp = Transforms.exp(y);
INDArray cumExp = exp.cumsum(0);
INDArray p = exp.div(cumExp);
// Random choice
int[] to_select = new int[vocabSize];
for (int i = 0; i < vocabSize; i++){
to_select[i] = i;
}
int idx = randChoice(to_select, p);
System.out.println("Sampled idx: " + idx);
oneHotArray = new float[vocabSize];
for (int j = 0; j < oneHotArray.length; j++) {
if ( j == idx ) {
oneHotArray[j] = 1;
}
}
x = Nd4j.create(oneHotArray, new int[]{vocabSize, 1});
ixes[t] = idx;
}
return ixes;
}
/**
* Randomly select an index from a vector, given a vector of probabilities
* @param idxs
* @param probabilities
* @return
*/
private static int randChoice(int[] idxs, INDArray probabilities) {
double p = Math.random();
double cumulativeProbability = 0.0;
// System.out.println("Probabilities");
// System.out.println(probabilities.toString());
int idx = 0;
for (; idx < idxs.length; idx++) {
cumulativeProbability += probabilities.getDouble(idx);
if (p <= cumulativeProbability) {
return idx;
}
}
return idx;
}
} |
package com.jaamsim.ui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowFocusListener;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import com.jaamsim.Graphics.DisplayEntity;
import com.jaamsim.Graphics.EntityLabel;
import com.jaamsim.basicsim.Entity;
import com.jaamsim.basicsim.ErrorException;
import com.jaamsim.basicsim.ObjectType;
import com.jaamsim.basicsim.Simulation;
import com.jaamsim.controllers.RenderManager;
import com.jaamsim.input.InputAgent;
import com.jaamsim.input.KeywordIndex;
import com.jaamsim.math.Vec3d;
public class ObjectSelector extends FrameBox {
private static ObjectSelector myInstance;
// Tree view properties
private DefaultMutableTreeNode top;
private final DefaultTreeModel treeModel;
private final JTree tree;
private final JScrollPane treeView;
public static Entity currentEntity;
private long entSequence;
public ObjectSelector() {
super( "Object Selector" );
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(FrameBox.getCloseListener("ShowObjectSelector"));
addWindowFocusListener(new MyFocusListener());
top = new DefaultMutableTreeNode();
treeModel = new DefaultTreeModel(top);
tree = new JTree();
tree.setModel(treeModel);
tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION );
tree.setRootVisible(false);
tree.setShowsRootHandles(true);
tree.setInvokesStopCellEditing(true);
treeView = new JScrollPane(tree);
getContentPane().add(treeView);
entSequence = 0;
setLocation(GUIFrame.COL1_START, GUIFrame.BOTTOM_START);
setSize(GUIFrame.COL1_WIDTH, GUIFrame.HALF_BOTTOM);
tree.addTreeSelectionListener( new MyTreeSelectionListener() );
treeModel.addTreeModelListener( new MyTreeModelListener(tree) );
tree.addMouseListener(new MyMouseListener());
tree.addKeyListener(new MyKeyListener());
}
@Override
public void setEntity(Entity ent) {
if (ent == currentEntity)
return;
currentEntity = ent;
if (tree == null)
return;
long curSequence = Entity.getEntitySequence();
if (entSequence != curSequence) {
entSequence = curSequence;
updateTree();
}
if (currentEntity == null) {
tree.setSelectionPath(null);
tree.setEditable(false);
return;
}
tree.setEditable(true);
DefaultMutableTreeNode root = (DefaultMutableTreeNode)tree.getModel().getRoot();
Enumeration<?> e = root.depthFirstEnumeration();
while (e.hasMoreElements()) {
DefaultMutableTreeNode aNode = (DefaultMutableTreeNode)e.nextElement();
if (aNode.getUserObject() == currentEntity) {
TreePath path = new TreePath(aNode.getPath());
tree.scrollPathToVisible(path);
tree.setSelectionPath(path);
return;
}
}
}
@Override
public void updateValues(double simTime) {
if (!this.isVisible())
return;
long curSequence = Entity.getEntitySequence();
if (entSequence != curSequence) {
entSequence = curSequence;
updateTree();
}
}
public static void allowUpdate() {
myInstance.entSequence = 0;
}
/**
* Returns the only instance of the Object Selector
*/
public static synchronized ObjectSelector getInstance() {
if (myInstance == null)
myInstance = new ObjectSelector();
myInstance.treeView.getHorizontalScrollBar().getModel().setValue(0);
return myInstance;
}
private synchronized static void killInstance() {
myInstance = null;
}
@Override
public void dispose() {
killInstance();
currentEntity = null;
super.dispose();
}
private void updateTree() {
if (tree == null || top == null)
return;
// Store all the expanded paths
Enumeration<TreePath> expandedPaths = tree.getExpandedDescendants(new TreePath(top));
// Identify the selected entity (cannot use currentEntity -- would race with setEntity)
Entity selectedEnt = null;
TreePath selectedPath = tree.getSelectionPath();
if (selectedPath != null) {
Object selectedObj = ((DefaultMutableTreeNode)selectedPath.getLastPathComponent()).getUserObject();
if (selectedObj instanceof Entity)
selectedEnt = (Entity)selectedObj;
}
// Clear the present tree
top.removeAllChildren();
// Add the instance for Simulation to the top of the tree as a single leaf node
top.add(new DefaultMutableTreeNode(Simulation.getInstance(), false));
// Create the tree structure for palettes and object types in the correct order
for (int i = 0; i < ObjectType.getAll().size(); i++) {
try {
final ObjectType type = ObjectType.getAll().get(i);
if (type == null)
continue;
// Find or create the node for the palette
DefaultMutableTreeNode paletteNode = getNodeFor_In(type.getPaletteName(), top);
if (paletteNode == null) {
paletteNode = new DefaultMutableTreeNode(type.getPaletteName());
top.add(paletteNode);
}
// Add the node for the Object Type to the palette
DefaultMutableTreeNode typeNode = new DefaultMutableTreeNode(type.getName(), true);
paletteNode.add(typeNode);
}
catch (IndexOutOfBoundsException e) {}
}
// Loop through the entities in the model
for (int i = 0; i < Entity.getAll().size(); i++) {
try {
final Entity ent = Entity.getAll().get(i);
// The instance for Simulation has already been added
if (ent == Simulation.getInstance())
continue;
// Skip an entity that is locked
if (ent.testFlag(Entity.FLAG_LOCKED))
continue;
// Determine the object type for this entity
final ObjectType type = ent.getObjectType();
if (type == null)
continue;
// Find the pallete node for this entity
DefaultMutableTreeNode paletteNode = getNodeFor_In(type.getPaletteName(), top);
if (paletteNode == null)
continue;
// Find the object type node for this entity
DefaultMutableTreeNode typeNode = getNodeFor_In(type.getName(), paletteNode);
if (typeNode == null)
continue;
// Add the entity to the object type node
DefaultMutableTreeNode entityNode = new DefaultMutableTreeNode(ent, false);
typeNode.add(entityNode);
}
catch (IndexOutOfBoundsException e) {}
}
// Remove any object type tree nodes that have no entities
ArrayList<DefaultMutableTreeNode> nodesToRemove = new ArrayList<>();
Enumeration<DefaultMutableTreeNode> paletteEnum = top.children();
while (paletteEnum.hasMoreElements()) {
DefaultMutableTreeNode paletteNode = paletteEnum.nextElement();
Enumeration<DefaultMutableTreeNode> typeEnum = paletteNode.children();
while (typeEnum.hasMoreElements()) {
DefaultMutableTreeNode typeNode = typeEnum.nextElement();
if (typeNode.isLeaf())
nodesToRemove.add(typeNode);
}
for (DefaultMutableTreeNode typeNode : nodesToRemove) {
paletteNode.remove(typeNode);
}
nodesToRemove.clear();
}
// Remove any palettes that have no object types left
paletteEnum = top.children();
while (paletteEnum.hasMoreElements()) {
DefaultMutableTreeNode paletteNode = paletteEnum.nextElement();
// Do not remove any of the special nodes such as the instance for Simulation
if (!paletteNode.getAllowsChildren())
continue;
if (paletteNode.isLeaf())
nodesToRemove.add(paletteNode);
}
for (DefaultMutableTreeNode paletteNode : nodesToRemove) {
top.remove(paletteNode);
}
// Refresh the tree
treeModel.reload(top);
// Restore the path to the selected entity
if (selectedEnt != null) {
TreePath path = ObjectSelector.getPathToEntity(selectedEnt, top);
if (path != null)
tree.setSelectionPath(path);
}
// Restore all the expanded paths
while (expandedPaths != null && expandedPaths.hasMoreElements()) {
TreePath oldPath = expandedPaths.nextElement();
if (oldPath.getPathCount() < 2)
continue;
// Path to a palette
DefaultMutableTreeNode oldPaletteNode = (DefaultMutableTreeNode) (oldPath.getPath())[1];
String paletteName = (String) (oldPaletteNode.getUserObject());
DefaultMutableTreeNode paletteNode = getNodeFor_In(paletteName, top);
if (paletteNode == null)
continue;
if (oldPath.getPathCount() == 2) {
Object[] nodeList = { top, paletteNode };
tree.expandPath(new TreePath(nodeList));
continue;
}
// Path to an object type
DefaultMutableTreeNode oldTypeNode = (DefaultMutableTreeNode) (oldPath.getPath())[2];
String typeName = (String) (oldTypeNode.getUserObject());
DefaultMutableTreeNode typeNode = getNodeFor_In(typeName, paletteNode);
if (typeNode == null)
continue;
Object[] nodeList = { top, paletteNode, typeNode };
tree.expandPath(new TreePath(nodeList));
}
}
/**
* Returns a tree node for the specified userObject in the specified parent.
* If a node, already exists for this parent, it is returned. If it does
* not exist, then null is returned.
* @param userObject - object for the tree node.
* @param parent - object's parent
* @return tree node for the object.
*/
private static DefaultMutableTreeNode getNodeFor_In(Object userObject, DefaultMutableTreeNode parent) {
// Loop through the parent's children
Enumeration<DefaultMutableTreeNode> enumeration = parent.children();
while (enumeration.hasMoreElements()) {
DefaultMutableTreeNode eachNode = enumeration.nextElement();
if (eachNode.getUserObject() == userObject ||
userObject instanceof String && ((String) userObject).equals(eachNode.getUserObject()) )
return eachNode;
}
return null;
}
private static TreePath getPathToEntity(Entity ent, DefaultMutableTreeNode root) {
final ObjectType type = ent.getObjectType();
if (type == null)
return null;
DefaultMutableTreeNode paletteNode = getNodeFor_In(type.getPaletteName(), root);
if (paletteNode == null)
return null;
DefaultMutableTreeNode typeNode = getNodeFor_In(type.getName(), paletteNode);
if (typeNode == null)
return null;
DefaultMutableTreeNode entityNode = getNodeFor_In(ent, typeNode);
if (entityNode == null)
return null;
Object[] nodeList = { root, paletteNode, typeNode, entityNode };
return new TreePath(nodeList);
}
static class MyTreeSelectionListener implements TreeSelectionListener {
@Override
public void valueChanged( TreeSelectionEvent e ) {
JTree tree = (JTree) e.getSource();
DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
if(node == null) {
// This occurs when we set no selected entity (null) and then
// force the tree to have a null selected node
return;
}
Object userObj = node.getUserObject();
if (userObj instanceof Entity) {
FrameBox.setSelectedEntity((Entity)userObj);
}
else {
FrameBox.setSelectedEntity(null);
}
}
}
static class MyTreeModelListener implements TreeModelListener {
private final JTree tree;
public MyTreeModelListener(JTree tree) {
this.tree = tree;
}
@Override
public void treeNodesChanged( TreeModelEvent e ) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
String newName = ((String)node.getUserObject()).trim();
try {
InputAgent.renameEntity(currentEntity, newName);
if (currentEntity instanceof DisplayEntity) {
DisplayEntity dEnt = (DisplayEntity) currentEntity;
EntityLabel label = EntityLabel.getLabel(dEnt);
if (label != null)
label.updateForTargetNameChange();
}
}
catch (ErrorException err) {
GUIFrame.showErrorDialog("Input Error", err.getMessage());
}
finally {
node.setUserObject(currentEntity);
FrameBox.reSelectEntity();
}
}
@Override
public void treeNodesInserted(TreeModelEvent e) {}
@Override
public void treeNodesRemoved(TreeModelEvent e) {}
@Override
public void treeStructureChanged(TreeModelEvent e) {}
}
static class InputMenuItem extends MenuItem {
private final Entity ent;
public InputMenuItem(Entity ent) {
super("Input Editor");
this.ent = ent;
}
@Override
public void action() {
InputAgent.applyArgs(Simulation.getInstance(), "ShowInputEditor", "TRUE");
FrameBox.setSelectedEntity(ent);
}
}
static class PropertyMenuItem extends MenuItem {
private final Entity ent;
public PropertyMenuItem(Entity ent) {
super("Property Viewer");
this.ent = ent;
}
@Override
public void action() {
InputAgent.applyArgs(Simulation.getInstance(), "ShowPropertyViewer", "TRUE");
FrameBox.setSelectedEntity(ent);
}
}
static class OutputMenuItem extends MenuItem {
private final Entity ent;
public OutputMenuItem(Entity ent) {
super("Output Viewer");
this.ent = ent;
}
@Override
public void action() {
InputAgent.applyArgs(Simulation.getInstance(), "ShowOutputViewer", "TRUE");
FrameBox.setSelectedEntity(ent);
}
}
static class DuplicateMenuItem extends MenuItem {
private final Entity ent;
public DuplicateMenuItem(Entity ent) {
super("Duplicate");
this.ent = ent;
}
@Override
public void action() {
Entity copiedEntity = InputAgent.defineEntityWithUniqueName(ent.getClass(),
ent.getName(), "_Copy", true);
// Match all the inputs
copiedEntity.copyInputs(ent);
// Position the duplicated entity next to the original
if (copiedEntity instanceof DisplayEntity) {
DisplayEntity dEnt = (DisplayEntity)copiedEntity;
Vec3d pos = dEnt.getPosition();
pos.x += 0.5d * dEnt.getSize().x;
pos.y -= 0.5d * dEnt.getSize().y;
dEnt.setPosition(pos);
// Set the input for the "Position" keyword to the new value
KeywordIndex kw = InputAgent.formatPointInputs("Position", pos, "m");
InputAgent.apply(dEnt, kw);
}
// Show the duplicated entity in the editors and viewers
FrameBox.setSelectedEntity(copiedEntity);
}
}
static class DeleteMenuItem extends MenuItem {
private final Entity ent;
public DeleteMenuItem(Entity ent) {
super("Delete");
this.ent = ent;
}
@Override
public void action() {
ent.kill();
FrameBox.setSelectedEntity(null);
}
}
static class GraphicsMenuItem extends MenuItem {
private final DisplayEntity ent;
private final int x;
private final int y;
public GraphicsMenuItem(DisplayEntity ent, int x, int y) {
super("Change Graphics");
this.ent = ent;
this.x = x;
this.y = y;
}
@Override
public void action() {
// More than one DisplayModel(LOD) or No DisplayModel
if(ent.getDisplayModelList() == null)
return;
GraphicBox graphicBox = GraphicBox.getInstance(ent, x, y);
graphicBox.setVisible( true );
}
}
static class LabelMenuItem extends MenuItem {
private final DisplayEntity ent;
public LabelMenuItem(DisplayEntity ent) {
super("Add Label");
this.ent = ent;
}
@Override
public void action() {
EntityLabel label = InputAgent.defineEntityWithUniqueName(EntityLabel.class, ent.getName() + "_Label", "", true);
InputAgent.applyArgs(label, "TargetEntity", ent.getName());
InputAgent.applyArgs(label, "RelativeEntity", ent.getName());
if (ent.getCurrentRegion() != null)
InputAgent.applyArgs(label, "Region", ent.getCurrentRegion().getName());
double ypos = -0.15 - 0.5*ent.getSize().y;
InputAgent.apply(label, InputAgent.formatPointInputs("Position", new Vec3d(0.0, ypos, 0.0), "m"));
InputAgent.applyArgs(label, "TextHeight", "0.15", "m");
label.resizeForText();
}
}
static class CenterInViewMenuItem extends MenuItem {
private final DisplayEntity ent;
private final View v;
public CenterInViewMenuItem(DisplayEntity ent, View v) {
super("Center in View");
this.ent = ent;
this.v = v;
}
@Override
public void action() {
// Move the camera position so that the entity is in the centre of the screen
Vec3d viewPos = new Vec3d(v.getGlobalPosition());
viewPos.sub3(v.getGlobalCenter());
viewPos.add3(ent.getPosition());
v.setCenter(ent.getPosition());
v.setPosition(viewPos);
}
}
private static class JActionMenuItem extends JMenuItem
implements ActionListener {
private final MenuItem de;
public JActionMenuItem(MenuItem item) {
super(item.menuName);
de = item;
this.setEnabled(item.enabled);
this.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
de.action();
}
}
/**
* A miscelaneous utility to populate a JPopupMenu with a list of DisplayEntity menu items (for the right click menu)
* @param menu
* @param menuItems
*/
public static void populateMenu(JPopupMenu menu, Entity ent, int x, int y) {
ArrayList<MenuItem> menuItems = getMenuItems(ent, x, y);
for (MenuItem item : menuItems) {
menu.add(new JActionMenuItem(item));
}
}
private static ArrayList<MenuItem> getMenuItems(Entity ent, int x, int y) {
ArrayList<MenuItem> list = new ArrayList<>();
list.add(new InputMenuItem(ent));
list.add(new OutputMenuItem(ent));
list.add(new PropertyMenuItem(ent));
if (!ent.testFlag(Entity.FLAG_GENERATED))
list.add(new DuplicateMenuItem(ent));
list.add(new DeleteMenuItem(ent));
if (ent instanceof DisplayEntity) {
DisplayEntity dEnt = (DisplayEntity)ent;
if (RenderManager.isGood())
list.add(new GraphicsMenuItem(dEnt, x, y));
if (RenderManager.isGood()) {
View v = RenderManager.inst().getActiveView();
if (v != null) {
LabelMenuItem item = new LabelMenuItem(dEnt);
if (dEnt instanceof EntityLabel || EntityLabel.getLabel(dEnt) != null)
item.enabled = false;
list.add(item);
list.add(new CenterInViewMenuItem(dEnt, v));
}
}
}
if (ent instanceof MenuItemEntity)
((MenuItemEntity)ent).gatherMenuItems(list, x, y);
return list;
}
static class MyMouseListener implements MouseListener {
private final JPopupMenu menu= new JPopupMenu();
@Override
public void mouseClicked(MouseEvent e) {
if(e.getButton() != MouseEvent.BUTTON3)
return;
if(currentEntity == null)
return;
// Right mouse click on a movable DisplayEntity
menu.removeAll();
ObjectSelector.populateMenu(menu, currentEntity, e.getX(), e.getY());
menu.show(e.getComponent(), e.getX(), e.getX());
}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
}
static class MyKeyListener implements KeyListener {
@Override
public void keyReleased(KeyEvent e) {
if (e.getKeyCode() != KeyEvent.VK_DELETE)
return;
if(currentEntity instanceof DisplayEntity ) {
DisplayEntity disp = (DisplayEntity)currentEntity;
if(! disp.isMovable())
return;
// Delete key was released on a movable DisplayEntity
disp.kill();
FrameBox.setSelectedEntity(null);
}
}
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyTyped(KeyEvent e) {}
}
static class MyFocusListener implements WindowFocusListener {
@Override
public void windowGainedFocus(WindowEvent arg0) {}
@Override
public void windowLostFocus(WindowEvent e) {
// Complete any editing that has started
ObjectSelector.myInstance.tree.stopEditing();
}
}
} |
package com.jcabi.manifests;
import com.jcabi.aspects.Immutable;
import com.jcabi.log.Logger;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.jar.Attributes;
import java.util.jar.Attributes.Name;
import java.util.jar.Manifest;
import javax.servlet.ServletContext;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.SerializationUtils;
@Immutable
@SuppressWarnings("PMD.UseConcurrentHashMap")
public final class Manifests {
/**
* Injected attributes.
* @see #inject(String,String)
*/
private static final Map<String, String> INJECTED =
new ConcurrentHashMap<String, String>();
/**
* Attributes retrieved from all existing {@code MANIFEST.MF} files.
* @see #load()
*/
private static Map<String, String> attributes = Manifests.load();
/**
* Failures registered during loading.
* @see #load()
*/
private static Map<URI, String> failures;
/**
* It's a utility class, can't be instantiated.
*/
private Manifests() {
// intentionally empty
}
public static String read(
@NotNull(message = "attribute name can't be NULL")
@Pattern(regexp = ".+", message = "attribute name can't be empty")
final String name) {
if (Manifests.attributes == null) {
throw new IllegalArgumentException(
"Manifests haven't been loaded yet, internal error"
);
}
if (!Manifests.exists(name)) {
final StringBuilder bldr = new StringBuilder(
Logger.format(
// @checkstyle LineLength (1 line)
"Atribute '%s' not found in MANIFEST.MF file(s) among %d other attribute(s) %[list]s and %d injection(s)",
name,
Manifests.attributes.size(),
new TreeSet<String>(Manifests.attributes.keySet()),
Manifests.INJECTED.size()
)
);
if (!Manifests.failures.isEmpty()) {
bldr.append("; failures: ").append(
Logger.format("%[list]s", Manifests.failures.keySet())
);
}
throw new IllegalArgumentException(bldr.toString());
}
String result;
if (Manifests.INJECTED.containsKey(name)) {
result = Manifests.INJECTED.get(name);
} else {
result = Manifests.attributes.get(name);
}
Logger.debug(Manifests.class, "#read('%s'): found '%s'", name, result);
return result;
}
/**
* Inject new attribute.
*
* <p>An attribute can be injected in runtime, mostly for the sake of
* unit and integration testing. Once injected an attribute becomes
* available with {@link #read(String)}.
*
* <p>The method is thread-safe.
*
* @param name Name of the attribute
* @param value The value of the attribute being injected
*/
public static void inject(
@NotNull(message = "injected name can't be NULL")
@Pattern(regexp = ".+", message = "name of attribute can't be empty")
final String name,
@NotNull(message = "inected value can't be NULL") final String value) {
if (Manifests.INJECTED.containsKey(name)) {
Logger.info(
Manifests.class,
"#inject(%s, '%s'): replaced previous injection '%s'",
name,
value,
Manifests.INJECTED.get(name)
);
} else {
Logger.info(
Manifests.class,
"#inject(%s, '%s'): injected",
name,
value
);
}
Manifests.INJECTED.put(name, value);
}
/**
* Check whether attribute exists in any of {@code MANIFEST.MF} files.
*
* <p>Use this method before {@link #read(String)} to check whether an
* attribute exists, in order to avoid a runtime exception.
*
* <p>The method is thread-safe.
*
* @param name Name of the attribute to check
* @return Returns {@code TRUE} if it exists, {@code FALSE} otherwise
*/
public static boolean exists(
@NotNull(message = "name of attribute can't be NULL")
@Pattern(regexp = ".+", message = "name of attribute can't be empty")
final String name) {
final boolean exists = Manifests.attributes.containsKey(name)
|| Manifests.INJECTED.containsKey(name);
Logger.debug(Manifests.class, "#exists('%s'): %B", name, exists);
return exists;
}
/**
* Make a snapshot of current attributes and their values.
*
* <p>The method is thread-safe.
*
* @return The snapshot, to be used later with {@link #revert(byte[])}
*/
public static byte[] snapshot() {
byte[] snapshot;
synchronized (Manifests.INJECTED) {
snapshot = SerializationUtils.serialize(
(Serializable) Manifests.INJECTED
);
}
Logger.debug(
Manifests.class,
"#snapshot(): created (%d bytes)",
snapshot.length
);
return snapshot;
}
/**
* Revert to the state that was recorded by {@link #snapshot()}.
*
* <p>The method is thread-safe.
*
* @param snapshot The snapshot taken by {@link #snapshot()}
*/
@SuppressWarnings("unchecked")
public static void revert(@NotNull final byte[] snapshot) {
synchronized (Manifests.INJECTED) {
Manifests.INJECTED.clear();
Manifests.INJECTED.putAll(
(Map<String, String>) SerializationUtils.deserialize(snapshot)
);
}
Logger.debug(
Manifests.class,
"#revert(%d bytes): reverted",
snapshot.length
);
}
/**
* Append attributes from the web application {@code MANIFEST.MF}.
*
* <p>You can call this method in your own
* {@link javax.servlet.Filter} or
* {@link javax.servlet.ServletContextListener},
* in order to inject {@code MANIFEST.MF} attributes to the class.
*
* <p>The method is thread-safe.
*
* @param ctx Servlet context
* @see #Manifests()
* @throws IOException If some I/O problem inside
*/
public static void append(@NotNull final ServletContext ctx)
throws IOException {
final long start = System.currentTimeMillis();
URL main;
try {
main = ctx.getResource("/META-INF/MANIFEST.MF");
} catch (java.net.MalformedURLException ex) {
throw new IOException(ex);
}
if (main == null) {
Logger.warn(
Manifests.class,
"#append(%s): MANIFEST.MF not found in WAR package",
ctx.getClass().getName()
);
} else {
final Map<String, String> attrs = Manifests.loadOneFile(main);
Manifests.attributes.putAll(attrs);
Logger.info(
Manifests.class,
// @checkstyle LineLength (1 line)
"#append(%s): %d attribs loaded from %s in %[ms]s (%d total): %[list]s",
ctx.getClass().getName(),
attrs.size(),
main,
System.currentTimeMillis() - start,
Manifests.attributes.size(),
new TreeSet<String>(attrs.keySet())
);
}
}
/**
* Append attributes from the file.
*
* <p>The method is thread-safe.
*
* @param file The file to load attributes from
* @throws IOException If some I/O problem inside
*/
public static void append(@NotNull final File file) throws IOException {
final long start = System.currentTimeMillis();
Map<String, String> attrs;
try {
attrs = Manifests.loadOneFile(file.toURI().toURL());
} catch (java.net.MalformedURLException ex) {
throw new IOException(ex);
}
Manifests.attributes.putAll(attrs);
Logger.info(
Manifests.class,
// @checkstyle LineLength (1 line)
"#append('%s'): %d attributes loaded in %[ms]s (%d total): %[list]s",
file, attrs.size(),
System.currentTimeMillis() - start,
Manifests.attributes.size(),
new TreeSet<String>(attrs.keySet())
);
}
/**
* Load attributes from classpath.
*
* <p>This method doesn't throw any checked exceptions because it is called
* from a static context above. It's just more convenient to catch all
* exceptions here than above in a static call block.
*
* @return All found attributes
*/
private static Map<String, String> load() {
final long start = System.currentTimeMillis();
Manifests.failures = new ConcurrentHashMap<URI, String>();
final Map<String, String> attrs =
new ConcurrentHashMap<String, String>();
int count = 0;
for (URI uri : Manifests.uris()) {
try {
attrs.putAll(Manifests.loadOneFile(uri.toURL()));
} catch (IOException ex) {
Manifests.failures.put(uri, ex.getMessage());
Logger.error(
Manifests.class,
"#load(): '%s' failed %[exception]s",
uri, ex
);
}
++count;
}
Logger.info(
Manifests.class,
"#load(): %d attribs loaded from %d URL(s) in %[ms]s: %[list]s",
attrs.size(), count,
System.currentTimeMillis() - start,
new TreeSet<String>(attrs.keySet())
);
return attrs;
}
/**
* Find all URLs.
*
* <p>This method doesn't throw any checked exceptions just for convenience
* of calling of it (above in {@linke #load}), although it is clear that
* {@link IOException} is a good candidate for being thrown out of it.
*
* @return The list of URLs
* @see #load()
*/
private static Set<URI> uris() {
Enumeration<URL> resources;
try {
resources = Thread.currentThread().getContextClassLoader()
.getResources("META-INF/MANIFEST.MF");
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
final Set<URI> uris = new HashSet<URI>();
while (resources.hasMoreElements()) {
try {
uris.add(resources.nextElement().toURI());
} catch (URISyntaxException ex) {
throw new IllegalStateException(ex);
}
}
return uris;
}
/**
* Load attributes from one file.
*
* <p>Inside the method we catch {@code RuntimeException} (which may look
* suspicious) in order to protect our execution flow from expected (!)
* exceptions from {@link Manifest#getMainAttributes()}. For some reason,
* this JDK method doesn't throw checked exceptions if {@code MANIFEST.MF}
* file format is broken. Instead, it throws a runtime exception (an
* unchecked one), which we should catch in such an inconvenient way.
*
* @param url The URL of it
* @return The attributes loaded
* @see #load()
* @see tickets #193 and #323
* @throws IOException If some problem happens
*/
@SuppressWarnings("PMD.AvoidCatchingGenericException")
private static Map<String, String> loadOneFile(final URL url)
throws IOException {
final Map<String, String> props =
new ConcurrentHashMap<String, String>();
final InputStream stream = url.openStream();
try {
final Manifest manifest = new Manifest(stream);
final Attributes attrs = manifest.getMainAttributes();
for (Object key : attrs.keySet()) {
final String value = attrs.getValue((Name) key);
props.put(key.toString(), value);
}
Logger.debug(
Manifests.class,
"#loadOneFile('%s'): %d attributes loaded (%[list]s)",
url, props.size(), new TreeSet<String>(props.keySet())
);
} catch (RuntimeException ex) {
Logger.error(
Manifests.class,
"#getMainAttributes(): '%s' failed %[exception]s",
url, ex
);
} finally {
IOUtils.closeQuietly(stream);
}
return props;
}
} |
package com.shamanland.fab;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.LayerDrawable;
import android.os.Build;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.ImageButton;
import android.widget.ImageView;
public class FloatingActionButton extends ImageButton {
/**
* Constant representing normal size {@code 56dp}. Value: 0x0
*/
public static final int SIZE_NORMAL = 0;
/**
* Constant representing mini size {@code 40dp}. Value: 0x1
*/
public static final int SIZE_MINI = 1;
private int mSize;
private int mColor;
private ColorStateList mColorStateList;
private GradientDrawable mCircleDrawable;
/**
* Gets abstract size of this button.
*
* @return {@link #SIZE_NORMAL} or {@link #SIZE_MINI}
*/
public int getSize() {
return mSize;
}
/**
* Sets abstract size for this button.
* <p/>
* Xml attribute: {@code app:floatingActionButtonSize}
*
* @param size {@link #SIZE_NORMAL} or {@link #SIZE_MINI}
*/
public void setSize(int size) {
mSize = size;
}
/**
* Gets background color of this button.
*
* @return color
*/
public int getColor() {
return mColor;
}
/**
* Sets background color for this button.
* <p/>
* Xml attribute: {@code app:floatingActionButtonColor}
*
* @param color color
*/
public void setColor(int color) {
mColor = color;
}
/**
* Gets color state list used as background for this button.
*
* @return may be null
*/
public ColorStateList getColorStateList() {
return mColorStateList;
}
/**
* Sets color state list as background for this button.
* <p/>
* Xml attribute: {@code app:floatingActionButtonColor}
*
* @param colorStateList color
*/
public void setColorStateList(ColorStateList colorStateList) {
mColorStateList = colorStateList;
}
public FloatingActionButton(Context context) {
super(context);
init(context, null, 0);
}
public FloatingActionButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, R.attr.floatingActionButtonStyle);
}
public FloatingActionButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
TypedArray a;
try {
if (isInEditMode()) {
return;
}
if (attrs == null) {
return;
}
Resources.Theme theme = context.getTheme();
if (theme == null) {
return;
}
a = theme.obtainStyledAttributes(attrs, R.styleable.FloatingActionButton, defStyle, R.style.FloatingActionButton_Dark);
if (a == null) {
return;
}
} finally {
mSize = SIZE_NORMAL;
mColor = Color.GRAY;
mColorStateList = null;
}
try {
initAttrs(a);
} finally {
a.recycle();
}
initBackground();
}
private void initAttrs(TypedArray a) {
setSize(a.getInteger(R.styleable.FloatingActionButton_floatingActionButtonSize, SIZE_NORMAL));
setColor(a.getColor(R.styleable.FloatingActionButton_floatingActionButtonColor, Color.GRAY));
setColorStateList(a.getColorStateList(R.styleable.FloatingActionButton_floatingActionButtonColor));
}
/**
* Inflate and initialize background drawable for this view with arguments
* inflated from xml or specified using {@link #setSize(int)} or {@link #setColor(int)}
* <p/>
* Invoked from constructor, but it's allowed to invoke this method manually from code.
*/
@TargetApi(21)
public void initBackground() {
final int backgroundId;
if (mSize == SIZE_MINI) {
backgroundId = R.drawable.com_shamanland_fab_circle_mini;
} else {
backgroundId = R.drawable.com_shamanland_fab_circle_normal;
}
Drawable background = getResources().getDrawable(backgroundId);
if (background instanceof LayerDrawable) {
LayerDrawable layers = (LayerDrawable) background;
if (layers.getNumberOfLayers() == 2) {
Drawable shadow = layers.getDrawable(0);
Drawable circle = layers.getDrawable(1);
if (shadow instanceof GradientDrawable) {
((GradientDrawable) shadow.mutate()).setGradientRadius(getShadowRadius(shadow, circle));
}
if (circle instanceof GradientDrawable) {
mCircleDrawable = (GradientDrawable) circle.mutate();
mCircleDrawable.setColor(mColor);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
background = mCircleDrawable;
setElevation(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics()));
}
}
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
//noinspection deprecation
setBackgroundDrawable(background);
} else {
setBackground(background);
}
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
if (mCircleDrawable != null && mColorStateList != null) {
mCircleDrawable.setColor(mColorStateList.getColorForState(getDrawableState(), mColor));
// NOTE maybe this line is required only for Gingerbread
invalidate();
}
}
/**
* Calculates required radius of shadow.
*
* @param shadow underlay drawable
* @param circle overlay drawable
* @return calculated radius, always >= 1
*/
protected static int getShadowRadius(Drawable shadow, Drawable circle) {
int radius = 0;
if (shadow != null && circle != null) {
Rect rect = new Rect();
radius = (circle.getIntrinsicWidth() + (shadow.getPadding(rect) ? rect.left + rect.right : 0)) / 2;
}
return Math.max(1, radius);
}
} |
package com.loopperfect.buckaroo;
import com.google.common.io.MoreFiles;
import com.loopperfect.buckaroo.cli.CLICommand;
import com.loopperfect.buckaroo.cli.CLIParsers;
import com.loopperfect.buckaroo.tasks.LoggingTasks;
import com.loopperfect.buckaroo.views.ProgressView;
import com.loopperfect.buckaroo.views.SummaryView;
import com.loopperfect.buckaroo.virtualterminal.Color;
import com.loopperfect.buckaroo.virtualterminal.TerminalBuffer;
import com.loopperfect.buckaroo.virtualterminal.components.Component;
import com.loopperfect.buckaroo.virtualterminal.components.StackLayout;
import com.loopperfect.buckaroo.virtualterminal.components.Text;
import io.reactivex.Observable;
import io.reactivex.Scheduler;
import io.reactivex.annotations.NonNull;
import io.reactivex.observables.ConnectableObservable;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.schedulers.Schedulers;
import org.fusesource.jansi.AnsiConsole;
import org.jparsec.Parser;
import org.jparsec.error.ParserException;
import java.nio.charset.Charset;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.time.Instant;
import java.util.Arrays;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import static com.loopperfect.buckaroo.EvenMoreFiles.writeFile;
import static com.loopperfect.buckaroo.views.ProgressView.progressView;
import static com.loopperfect.buckaroo.views.SummaryView.summaryView;
public final class Main {
private Main() {}
public static void main(final String[] args) {
if (args.length == 0) {
System.out.println("Buck, Buck Buckaroo! \uD83E\uDD20");
System.out.println("https://buckaroo.readthedocs.io/");
return;
}
// We need to change the default behaviour of Schedulers.io()
// so that it has a bounded thread-pool.
// Take at least 2 threads to prevent dead-locks.
final int threads = 10;
final Scheduler IOScheduler = Schedulers.from(Executors.newFixedThreadPool(threads));
RxJavaPlugins.setIoSchedulerHandler(scheduler -> IOScheduler);
final FileSystem fs = FileSystems.getDefault();
final String rawCommand = String.join(" ", args);
// Send the command to the logging server, if present
//LoggingTasks.log(fs, rawCommand).subscribe(); // Ignore any results
// Parse the command
final Parser<CLICommand> commandParser = CLIParsers.commandParser;
try {
final CLICommand command = commandParser.parse(rawCommand);
final ExecutorService executorService = Executors.newCachedThreadPool();
final Scheduler scheduler = Schedulers.from(executorService);
final Context ctx = Context.of(fs, scheduler);
final Observable<Event> task = command.routine().apply(ctx);
final ConnectableObservable<Either<Throwable, Event>> events$ = task
.observeOn(scheduler)
.subscribeOn(scheduler)
.map(e->{
final Either<Throwable, Event> r = Either.right(e);
return r;
})
.onErrorReturn(Either::left)
.publish();
final Observable<Component> current$ = events$
.flatMap(x->{
if(x.left().isPresent()) return Observable.error(x.left().get());
return Observable.just(x.right().get());
})
.compose(ProgressView::progressView)
.subscribeOn(Schedulers.computation())
.sample(100, TimeUnit.MILLISECONDS)
.distinctUntilChanged();
final Observable<Component> summary$ = events$
.flatMap(x -> {
if(x.left().isPresent()) return Observable.error(x.left().get());
return Observable.just(x.right().get());
})
.compose(SummaryView::summaryView)
.subscribeOn(Schedulers.computation())
.lastElement().toObservable();
AnsiConsole.systemInstall();
TerminalBuffer buffer = new TerminalBuffer();
Observable
.concat(current$, summary$)
.map(c -> c.render(60))
.doOnNext(buffer::flip)
.doOnError(error -> {
buffer.flip(
StackLayout.of(
Text.of("buckaroo failed: "+ error.toString(), Color.RED),
Text.of("writing stacktrace to buckaroo-stacktrace.log", Color.YELLOW)
).render(60));
writeFile(
fs.getPath("").resolve("buckaroo-stacktrace.log"),
Arrays.stream(error.getStackTrace())
.map(s->s.toString())
.reduce(Instant.now().toString()+":", (a, b) -> a+"\n"+b),
Charset.defaultCharset(),
true);
}).doOnTerminate(() -> {
executorService.shutdown();
IOScheduler.shutdown();
scheduler.shutdown();
}).subscribe(x->{},e->{},()->{});
events$.connect();
} catch (final ParserException e) {
System.out.println("Uh oh!");
System.out.println(e.getMessage());
} catch(Throwable e){}
}
} |
package com.mollie.api.objects;
import java.math.BigDecimal;
public class Method {
public static final String IDEAL = "ideal";
public static final String PAYSAFECARD = "paysafecard";
public static final String CREDITCARD = "creditcard";
public static final String MISTERCASH = "mistercash";
public static final String SOFORT = "sofort";
public static final String BANKTRANSFER = "banktransfer";
public static final String DIRECTDEBIT = "directdebit";
public static final String PAYPAL = "paypal";
public static final String BITCOIN = "bitcoin";
public static final String BELFIUS = "belfius";
public static final String PODIUMCADEAUKAART = "podiumcadeaukaart";
private String id;
private String description;
private Amount amount;
private ImageGroup image;
public Method() {
}
public String id() { return id; }
public void setId(String anId) { id = anId; }
public String description() { return description; }
public void setDescription(String aDescription) { description = aDescription; }
public BigDecimal getMinimumAmount() {
return (amount != null ? amount.minimum() : null);
}
public BigDecimal getMaximumAmount() {
return (amount != null ? amount.maximum() : null);
}
public Amount amount() { return amount; }
public ImageGroup image() { return image; }
public static class Amount {
private BigDecimal minimum;
private BigDecimal maximum;
public BigDecimal minimum() { return minimum; }
public BigDecimal maximum() { return maximum; }
};
public static class ImageGroup {
private String normal;
private String bigger;
public String normal() { return normal; }
public String bigger() { return bigger; }
}
} |
package com.nhl.link.etl;
/**
* A descriptor of a {@link Row} attribute. May contain optional path expression
* that maps the attribute to a target attribute.
*/
public class RowAttribute {
private Class<?> type;
private String sourceName;
private String targetPath;
private int ordinal;
public RowAttribute(Class<?> type, String sourceName, String targetName, int ordinal) {
this.type = type;
this.sourceName = sourceName;
this.targetPath = targetName;
this.ordinal = ordinal;
}
/**
* Returns a position of the attribute in a row.
*/
public int getOrdinal() {
return ordinal;
}
public Class<?> type() {
return type;
}
/**
* Returns a String name of the attribute as provided by the source.
*/
public String getSourceName() {
return sourceName;
}
/**
* Returns a path expression that maps source Row value to a target
* property.
*/
public String getTargetPath() {
return targetPath;
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append("{sourceName:").append(sourceName).append(",targetName:").append(targetPath).append(",ordinal:")
.append(ordinal).append("}");
return buffer.toString();
}
} |
package com.nilhcem.fakesmtp;
import java.awt.EventQueue;
import javax.swing.UIManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.nilhcem.fakesmtp.core.Configuration;
import com.nilhcem.fakesmtp.gui.MainFrame;
/**
* Entry point of the application.
*
* @author Nilhcem
* @since 1.0
*/
public final class FakeSMTP {
private static final Logger LOGGER = LoggerFactory.getLogger(FakeSMTP.class);
private FakeSMTP() {
}
/**
* Sets some specific properties, and runs the main window.
* <p>
* Before opening the main window, this method will:
* <ul>
* <li>set a property for Mac OS X to take the menu bar off the JFrame;</li>
* <li>set a property for Mac OS X to set the name of the application menu item;</li>
* <li>turn off the bold font in all components for swing default theme;</li>
* <li>use the platform look and feel.</li>
* </ul>
* </p>
*
* @param args a list of parameters.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("com.apple.mrj.application.apple.menu.about.name", Configuration.INSTANCE.get("application.name"));
UIManager.put("swing.boldMetal", Boolean.FALSE);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
LOGGER.error("", e);
}
new MainFrame();
}
});
}
} |
package com.project1;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.SecureRandom;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.nimbusds.oauth2.sdk.ResponseType;
import com.nimbusds.oauth2.sdk.Scope;
import com.nimbusds.oauth2.sdk.id.ClientID;
import com.nimbusds.oauth2.sdk.id.State;
import com.nimbusds.openid.connect.sdk.AuthenticationRequest;
import com.nimbusds.openid.connect.sdk.Nonce;
import com.restfb.DefaultFacebookClient;
import com.restfb.FacebookClient;
import com.restfb.Version;
import com.restfb.scope.ExtendedPermissions;
import com.restfb.scope.ScopeBuilder;
import com.restfb.scope.UserDataPermissions;
import java.net.URI;
import java.net.URL;
/**
* Servlet implementation class LoginRedirection
*/
public class LoginRedirection extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginRedirection() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
String realm = request.getParameter("direction");
if (realm.equalsIgnoreCase("Google")) {
// REDIRECT THEM TO GOOGLE
URI redirectURI = null;
try {
redirectURI = new URI("http://192.168.12.16.nip.io:8080/project1/ReturnGoogle");
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
URI authURI = null;
try {
authURI = new URI("https://accounts.google.com/o/oauth2/v2/auth");
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ResponseType rt = new ResponseType("code");
Scope scope = new Scope("openid", "email", "profile");
ClientID clientID = new ClientID(
"664700022174-tkgm8ehfjl4sieruvsi1chqkassg6n6p.apps.googleusercontent.com");
// State state = new State();
String state1 = new BigInteger(130, new SecureRandom()).toString(32);
request.getSession().setAttribute("state", state1);
State state = new State(state1);
Nonce nonce = null; // new Nonce(); -- nonce not supported by Google
AuthenticationRequest authRequest = new AuthenticationRequest(redirectURI, rt, scope, clientID, redirectURI,
state, nonce);
URI parameterizedRedirectURI = null;
try {
parameterizedRedirectURI = new URI(authURI.toString() + "?" + authRequest.toQueryString());
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String redirectString = parameterizedRedirectURI.toString();
response.sendRedirect(redirectString);
} else if (realm.equalsIgnoreCase("Github")) {
String appId = "3fc8c836208f5da2ffa9";
String redirectUrl = "http://192.168.12.16.nip.io:8080/project1/ReturnPaypal";
String returnValue = "https://github.com/login/oauth/authorize?client_id=" + appId + "&redirect_uri="
+ redirectUrl + "&scope=user:email";
response.sendRedirect(returnValue);
} else if (realm.equalsIgnoreCase("Facebook")) {
String redirectUrl = "http://192.168.12.16:8080/project1/ReturnFacebook";
String appId = "592725680924003";
ScopeBuilder scopeBuilder = new ScopeBuilder();
scopeBuilder.addPermission(ExtendedPermissions.EMAIL);
FacebookClient client = new DefaultFacebookClient(Version.VERSION_2_5);
String loginDialogUrlString = client.getLoginDialogUrl(appId, redirectUrl, scopeBuilder);
response.sendRedirect(loginDialogUrlString);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
} |
package com.untamedears.humbug;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minecraft.server.v1_8_R2.EntityEnderPearl;
import net.minecraft.server.v1_8_R2.EntityTypes;
import net.minecraft.server.v1_8_R2.Item;
import net.minecraft.server.v1_8_R2.ItemEnderPearl;
import net.minecraft.server.v1_8_R2.MinecraftKey;
import net.minecraft.server.v1_8_R2.RegistryID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.World.Environment;
import org.bukkit.block.Biome;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.block.BlockState;
import org.bukkit.block.Hopper;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Boat;
import org.bukkit.entity.Damageable;
import org.bukkit.entity.Enderman;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Horse;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Player;
import org.bukkit.entity.Skeleton;
import org.bukkit.entity.Skeleton.SkeletonType;
import org.bukkit.entity.Vehicle;
import org.bukkit.entity.minecart.HopperMinecart;
import org.bukkit.entity.minecart.StorageMinecart;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockFromToEvent;
import org.bukkit.event.block.BlockPhysicsEvent;
import org.bukkit.event.block.BlockPistonExtendEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.enchantment.EnchantItemEvent;
import org.bukkit.event.enchantment.PrepareItemEnchantEvent;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityCreatePortalEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityDeathEvent;
import org.bukkit.event.entity.EntityExplodeEvent;
import org.bukkit.event.entity.EntityInteractEvent;
import org.bukkit.event.entity.EntityPortalEvent;
import org.bukkit.event.entity.EntityShootBowEvent;
import org.bukkit.event.entity.ExpBottleEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.entity.SheepDyeWoolEvent;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.player.PlayerBucketEmptyEvent;
import org.bukkit.event.player.PlayerExpChangeEvent;
import org.bukkit.event.player.PlayerInteractEntityEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerItemConsumeEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerKickEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerTeleportEvent.TeleportCause;
import org.bukkit.event.vehicle.VehicleDestroyEvent;
import org.bukkit.event.vehicle.VehicleEnterEvent;
import org.bukkit.event.vehicle.VehicleExitEvent;
import org.bukkit.event.vehicle.VehicleMoveEvent;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
import org.bukkit.event.world.PortalCreateEvent;
import org.bukkit.event.world.StructureGrowEvent;
import org.bukkit.inventory.EntityEquipment;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.Recipe;
import org.bukkit.inventory.ShapedRecipe;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.metadata.MetadataValue;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scheduler.BukkitScheduler;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.util.Vector;
import com.untamedears.humbug.annotations.BahHumbug;
import com.untamedears.humbug.annotations.BahHumbugs;
import com.untamedears.humbug.annotations.ConfigOption;
import com.untamedears.humbug.annotations.OptType;
public class Humbug extends JavaPlugin implements Listener {
public static void severe(String message) {
log_.severe("[Humbug] " + message);
}
public static void warning(String message) {
log_.warning("[Humbug] " + message);
}
public static void info(String message) {
log_.info("[Humbug] " + message);
}
public static void debug(String message) {
if (config_.getDebug()) {
log_.info("[Humbug] " + message);
}
}
public static Humbug getPlugin() {
return global_instance_;
}
private static final Logger log_ = Logger.getLogger("Humbug");
private static Humbug global_instance_ = null;
private static Config config_ = null;
private static int max_golden_apple_stack_ = 1;
static {
max_golden_apple_stack_ = Material.GOLDEN_APPLE.getMaxStackSize();
if (max_golden_apple_stack_ > 64) {
max_golden_apple_stack_ = 64;
}
}
private Random prng_ = new Random();
private CombatTagManager combatTag_ = new CombatTagManager();
public Humbug() {}
// Reduce registered PlayerInteractEvent count. onPlayerInteractAll handles
// cancelled events.
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
onAnvilOrEnderChestUse(event);
if (!event.isCancelled()) {
onCauldronInteract(event);
}
if (!event.isCancelled()) {
onRecordInJukebox(event);
}
if (!event.isCancelled()) {
onEnchantingTableUse(event);
}
if (!event.isCancelled()) {
onChangingSpawners(event);
}
}
@BahHumbug(opt="changing_spawners_with_eggs", def="true")
public void onChangingSpawners(PlayerInteractEvent event)
{
if (!config_.get("changing_spawners_with_eggs").getBool()) {
return;
}
if ((event.getClickedBlock() != null) && (event.getItem() != null) &&
(event.getClickedBlock().getType()==Material.MOB_SPAWNER) && (event.getItem().getType() == Material.MONSTER_EGG)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST) // ignoreCancelled=false
public void onPlayerInteractAll(PlayerInteractEvent event) {
onPlayerEatGoldenApple(event);
throttlePearlTeleport(event);
}
// Stops people from dying sheep
@BahHumbug(opt="allow_dye_sheep", def="true")
@EventHandler
public void onDyeWool(SheepDyeWoolEvent event) {
if (!config_.get("allow_dye_sheep").getBool()) {
event.setCancelled(true);
}
}
// Configurable bow buff
@EventHandler
public void onEntityShootBowEventAlreadyIntializedSoIMadeThisUniqueName(EntityShootBowEvent event) {
Integer power = event.getBow().getEnchantmentLevel(Enchantment.ARROW_DAMAGE);
MetadataValue metadata = new FixedMetadataValue(this, power);
event.getProjectile().setMetadata("power", metadata);
}
@BahHumbug(opt="bow_buff", type=OptType.Double, def="1.000000")
@EventHandler
public void onArrowHitEntity(EntityDamageByEntityEvent event) {
Double multiplier = config_.get("bow_buff").getDouble();
if(multiplier <= 1.000001 && multiplier >= 0.999999) {
return;
}
if (event.getEntity() instanceof LivingEntity) {
Entity damager = event.getDamager();
if (damager instanceof Arrow) {
Arrow arrow = (Arrow) event.getDamager();
Double damage = event.getDamage() * config_.get("bow_buff").getDouble();
Integer power = 0;
if(arrow.hasMetadata("power")) {
power = arrow.getMetadata("power").get(0).asInt();
}
damage *= Math.pow(1.25, power - 5); // f(x) = 1.25^(x - 5)
event.setDamage(damage);
}
}
}
// Fixes Teleporting through walls and doors
// ** and **
// Ender Pearl Teleportation disabling
// ** and **
// Ender pearl cooldown timer
private class PearlTeleportInfo {
public long last_teleport;
public long last_notification;
}
private Map<String, PearlTeleportInfo> pearl_teleport_info_
= new TreeMap<String, PearlTeleportInfo>();
private final static int PEARL_THROTTLE_WINDOW = 10000; // 10 sec
private final static int PEARL_NOTIFICATION_WINDOW = 1000; // 1 sec
// EventHandler registered in onPlayerInteractAll
@BahHumbug(opt="ender_pearl_teleportation_throttled", def="true")
public void throttlePearlTeleport(PlayerInteractEvent event) {
if (!config_.get("ender_pearl_teleportation_throttled").getBool()) {
return;
}
if (event.getItem() == null || !event.getItem().getType().equals(Material.ENDER_PEARL)) {
return;
}
final Action action = event.getAction();
if (action != Action.RIGHT_CLICK_AIR && action != Action.RIGHT_CLICK_BLOCK) {
return;
}
final Block clickedBlock = event.getClickedBlock();
BlockState clickedState = null;
Material clickedMaterial = null;
if (clickedBlock != null) {
clickedState = clickedBlock.getState();
clickedMaterial = clickedState.getType();
}
if (clickedState != null && (
clickedState instanceof InventoryHolder
|| clickedMaterial.equals(Material.ANVIL)
|| clickedMaterial.equals(Material.ENCHANTMENT_TABLE)
|| clickedMaterial.equals(Material.ENDER_CHEST)
|| clickedMaterial.equals(Material.WORKBENCH))) {
// Prevent Combat Tag/Pearl cooldown on inventory access
return;
}
final long current_time = System.currentTimeMillis();
final Player player = event.getPlayer();
final String player_name = player.getName();
PearlTeleportInfo teleport_info = pearl_teleport_info_.get(player_name);
long time_diff = 0;
if (teleport_info == null) {
// New pearl thrown outside of throttle window
teleport_info = new PearlTeleportInfo();
teleport_info.last_teleport = current_time;
teleport_info.last_notification =
current_time - (PEARL_NOTIFICATION_WINDOW + 100); // Force notify
combatTag_.tagPlayer(player);
} else {
time_diff = current_time - teleport_info.last_teleport;
if (PEARL_THROTTLE_WINDOW > time_diff) {
// Pearl throw throttled
event.setCancelled(true);
} else {
// New pearl thrown outside of throttle window
combatTag_.tagPlayer(player);
teleport_info.last_teleport = current_time;
teleport_info.last_notification =
current_time - (PEARL_NOTIFICATION_WINDOW + 100); // Force notify
time_diff = 0;
}
}
final long notify_diff = current_time - teleport_info.last_notification;
if (notify_diff > PEARL_NOTIFICATION_WINDOW) {
teleport_info.last_notification = current_time;
Integer tagCooldown = combatTag_.remainingSeconds(player);
if (tagCooldown != null) {
player.sendMessage(String.format(
"Pearl in %d seconds. Combat Tag in %d seconds.",
(PEARL_THROTTLE_WINDOW - time_diff + 500) / 1000,
tagCooldown));
} else {
player.sendMessage(String.format(
"Pearl Teleport Cooldown: %d seconds",
(PEARL_THROTTLE_WINDOW - time_diff + 500) / 1000));
}
}
pearl_teleport_info_.put(player_name, teleport_info);
return;
}
@BahHumbugs({
@BahHumbug(opt="ender_pearl_teleportation", def="true"),
@BahHumbug(opt="fix_teleport_glitch", def="true")
})
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onTeleport(PlayerTeleportEvent event) {
TeleportCause cause = event.getCause();
if (cause != TeleportCause.ENDER_PEARL) {
return;
} else if (!config_.get("ender_pearl_teleportation").getBool()) {
event.setCancelled(true);
return;
}
if (!config_.get("fix_teleport_glitch").getBool()) {
return;
}
Location to = event.getTo();
World world = to.getWorld();
// From and To are feet positions. Check and make sure we can teleport to a location with air
// above the To location.
Block toBlock = world.getBlockAt(to);
Block aboveBlock = world.getBlockAt(to.getBlockX(), to.getBlockY()+1, to.getBlockZ());
Block belowBlock = world.getBlockAt(to.getBlockX(), to.getBlockY()-1, to.getBlockZ());
boolean lowerBlockBypass = false;
double height = 0.0;
switch( toBlock.getType() ) {
case CHEST: // Probably never will get hit directly
case ENDER_CHEST: // Probably never will get hit directly
height = 0.875;
break;
case STEP:
lowerBlockBypass = true;
height = 0.5;
break;
case WATER_LILY:
height = 0.016;
break;
case ENCHANTMENT_TABLE:
lowerBlockBypass = true;
height = 0.75;
break;
case BED:
case BED_BLOCK:
// This one is tricky, since even with a height offset of 2.5, it still glitches.
//lowerBlockBypass = true;
//height = 0.563;
// Disabling teleporting on top of beds for now by leaving lowerBlockBypass false.
break;
case FLOWER_POT:
case FLOWER_POT_ITEM:
height = 0.375;
break;
case SKULL: // Probably never will get hit directly
height = 0.5;
break;
default:
break;
}
// Check if the below block is difficult
// This is added because if you face downward directly on a gate, it will
// teleport your feet INTO the gate, thus bypassing the gate until you leave that block.
switch( belowBlock.getType() ) {
case FENCE:
case FENCE_GATE:
case NETHER_FENCE:
case COBBLE_WALL:
height = 0.5;
break;
default:
break;
}
boolean upperBlockBypass = false;
if( height >= 0.5 ) {
Block aboveHeadBlock = world.getBlockAt(aboveBlock.getX(), aboveBlock.getY()+1, aboveBlock.getZ());
if( false == aboveHeadBlock.getType().isSolid() ) {
height = 0.5;
} else {
upperBlockBypass = true; // Cancel this event. What's happening is the user is going to get stuck due to the height.
}
}
// Normalize teleport to the center of the block. Feet ON the ground, plz.
// Leave Yaw and Pitch alone
to.setX(Math.floor(to.getX()) + 0.5000);
to.setY(Math.floor(to.getY()) + height);
to.setZ(Math.floor(to.getZ()) + 0.5000);
if(aboveBlock.getType().isSolid() ||
(toBlock.getType().isSolid() && !lowerBlockBypass) ||
upperBlockBypass ) {
// One last check because I care about Top Nether. (someone build me a shrine up there)
boolean bypass = false;
if ((world.getEnvironment() == Environment.NETHER) &&
(to.getBlockY() > 124) && (to.getBlockY() < 129)) {
bypass = true;
}
if (!bypass) {
event.setCancelled(true);
}
}
}
// Villager Trading
@BahHumbug(opt="villager_trades")
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
if (config_.get("villager_trades").getBool()) {
return;
}
Entity npc = event.getRightClicked();
if (npc == null) {
return;
}
if (npc.getType() == EntityType.VILLAGER) {
event.setCancelled(true);
}
}
// Anvil and Ender Chest usage
// EventHandler registered in onPlayerInteract
@BahHumbugs({
@BahHumbug(opt="anvil"),
@BahHumbug(opt="ender_chest")
})
public void onAnvilOrEnderChestUse(PlayerInteractEvent event) {
if (config_.get("anvil").getBool() && config_.get("ender_chest").getBool()) {
return;
}
Action action = event.getAction();
Material material = event.getClickedBlock().getType();
boolean anvil = !config_.get("anvil").getBool() &&
action == Action.RIGHT_CLICK_BLOCK &&
material.equals(Material.ANVIL);
boolean ender_chest = !config_.get("ender_chest").getBool() &&
action == Action.RIGHT_CLICK_BLOCK &&
material.equals(Material.ENDER_CHEST);
if (anvil || ender_chest) {
event.setCancelled(true);
}
}
@BahHumbug(opt="enchanting_table", def = "false")
public void onEnchantingTableUse(PlayerInteractEvent event) {
if(!config_.get("enchanting_table").getBool()) {
return;
}
Action action = event.getAction();
Material material = event.getClickedBlock().getType();
boolean enchanting_table = action == Action.RIGHT_CLICK_BLOCK &&
material.equals(Material.ENCHANTMENT_TABLE);
if(enchanting_table) {
event.setCancelled(true);
}
}
@BahHumbug(opt="ender_chests_placeable", def="true")
@EventHandler(ignoreCancelled=true)
public void onEnderChestPlace(BlockPlaceEvent e) {
Material material = e.getBlock().getType();
if (!config_.get("ender_chests_placeable").getBool() && material == Material.ENDER_CHEST) {
e.setCancelled(true);
}
}
public void EmptyEnderChest(HumanEntity human) {
if (config_.get("ender_backpacks").getBool()) {
dropInventory(human.getLocation(), human.getEnderChest());
}
}
public void dropInventory(Location loc, Inventory inv) {
final World world = loc.getWorld();
final int end = inv.getSize();
for (int i = 0; i < end; ++i) {
try {
final ItemStack item = inv.getItem(i);
if (item != null) {
world.dropItemNaturally(loc, item);
inv.clear(i);
}
} catch (Exception ex) {}
}
}
// Unlimited Cauldron water
// EventHandler registered in onPlayerInteract
@BahHumbug(opt="unlimitedcauldron")
public void onCauldronInteract(PlayerInteractEvent e) {
if (!config_.get("unlimitedcauldron").getBool()) {
return;
}
// block water going down on cauldrons
if(e.getClickedBlock().getType() == Material.CAULDRON && e.getMaterial() == Material.GLASS_BOTTLE && e.getAction() == Action.RIGHT_CLICK_BLOCK)
{
Block block = e.getClickedBlock();
if(block.getData() > 0)
{
block.setData((byte)(block.getData()+1));
}
}
}
// Quartz from Gravel
@BahHumbug(opt="quartz_gravel_percentage", type=OptType.Int)
@EventHandler(ignoreCancelled=true, priority = EventPriority.HIGHEST)
public void onGravelBreak(BlockBreakEvent e) {
if(e.getBlock().getType() != Material.GRAVEL
|| config_.get("quartz_gravel_percentage").getInt() <= 0) {
return;
}
if(prng_.nextInt(100) < config_.get("quartz_gravel_percentage").getInt())
{
e.setCancelled(true);
e.getBlock().setType(Material.AIR);
e.getBlock().getWorld().dropItemNaturally(e.getBlock().getLocation(), new ItemStack(Material.QUARTZ, 1));
}
}
// Portals
@BahHumbug(opt="portalcreate", def="true")
@EventHandler(ignoreCancelled=true)
public void onPortalCreate(PortalCreateEvent e) {
if (!config_.get("portalcreate").getBool()) {
e.setCancelled(true);
}
}
@EventHandler(ignoreCancelled=true)
public void onEntityPortalCreate(EntityCreatePortalEvent e) {
if (!config_.get("portalcreate").getBool()) {
e.setCancelled(true);
}
}
// EnderDragon
@BahHumbug(opt="enderdragon", def="true")
@EventHandler(ignoreCancelled=true)
public void onDragonSpawn(CreatureSpawnEvent e) {
if (e.getEntityType() == EntityType.ENDER_DRAGON
&& !config_.get("enderdragon").getBool()) {
e.setCancelled(true);
}
}
// Join/Quit/Kick messages
@BahHumbug(opt="joinquitkick", def="true")
@EventHandler(priority=EventPriority.HIGHEST)
public void onJoin(PlayerJoinEvent e) {
if (!config_.get("joinquitkick").getBool()) {
e.setJoinMessage(null);
}
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onQuit(PlayerQuitEvent e) {
EmptyEnderChest(e.getPlayer());
if (!config_.get("joinquitkick").getBool()) {
e.setQuitMessage(null);
}
}
@EventHandler(priority=EventPriority.HIGHEST)
public void onKick(PlayerKickEvent e) {
EmptyEnderChest(e.getPlayer());
if (!config_.get("joinquitkick").getBool()) {
e.setLeaveMessage(null);
}
}
// Death Messages
@BahHumbugs({
@BahHumbug(opt="deathannounce", def="true"),
@BahHumbug(opt="deathlog"),
@BahHumbug(opt="deathpersonal"),
@BahHumbug(opt="deathred"),
@BahHumbug(opt="ender_backpacks")
})
@EventHandler(priority=EventPriority.HIGHEST)
public void onDeath(PlayerDeathEvent e) {
final boolean logMsg = config_.get("deathlog").getBool();
final boolean sendPersonal = config_.get("deathpersonal").getBool();
final Player player = e.getEntity();
EmptyEnderChest(player);
if (logMsg || sendPersonal) {
Location location = player.getLocation();
String msg = String.format(
"%s ([%s] %d, %d, %d)", e.getDeathMessage(), location.getWorld().getName(),
location.getBlockX(), location.getBlockY(), location.getBlockZ());
if (logMsg) {
info(msg);
}
if (sendPersonal) {
e.getEntity().sendMessage(ChatColor.RED + msg);
}
}
if (!config_.get("deathannounce").getBool()) {
e.setDeathMessage(null);
} else if (config_.get("deathred").getBool()) {
e.setDeathMessage(ChatColor.RED + e.getDeathMessage());
}
}
// Endermen Griefing
@BahHumbug(opt="endergrief", def="true")
@EventHandler(ignoreCancelled=true)
public void onEndermanGrief(EntityChangeBlockEvent e)
{
if (!config_.get("endergrief").getBool() && e.getEntity() instanceof Enderman) {
e.setCancelled(true);
}
}
// Wither Insta-breaking and Explosions
@BahHumbug(opt="wither_insta_break")
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEntityChangeBlock(EntityChangeBlockEvent event) {
if (config_.get("wither_insta_break").getBool()) {
return;
}
Entity npc = event.getEntity();
if (npc == null) {
return;
}
EntityType npc_type = npc.getType();
if (npc_type.equals(EntityType.WITHER)) {
event.setCancelled(true);
}
}
@BahHumbug(opt="wither_explosions")
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEntityExplode(EntityExplodeEvent event) {
if (config_.get("wither_explosions").getBool()) {
return;
}
Entity npc = event.getEntity();
if (npc == null) {
return;
}
EntityType npc_type = npc.getType();
if ((npc_type.equals(EntityType.WITHER) ||
npc_type.equals(EntityType.WITHER_SKULL))) {
event.blockList().clear();
}
}
@BahHumbug(opt="wither", def="true")
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onWitherSpawn(CreatureSpawnEvent event) {
if (config_.get("wither").getBool()) {
return;
}
if (!event.getEntityType().equals(EntityType.WITHER)) {
return;
}
event.setCancelled(true);
}
// Prevent specified items from dropping off mobs
public void removeItemDrops(EntityDeathEvent event) {
if (!config_.doRemoveItemDrops()) {
return;
}
if (event.getEntity() instanceof Player) {
return;
}
Set<Integer> remove_ids = config_.getRemoveItemDrops();
List<ItemStack> drops = event.getDrops();
ItemStack item;
int i = drops.size() - 1;
while (i >= 0) {
item = drops.get(i);
if (remove_ids.contains(item.getTypeId())) {
drops.remove(i);
}
--i;
}
}
// Spawn more Wither Skeletons and Ghasts
@BahHumbugs ({
@BahHumbug(opt="extra_ghast_spawn_rate", type=OptType.Int),
@BahHumbug(opt="extra_wither_skele_spawn_rate", type=OptType.Int),
@BahHumbug(opt="portal_extra_ghast_spawn_rate", type=OptType.Int),
@BahHumbug(opt="portal_extra_wither_skele_spawn_rate", type=OptType.Int),
@BahHumbug(opt="portal_pig_spawn_multiplier", type=OptType.Int)
})
@EventHandler(priority = EventPriority.HIGH, ignoreCancelled=true)
public void spawnMoreHellMonsters(CreatureSpawnEvent e) {
final Location loc = e.getLocation();
final World world = loc.getWorld();
boolean portalSpawn = false;
final int blockType = world.getBlockTypeIdAt(loc);
if (blockType == 90 || blockType == 49) {
// >= because we are preventing instead of spawning
if(prng_.nextInt(1000000) >= config_.get("portal_pig_spawn_multiplier").getInt()) {
e.setCancelled(true);
return;
}
portalSpawn = true;
}
if (config_.get("extra_wither_skele_spawn_rate").getInt() <= 0
&& config_.get("extra_ghast_spawn_rate").getInt() <= 0) {
return;
}
if (e.getEntityType() == EntityType.PIG_ZOMBIE) {
int adjustedwither;
int adjustedghast;
if (portalSpawn) {
adjustedwither = config_.get("portal_extra_wither_skele_spawn_rate").getInt();
adjustedghast = config_.get("portal_extra_ghast_spawn_rate").getInt();
} else {
adjustedwither = config_.get("extra_wither_skele_spawn_rate").getInt();
adjustedghast = config_.get("extra_ghast_spawn_rate").getInt();
}
if(prng_.nextInt(1000000) < adjustedwither) {
e.setCancelled(true);
world.spawnEntity(loc, EntityType.SKELETON);
} else if(prng_.nextInt(1000000) < adjustedghast) {
e.setCancelled(true);
int x = loc.getBlockX();
int z = loc.getBlockZ();
List<Integer> heights = new ArrayList<Integer>(16);
int lastBlockHeight = 2;
int emptyCount = 0;
int maxHeight = world.getMaxHeight();
for (int y = 2; y < maxHeight; ++y) {
Block block = world.getBlockAt(x, y, z);
if (block.isEmpty()) {
++emptyCount;
if (emptyCount == 11) {
heights.add(lastBlockHeight + 2);
}
} else {
lastBlockHeight = y;
emptyCount = 0;
}
}
if (heights.size() <= 0) {
return;
}
loc.setY(heights.get(prng_.nextInt(heights.size())));
world.spawnEntity(loc, EntityType.GHAST);
}
} else if (e.getEntityType() == EntityType.SKELETON
&& e.getSpawnReason() == CreatureSpawnEvent.SpawnReason.CUSTOM) {
Entity entity = e.getEntity();
if (entity instanceof Skeleton) {
Skeleton skele = (Skeleton)entity;
skele.setSkeletonType(SkeletonType.WITHER);
EntityEquipment entity_equip = skele.getEquipment();
entity_equip.setItemInHand(new ItemStack(Material.STONE_SWORD));
entity_equip.setItemInHandDropChance(0.0F);
}
}
}
// Wither Skull drop rate
public static final int skull_id_ = Material.SKULL_ITEM.getId();
public static final byte wither_skull_data_ = 1;
@BahHumbug(opt="wither_skull_drop_rate", type=OptType.Int)
public void adjustWitherSkulls(EntityDeathEvent event) {
Entity entity = event.getEntity();
if (!(entity instanceof Skeleton)) {
return;
}
int rate = config_.get("wither_skull_drop_rate").getInt();
if (rate < 0 || rate > 1000000) {
return;
}
Skeleton skele = (Skeleton)entity;
if (skele.getSkeletonType() != SkeletonType.WITHER) {
return;
}
List<ItemStack> drops = event.getDrops();
ItemStack item;
int i = drops.size() - 1;
while (i >= 0) {
item = drops.get(i);
if (item.getTypeId() == skull_id_
&& item.getData().getData() == wither_skull_data_) {
drops.remove(i);
}
--i;
}
if (rate - prng_.nextInt(1000000) <= 0) {
return;
}
item = new ItemStack(Material.SKULL_ITEM);
item.setAmount(1);
item.setDurability((short)wither_skull_data_);
drops.add(item);
}
// Fix a few issues with pearls, specifically pearls in unloaded chunks and slime blocks.
@BahHumbug(opt="remove_pearls_chunks", type=OptType.Bool, def = "true")
@EventHandler()
public void onChunkUnloadEvent(ChunkUnloadEvent event){
Entity[] entities = event.getChunk().getEntities();
for (Entity ent: entities)
if (ent.getType() == EntityType.ENDER_PEARL)
ent.remove();
}
private void registerTimerForPearlCheck(){
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new Runnable(){
@Override
public void run() {
for (Entity ent: pearlTime.keySet()){
if (pearlTime.get(ent).booleanValue()){
ent.remove();
}
else
pearlTime.put(ent, true);
}
}
}, 100, 200);
}
private Map<Entity, Boolean> pearlTime = new HashMap<Entity, Boolean>();
public void onPearlLastingTooLong(EntityInteractEvent event){
if (event.getEntityType() != EntityType.ENDER_PEARL)
return;
Entity ent = event.getEntity();
pearlTime.put(ent, false);
}
// Generic mob drop rate adjustment
@BahHumbug(opt="disable_xp_orbs", type=OptType.Bool, def = "true")
public void adjustMobItemDrops(EntityDeathEvent event){
Entity mob = event.getEntity();
if (mob instanceof Player){
return;
}
// Try specific multiplier, if that doesn't exist use generic
EntityType mob_type = mob.getType();
int multiplier = config_.getLootMultiplier(mob_type.toString());
if (multiplier < 0) {
multiplier = config_.getLootMultiplier("generic");
}
//set entity death xp to zero so they don't drop orbs
if(config_.get("disable_xp_orbs").getBool()){
event.setDroppedExp(0);
}
//if a dropped item was in the mob's inventory, drop only one, otherwise drop the amount * the multiplier
LivingEntity liveMob = (LivingEntity) mob;
EntityEquipment mobEquipment = liveMob.getEquipment();
ItemStack[] eeItem = mobEquipment.getArmorContents();
for (ItemStack item : event.getDrops()) {
boolean armor = false;
boolean hand = false;
for(ItemStack i : eeItem){
if(i.isSimilar(item)){
armor = true;
item.setAmount(1);
}
}
if(item.isSimilar(mobEquipment.getItemInHand())){
hand = true;
item.setAmount(1);
}
if(!hand && !armor){
int amount = item.getAmount() * multiplier;
item.setAmount(amount);
}
}
}
@EventHandler(priority = EventPriority.LOW, ignoreCancelled = true)
public void onEntityDeathEvent(EntityDeathEvent event) {
removeItemDrops(event);
adjustWitherSkulls(event);
adjustMobItemDrops(event);
}
// Enchanted Golden Apple
public boolean isEnchantedGoldenApple(ItemStack item) {
// Golden Apples are GOLDEN_APPLE with 0 durability
// Enchanted Golden Apples are GOLDEN_APPLE with 1 durability
if (item == null) {
return false;
}
if (item.getDurability() != 1) {
return false;
}
Material material = item.getType();
return material.equals(Material.GOLDEN_APPLE);
}
public boolean isMossyStoneBrick(ItemStack item) {
// Mossy stone bricks are stone bricks with 1 durability
if (item == null) {
return false;
}
if (item.getDurability() != 1) {
return false;
}
Material material = item.getType();
return material.equals(Material.SMOOTH_BRICK);
}
public boolean isCrackedStoneBrick(ItemStack item) {
// Cracked stone bricks are stone bricks with 2 durability
if (item == null) {
return false;
}
if (item.getDurability() != 2) {
return false;
}
Material material = item.getType();
return material.equals(Material.SMOOTH_BRICK);
}
public boolean isChiseledStoneBrick(ItemStack item) {
// Chiseled stone bricks are stone bricks with 3 durability
if (item == null) {
return false;
}
if (item.getDurability() != 3) {
return false;
}
Material material = item.getType();
return material.equals(Material.SMOOTH_BRICK);
}
public void replaceEnchantedGoldenApple(
String player_name, ItemStack item, int inventory_max_stack_size) {
if (!isEnchantedGoldenApple(item)) {
return;
}
int stack_size = max_golden_apple_stack_;
if (inventory_max_stack_size < max_golden_apple_stack_) {
stack_size = inventory_max_stack_size;
}
info(String.format(
"Replaced %d Enchanted with %d Normal Golden Apples for %s",
item.getAmount(), stack_size, player_name));
item.setDurability((short)0);
item.setAmount(stack_size);
}
@BahHumbug({
@BahHumbug(opt="ench_gold_app_craftable", def = "false"),
@BahHumbug(opt="moss_stone_craftable", def = "false"),
@BahHumbug(opt="cracked_stone_craftable", def = "false")
@BahHumbug(opt="moss_brick_craftable", def = "false"),
@BahHumbug(opt="chiseled_stone_craftable", def = "false")
})
public void removeRecipies() {
if (config_.get("ench_gold_app_craftable").getBool()&&config_.get("moss_stone_craftable").getBool()&&config_.get("cracked_stone_craftable").getBool()&&config_.get("moss_brick_craftable").getBool()&&config_.get("chiseled_stone_craftable").getBool()) {
return;
}
Iterator<Recipe> it = getServer().recipeIterator();
while (it.hasNext()) {
Recipe recipe = it.next();
ItemStack resulting_item = recipe.getResult();
if (!config_.get("ench_gold_app_craftable").getBool() &&
isEnchantedGoldenApple(resulting_item)) {
it.remove();
info("Enchanted Golden Apple Recipe disabled");
}else
if (!config_.get("moss_stone_craftable").getBool() &&
resulting_item.getType().equals(Material.MOSSY_COBBLESTONE)) {
it.remove();
info("Moss Stone Recipe disabled");
}else
if (!config_.get("cracked_stone_craftable").getBool() &&
isCrackedStoneBrick(resulting_item)) {
it.remove();
info("Cracked Stone Recipe disabled");
}
if (!config_.get("moss_brick_craftable").getBool() &&
isMossyStoneBrick(resulting_item)) {
it.remove();
info("Cracked Stone Recipe disabled");
}
if (!config_.get("chiseled_stone_craftable").getBool() &&
isChiseledStoneBrick(resulting_item)) {
it.remove();
info("Cracked Stone Recipe disabled");
}
}
}
// EventHandler registered in onPlayerInteractAll
@BahHumbug(opt="ench_gold_app_edible")
public void onPlayerEatGoldenApple(PlayerInteractEvent event) {
// The event when eating is cancelled before even LOWEST fires when the
// player clicks on AIR.
if (config_.get("ench_gold_app_edible").getBool()) {
return;
}
Player player = event.getPlayer();
Inventory inventory = player.getInventory();
ItemStack item = event.getItem();
replaceEnchantedGoldenApple(
player.getName(), item, inventory.getMaxStackSize());
}
// Fix entities going through portals
// This needs to be removed when updated to citadel 3.0
@BahHumbug(opt="disable_entities_portal", type = OptType.Bool, def = "true")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void entityPortalEvent(EntityPortalEvent event){
event.setCancelled(config_.get("disable_entities_portal").getBool());
}
// Enchanted Book
public boolean isNormalBook(ItemStack item) {
if (item == null) {
return false;
}
Material material = item.getType();
return material.equals(Material.BOOK);
}
@BahHumbug(opt="ench_book_craftable")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onPrepareItemEnchantEvent(PrepareItemEnchantEvent event) {
if (config_.get("ench_book_craftable").getBool()) {
return;
}
ItemStack item = event.getItem();
if (isNormalBook(item)) {
event.setCancelled(true);
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onEnchantItemEvent(EnchantItemEvent event) {
if (config_.get("ench_book_craftable").getBool()) {
return;
}
ItemStack item = event.getItem();
if (isNormalBook(item)) {
event.setCancelled(true);
Player player = event.getEnchanter();
warning(
"Prevented book enchant. This should not trigger. Watch player " +
player.getName());
}
}
// Stop Cobble generation from lava+water
private static final BlockFace[] faces_ = new BlockFace[] {
BlockFace.NORTH,
BlockFace.SOUTH,
BlockFace.EAST,
BlockFace.WEST,
BlockFace.UP,
BlockFace.DOWN
};
private BlockFace WaterAdjacentLava(Block lava_block) {
for (BlockFace face : faces_) {
Block block = lava_block.getRelative(face);
Material material = block.getType();
if (material.equals(Material.WATER) ||
material.equals(Material.STATIONARY_WATER)) {
return face;
}
}
return BlockFace.SELF;
}
public void ConvertLava(final Block block) {
int data = (int)block.getData();
if (data == 0) {
return;
}
Material material = block.getType();
if (!material.equals(Material.LAVA) &&
!material.equals(Material.STATIONARY_LAVA)) {
return;
}
if (isLavaSourceNear(block, 3)) {
return;
}
BlockFace face = WaterAdjacentLava(block);
if (face == BlockFace.SELF) {
return;
}
Bukkit.getScheduler().runTask(this, new Runnable() {
@Override
public void run() {
block.setType(Material.AIR);
}
});
}
public boolean isLavaSourceNear(Block block, int ttl) {
int data = (int)block.getData();
if (data == 0) {
Material material = block.getType();
if (material.equals(Material.LAVA) ||
material.equals(Material.STATIONARY_LAVA)) {
return true;
}
}
if (ttl <= 0) {
return false;
}
for (BlockFace face : faces_) {
Block child = block.getRelative(face);
if (isLavaSourceNear(child, ttl - 1)) {
return true;
}
}
return false;
}
public void LavaAreaCheck(Block block, int ttl) {
ConvertLava(block);
if (ttl <= 0) {
return;
}
for (BlockFace face : faces_) {
Block child = block.getRelative(face);
LavaAreaCheck(child, ttl - 1);
}
}
@BahHumbugs ({
@BahHumbug(opt="cobble_from_lava"),
@BahHumbug(opt="cobble_from_lava_scan_radius", type=OptType.Int, def="0")
})
@EventHandler(priority = EventPriority.LOWEST)
public void onBlockPhysicsEvent(BlockPhysicsEvent event) {
if (config_.get("cobble_from_lava").getBool()) {
return;
}
Block block = event.getBlock();
LavaAreaCheck(block, config_.get("cobble_from_lava_scan_radius").getInt());
}
// Counteract 1.4.6 protection enchant nerf
@BahHumbug(opt="scale_protection_enchant", def="true")
@EventHandler(priority = EventPriority.LOWEST) // ignoreCancelled=false
public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) {
if (!config_.get("scale_protection_enchant").getBool()) {
return;
}
double damage = event.getDamage();
if (damage <= 0.0000001D) {
return;
}
DamageCause cause = event.getCause();
if (!cause.equals(DamageCause.ENTITY_ATTACK) &&
!cause.equals(DamageCause.PROJECTILE)) {
return;
}
Entity entity = event.getEntity();
if (!(entity instanceof Player)) {
return;
}
Player defender = (Player)entity;
PlayerInventory inventory = defender.getInventory();
int enchant_level = 0;
for (ItemStack armor : inventory.getArmorContents()) {
enchant_level += armor.getEnchantmentLevel(Enchantment.PROTECTION_ENVIRONMENTAL);
}
int damage_adjustment = 0;
if (enchant_level >= 3 && enchant_level <= 6) {
// 0 to 2
damage_adjustment = prng_.nextInt(3);
} else if (enchant_level >= 7 && enchant_level <= 10) {
// 0 to 3
damage_adjustment = prng_.nextInt(4);
} else if (enchant_level >= 11 && enchant_level <= 14) {
// 1 to 4
damage_adjustment = prng_.nextInt(4) + 1;
} else if (enchant_level >= 15) {
// 2 to 4
damage_adjustment = prng_.nextInt(3) + 2;
}
damage = Math.max(damage - (double)damage_adjustment, 0.0D);
event.setDamage(damage);
}
@BahHumbug(opt="player_max_health", type=OptType.Int, def="20")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onPlayerJoinEvent(PlayerJoinEvent event) {
Player player = event.getPlayer();
player.setMaxHealth((double)config_.get("player_max_health").getInt());
}
// Fix dupe bug with chests and other containers
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void blockExplodeEvent(EntityExplodeEvent event) {
List<HumanEntity> humans = new ArrayList<HumanEntity>();
for (Block block: event.blockList()) {
if (block.getState() instanceof InventoryHolder) {
InventoryHolder holder = (InventoryHolder) block.getState();
for (HumanEntity ent: holder.getInventory().getViewers()) {
humans.add(ent);
}
}
}
for (HumanEntity human: humans) {
human.closeInventory();
}
}
// Prevent entity dup bug
@BahHumbug(opt="fix_rail_dup_bug", def="true")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onPistonPushRail(BlockPistonExtendEvent e) {
if (!config_.get("fix_rail_dup_bug").getBool()) {
return;
}
for (Block b : e.getBlocks()) {
Material t = b.getType();
if (t == Material.RAILS ||
t == Material.POWERED_RAIL ||
t == Material.DETECTOR_RAIL) {
e.setCancelled(true);
return;
}
}
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onRailPlace(BlockPlaceEvent e) {
if (!config_.get("fix_rail_dup_bug").getBool()) {
return;
}
Block b = e.getBlock();
Material t = b.getType();
if (t == Material.RAILS ||
t == Material.POWERED_RAIL ||
t == Material.DETECTOR_RAIL) {
for (BlockFace face : faces_) {
t = b.getRelative(face).getType();
if (t == Material.PISTON_STICKY_BASE ||
t == Material.PISTON_EXTENSION ||
t == Material.PISTON_MOVING_PIECE ||
t == Material.PISTON_BASE) {
e.setCancelled(true);
return;
}
}
}
}
// Combat Tag players on server join
@BahHumbug(opt="tag_on_join", def="true")
@EventHandler
public void tagOnJoin(PlayerJoinEvent event){
if(!config_.get("tag_on_join").getBool()) {
return;
}
// Delay two ticks to tag after secure login has been denied.
// This opens a 1 tick window for a cheater to login and grab
// server info, which should be detectable and bannable.
final Player loginPlayer = event.getPlayer();
Bukkit.getScheduler().runTaskLater(this, new Runnable() {
@Override
public void run() {
combatTag_.tagPlayer(loginPlayer.getName());
loginPlayer.sendMessage("You have been Combat Tagged on Login");
}
}, 2L);
}
// Give introduction book to n00bs
private Set<String> playersWithN00bBooks_ = new TreeSet<String>();
@BahHumbug(opt="drop_newbie_book", def="true")
@EventHandler(priority=EventPriority.HIGHEST)
public void onPlayerDeathBookDrop(PlayerDeathEvent e) {
if (!config_.get("drop_newbie_book").getBool()) {
return;
}
final String playerName = e.getEntity().getName();
List<ItemStack> dropList = e.getDrops();
for (int i = 0; i < dropList.size(); ++i) {
final ItemStack item = dropList.get(i);
if (item.getType().equals(Material.WRITTEN_BOOK)) {
final BookMeta bookMeta = (BookMeta)item.getItemMeta();
if (bookMeta.getTitle().equals(config_.getTitle())) {
playersWithN00bBooks_.add(playerName);
dropList.remove(i);
return;
}
}
}
playersWithN00bBooks_.remove(playerName);
}
@EventHandler
public void onGiveBookOnRespawn(PlayerRespawnEvent event) {
if (!config_.get("drop_newbie_book").getBool()) {
return;
}
final Player player = event.getPlayer();
final String playerName = player.getName();
if (!playersWithN00bBooks_.contains(playerName)) {
return;
}
playersWithN00bBooks_.remove(playerName);
giveN00bBook(player);
}
@EventHandler
public void onGiveBookOnJoin(PlayerJoinEvent event) {
if (!config_.get("drop_newbie_book").getBool()) {
return;
}
final Player player = event.getPlayer();
final String playerName = player.getName();
if (player.hasPlayedBefore() && !playersWithN00bBooks_.contains(playerName)) {
return;
}
playersWithN00bBooks_.remove(playerName);
giveN00bBook(player);
}
public void giveN00bBook(Player player) {
Inventory inv = player.getInventory();
inv.addItem(createN00bBook());
}
public ItemStack createN00bBook() {
ItemStack book = new ItemStack(Material.WRITTEN_BOOK);
BookMeta sbook = (BookMeta)book.getItemMeta();
sbook.setTitle(config_.getTitle());
sbook.setAuthor(config_.getAuthor());
sbook.setPages(config_.getPages());
book.setItemMeta(sbook);
return book;
}
public boolean checkForInventorySpace(Inventory inv, int emptySlots) {
int foundEmpty = 0;
final int end = inv.getSize();
for (int slot = 0; slot < end; ++slot) {
ItemStack item = inv.getItem(slot);
if (item == null) {
++foundEmpty;
} else if (item.getType().equals(Material.AIR)) {
++foundEmpty;
}
}
return foundEmpty >= emptySlots;
}
public void giveHolidayPackage(Player player) {
int count = 0;
Inventory inv = player.getInventory();
while (checkForInventorySpace(inv, 4)) {
inv.addItem(createHolidayBook());
inv.addItem(createFruitcake());
inv.addItem(createTurkey());
inv.addItem(createCoal());
++count;
}
info(String.format("%s generated %d packs of holiday cheer.",
player.getName(), count));
}
public ItemStack createHolidayBook() {
ItemStack book = new ItemStack(Material.WRITTEN_BOOK);
BookMeta sbook = (BookMeta)book.getItemMeta();
sbook.setTitle(config_.getHolidayTitle());
sbook.setAuthor(config_.getHolidayAuthor());
sbook.setPages(config_.getHolidayPages());
List<String> lore = new ArrayList<String>(1);
lore.add("December 25th, 2013");
sbook.setLore(lore);
book.setItemMeta(sbook);
return book;
}
public ItemStack createFruitcake() {
ItemStack cake = new ItemStack(Material.CAKE);
ItemMeta meta = cake.getItemMeta();
meta.setDisplayName("Fruitcake");
List<String> lore = new ArrayList<String>(1);
lore.add("Deliciously stale");
meta.setLore(lore);
cake.setItemMeta(meta);
return cake;
}
private String[] turkey_names_ = new String[] {
"Turkey",
"Turkey",
"Turkey",
"Turducken",
"Tofurkey",
"Cearc Frangach",
"Dinde",
"Kalkoen",
"Indeyka",
"Pollo d'India",
"Pelehu",
"Chilmyeonjo"
};
public ItemStack createTurkey() {
String turkey_name = turkey_names_[prng_.nextInt(turkey_names_.length)];
ItemStack turkey = new ItemStack(Material.COOKED_CHICKEN);
ItemMeta meta = turkey.getItemMeta();
meta.setDisplayName(turkey_name);
List<String> lore = new ArrayList<String>(1);
lore.add("Tastes like chicken");
meta.setLore(lore);
turkey.setItemMeta(meta);
return turkey;
}
public ItemStack createCoal() {
ItemStack coal = new ItemStack(Material.COAL);
ItemMeta meta = coal.getItemMeta();
List<String> lore = new ArrayList<String>(1);
lore.add("You've been naughty");
meta.setLore(lore);
coal.setItemMeta(meta);
return coal;
}
// Playing records in jukeboxen? Gone
// EventHandler registered in onPlayerInteract
@BahHumbug(opt="disallow_record_playing", def="true")
public void onRecordInJukebox(PlayerInteractEvent event) {
if (!config_.get("disallow_record_playing").getBool()) {
return;
}
Block cb = event.getClickedBlock();
if (cb == null || cb.getType() != Material.JUKEBOX) {
return;
}
ItemStack his = event.getItem();
if(his != null && his.getType().isRecord()) {
event.setCancelled(true);
}
}
// Water in the nether? Nope.
@BahHumbugs ({
@BahHumbug(opt="allow_water_in_nether"),
@BahHumbug(opt="indestructible_end_portals", def="true")
})
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onPlayerBucketEmptyEvent(PlayerBucketEmptyEvent e) {
if(!config_.get("allow_water_in_nether").getBool()) {
if( ( e.getBlockClicked().getBiome() == Biome.HELL )
&& ( e.getBucket() == Material.WATER_BUCKET ) ) {
e.setCancelled(true);
e.getItemStack().setType(Material.BUCKET);
e.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.WATER_BREATHING, 5, 1));
}
}
if (config_.get("indestructible_end_portals").getBool()) {
Block baseBlock = e.getBlockClicked();
BlockFace face = e.getBlockFace();
Block block = baseBlock.getRelative(face);
if (block.getType() == Material.ENDER_PORTAL) {
e.setCancelled(true);
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onBlockFromToEvent(BlockFromToEvent e) {
if(!config_.get("allow_water_in_nether").getBool()) {
if( e.getToBlock().getBiome() == Biome.HELL ) {
if( ( e.getBlock().getType() == Material.WATER )
|| ( e.getBlock().getType() == Material.STATIONARY_WATER ) ) {
e.setCancelled(true);
}
}
}
if (config_.get("indestructible_end_portals").getBool()) {
if (e.getToBlock().getType() == Material.ENDER_PORTAL) {
e.setCancelled(true);
}
}
if(!e.isCancelled() && config_.get("obsidian_generator").getBool()) {
generateObsidian(e);
}
}
// Generates obsidian like it did in 1.7.
// Note that this does not change anything in versions where obsidian generation exists.
@BahHumbug(opt="obsidian_generator", def="false")
public void generateObsidian(BlockFromToEvent event) {
if(!event.getBlock().getType().equals(Material.STATIONARY_LAVA)) {
return;
}
if(!event.getToBlock().getType().equals(Material.TRIPWIRE)) {
return;
}
Block string = event.getToBlock();
if(!(string.getRelative(BlockFace.NORTH).getType().equals(Material.STATIONARY_WATER)
|| string.getRelative(BlockFace.EAST).getType().equals(Material.STATIONARY_WATER)
|| string.getRelative(BlockFace.WEST).getType().equals(Material.STATIONARY_WATER)
|| string.getRelative(BlockFace.SOUTH).getType().equals(Material.STATIONARY_WATER))) {
return;
}
string.setType(Material.OBSIDIAN);
}
// Stops perculators
private Map<Chunk, Integer> waterChunks = new HashMap<Chunk, Integer>();
BukkitTask waterSchedule = null;
@BahHumbugs ({
@BahHumbug(opt="max_water_lava_height", def="100", type=OptType.Int),
@BahHumbug(opt="max_water_lava_amount", def = "400", type=OptType.Int),
@BahHumbug(opt="max_water_lava_timer", def = "1200", type=OptType.Int)
})
@EventHandler(priority = EventPriority.LOWEST)
public void stopLiquidMoving(BlockFromToEvent event){
try {
Block to = event.getToBlock();
Block from = event.getBlock();
if (to.getLocation().getBlockY() < config_.get("max_water_lava_height").getInt()) {
return;
}
Material mat = from.getType();
if (!(mat.equals(Material.WATER) || mat.equals(Material.STATIONARY_WATER) ||
mat.equals(Material.LAVA) || mat.equals(Material.STATIONARY_LAVA))) {
return;
}
Chunk c = to.getChunk();
if (!waterChunks.containsKey(c)){
waterChunks.put(c, 0);
}
Integer i = waterChunks.get(c);
i = i + 1;
waterChunks.put(c, i);
int amount = getWaterInNearbyChunks(c);
if (amount > config_.get("max_water_lava_amount").getInt()) {
event.setCancelled(true);
}
if (waterSchedule != null) {
return;
}
waterSchedule = Bukkit.getScheduler().runTaskLater(this, new Runnable(){
@Override
public void run() {
waterChunks.clear();
waterSchedule = null;
}
}, config_.get("max_water_lava_timer").getInt());
} catch (Exception e){
getLogger().log(Level.INFO, "Tried getting info from a chunk before it generated, skipping.");
return;
}
}
public int getWaterInNearbyChunks(Chunk chunk){
World world = chunk.getWorld();
Chunk[] chunks = {
world.getChunkAt(chunk.getX(), chunk.getZ()), world.getChunkAt(chunk.getX()-1, chunk.getZ()),
world.getChunkAt(chunk.getX(), chunk.getZ()-1), world.getChunkAt(chunk.getX()-1, chunk.getZ()-1),
world.getChunkAt(chunk.getX()+1, chunk.getZ()), world.getChunkAt(chunk.getX(), chunk.getZ()+1),
world.getChunkAt(chunk.getX()+1, chunk.getZ()+1), world.getChunkAt(chunk.getX()-1, chunk.getZ()+1),
world.getChunkAt(chunk.getX()+1, chunk.getZ()-1)
};
int count = 0;
for (Chunk c: chunks){
Integer amount = waterChunks.get(c);
if (amount == null)
continue;
count += amount;
}
return count;
}
// Changes Strength Potions, strength_multiplier 3 is roughly Pre-1.6 Level
@BahHumbugs ({
@BahHumbug(opt="nerf_strength", def="true"),
@BahHumbug(opt="strength_multiplier", type=OptType.Int, def="3")
})
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPlayerDamage(EntityDamageByEntityEvent event) {
if (!config_.get("nerf_strength").getBool()) {
return;
}
if (!(event.getDamager() instanceof Player)) {
return;
}
Player player = (Player)event.getDamager();
final int strengthMultiplier = config_.get("strength_multiplier").getInt();
if (player.hasPotionEffect(PotionEffectType.INCREASE_DAMAGE)) {
for (PotionEffect effect : player.getActivePotionEffects()) {
if (effect.getType().equals(PotionEffectType.INCREASE_DAMAGE)) {
final int potionLevel = effect.getAmplifier() + 1;
final double unbuffedDamage = event.getDamage() / (1.3 * potionLevel + 1);
final double newDamage = unbuffedDamage + (potionLevel * strengthMultiplier);
event.setDamage(newDamage);
break;
}
}
}
}
// Buffs health splash to pre-1.6 levels
@BahHumbug(opt="buff_health_pots", def="true")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPotionSplash(PotionSplashEvent event) {
if (!config_.get("buff_health_pots").getBool()) {
return;
}
for (PotionEffect effect : event.getEntity().getEffects()) {
if (!(effect.getType().getName().equalsIgnoreCase("heal"))) { // Splash potion of poison
return;
}
}
for (LivingEntity entity : event.getAffectedEntities()) {
if (entity instanceof Player) {
if(((Damageable)entity).getHealth() > 0d) {
final double newHealth = Math.min(
((Damageable)entity).getHealth() + 4.0D,
((Damageable)entity).getMaxHealth());
entity.setHealth(newHealth);
}
}
}
}
// Bow shots cause slow debuff
@BahHumbugs ({
@BahHumbug(opt="projectile_slow_chance", type=OptType.Int, def="30"),
@BahHumbug(opt="projectile_slow_ticks", type=OptType.Int, def="100")
})
@EventHandler
public void onEDBE(EntityDamageByEntityEvent event) {
int rate = config_.get("projectile_slow_chance").getInt();
if (rate <= 0 || rate > 100) {
return;
}
if (!(event.getEntity() instanceof Player)) {
return;
}
boolean damager_is_player_arrow = false;
int chance_scaling = 0;
Entity damager_entity = event.getDamager();
if (damager_entity != null) {
// public LivingEntity CraftArrow.getShooter()
// Playing this game to not have to take a hard dependency on
// craftbukkit internals.
try {
Class<?> damager_class = damager_entity.getClass();
if (damager_class.getName().endsWith(".CraftArrow")) {
Method getShooter = damager_class.getMethod("getShooter");
Object result = getShooter.invoke(damager_entity);
if (result instanceof Player) {
damager_is_player_arrow = true;
String player_name = ((Player)result).getName();
if (bow_level_.containsKey(player_name)) {
chance_scaling = bow_level_.get(player_name);
}
}
}
} catch(Exception ex) {}
}
if (!damager_is_player_arrow) {
return;
}
rate += chance_scaling * 5;
int percent = prng_.nextInt(100);
if (percent < rate){
int ticks = config_.get("projectile_slow_ticks").getInt();
Player player = (Player)event.getEntity();
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, ticks, 1, false));
}
}
// Used to track bow enchantment levels per player
private Map<String, Integer> bow_level_ = new TreeMap<String, Integer>();
@EventHandler
public void onEntityShootBow(EntityShootBowEvent event) {
if (!(event.getEntity() instanceof Player)) {
return;
}
int ench_level = 0;
ItemStack bow = event.getBow();
Map<Enchantment, Integer> enchants = bow.getEnchantments();
for (Enchantment ench : enchants.keySet()) {
int tmp_ench_level = 0;
if (ench.equals(Enchantment.KNOCKBACK) || ench.equals(Enchantment.ARROW_KNOCKBACK)) {
tmp_ench_level = enchants.get(ench) * 2;
} else if (ench.equals(Enchantment.ARROW_DAMAGE)) {
tmp_ench_level = enchants.get(ench);
}
if (tmp_ench_level > ench_level) {
ench_level = tmp_ench_level;
}
}
bow_level_.put(
((Player)event.getEntity()).getName(),
ench_level);
}
// BottleO refugees
// Changes the yield from an XP bottle
@BahHumbugs ({
@BahHumbug(opt="disable_experience", def="true"),
@BahHumbug(opt="xp_per_bottle", type=OptType.Int, def="10")
})
@EventHandler(priority=EventPriority.HIGHEST)
public void onExpBottleEvent(ExpBottleEvent event) {
final int bottle_xp = config_.get("xp_per_bottle").getInt();
if (config_.get("disable_experience").getBool()) {
((Player) event.getEntity().getShooter()).giveExp(bottle_xp);
event.setExperience(0);
} else {
event.setExperience(bottle_xp);
}
}
// Diables all XP gain except when manually changed via code.
@EventHandler
public void onPlayerExpChangeEvent(PlayerExpChangeEvent event) {
if (config_.get("disable_experience").getBool()) {
event.setAmount(0);
}
}
// Find the end portals
public static final int ender_portal_id_ = Material.ENDER_PORTAL.getId();
public static final int ender_portal_frame_id_ = Material.ENDER_PORTAL_FRAME.getId();
private Set<Long> end_portal_scanned_chunks_ = new TreeSet<Long>();
@BahHumbug(opt="find_end_portals", type=OptType.String)
@EventHandler
public void onFindEndPortals(ChunkLoadEvent event) {
String scanWorld = config_.get("find_end_portals").getString();
if (scanWorld.isEmpty()) {
return;
}
World world = event.getWorld();
if (!world.getName().equalsIgnoreCase(scanWorld)) {
return;
}
Chunk chunk = event.getChunk();
long chunk_id = (long)chunk.getX() << 32L + (long)chunk.getZ();
if (end_portal_scanned_chunks_.contains(chunk_id)) {
return;
}
end_portal_scanned_chunks_.add(chunk_id);
int chunk_x = chunk.getX() * 16;
int chunk_end_x = chunk_x + 16;
int chunk_z = chunk.getZ() * 16;
int chunk_end_z = chunk_z + 16;
int max_height = 0;
for (int x = chunk_x; x < chunk_end_x; x += 3) {
for (int z = chunk_z; z < chunk_end_z; ++z) {
int height = world.getMaxHeight();
if (height > max_height) {
max_height = height;
}
}
}
for (int y = 1; y <= max_height; ++y) {
int z_adj = 0;
for (int x = chunk_x; x < chunk_end_x; ++x) {
for (int z = chunk_z + z_adj; z < chunk_end_z; z += 3) {
int block_type = world.getBlockTypeIdAt(x, y, z);
if (block_type == ender_portal_id_ || block_type == ender_portal_frame_id_) {
info(String.format("End portal found at %d,%d", x, z));
return;
}
}
// This funkiness results in only searching 48 of the 256 blocks on
// each y-level. 81.25% fewer blocks checked.
++z_adj;
if (z_adj >= 3) {
z_adj = 0;
x += 2;
}
}
}
}
// Prevent inventory access while in a vehicle, unless it's the Player's
@BahHumbugs ({
@BahHumbug(opt="prevent_opening_container_carts", def="true"),
@BahHumbug(opt="prevent_vehicle_inventory_open", def="true")
})
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPreventVehicleInvOpen(InventoryOpenEvent event) {
// Cheap break-able conditional statement
while (config_.get("prevent_vehicle_inventory_open").getBool()) {
HumanEntity human = event.getPlayer();
if (!(human instanceof Player)) {
break;
}
if (!human.isInsideVehicle()) {
break;
}
InventoryHolder holder = event.getInventory().getHolder();
if (holder == human) {
break;
}
event.setCancelled(true);
break;
}
if (config_.get("prevent_opening_container_carts").getBool() && !event.isCancelled()) {
InventoryHolder holder = event.getInventory().getHolder();
if (holder instanceof StorageMinecart || holder instanceof HopperMinecart) {
event.setCancelled(true);
}
}
}
// Disable outbound hopper transfers
@BahHumbug(opt="disable_hopper_out_transfers", def="false")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onInventoryMoveItem(InventoryMoveItemEvent event) {
if (!config_.get("disable_hopper_out_transfers").getBool()) {
return;
}
final Inventory src = event.getSource();
final InventoryHolder srcHolder = src.getHolder();
if (srcHolder instanceof Hopper) {
event.setCancelled(true);
return;
}
}
// Adjust horse speeds
@BahHumbug(opt="horse_speed", type=OptType.Double, def="0.170000")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onVehicleEnter(VehicleEnterEvent event) {
// 0.17 is just a tad slower than minecarts
Vehicle vehicle = event.getVehicle();
if (!(vehicle instanceof Horse)) {
return;
}
Versioned.setHorseSpeed((Entity)vehicle, config_.get("horse_speed").getDouble());
}
// Admins can view player inventories
@SuppressWarnings("deprecation")
public void onInvseeCommand(Player admin, String playerName) {
final Player player = Bukkit.getPlayerExact(playerName);
if (player == null) {
admin.sendMessage("Player not found");
return;
}
final Inventory pl_inv = player.getInventory();
final Inventory inv = Bukkit.createInventory(
admin, 36, playerName + "'s Inventory");
for (int slot = 0; slot < 36; slot++) {
final ItemStack it = pl_inv.getItem(slot);
inv.setItem(slot, it);
}
admin.openInventory(inv);
admin.updateInventory();
}
// Fix boats
@BahHumbug(opt="prevent_self_boat_break", def="true")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPreventLandBoats(VehicleDestroyEvent event) {
if (!config_.get("prevent_land_boats").getBool()) {
return;
}
final Vehicle vehicle = event.getVehicle();
if (vehicle == null || !(vehicle instanceof Boat)) {
return;
}
final Entity passenger = vehicle.getPassenger();
if (passenger == null || !(passenger instanceof Player)) {
return;
}
final Entity attacker = event.getAttacker();
if (attacker == null) {
return;
}
if (!attacker.getUniqueId().equals(passenger.getUniqueId())) {
return;
}
final Player player = (Player)passenger;
Humbug.info(String.format(
"Player '%s' kicked for self damaging boat at %s",
player.getName(), vehicle.getLocation().toString()));
vehicle.eject();
vehicle.getWorld().dropItem(vehicle.getLocation(), new ItemStack(Material.BOAT));
vehicle.remove();
((Player)passenger).kickPlayer("Nope");
}
@BahHumbug(opt="prevent_land_boats", def="true")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onPreventLandBoats(VehicleMoveEvent event) {
if (!config_.get("prevent_land_boats").getBool()) {
return;
}
final Vehicle vehicle = event.getVehicle();
if (vehicle == null || !(vehicle instanceof Boat)) {
return;
}
final Entity passenger = vehicle.getPassenger();
if (passenger == null || !(passenger instanceof Player)) {
return;
}
final Location to = event.getTo();
final Material boatOn = to.getBlock().getRelative(BlockFace.DOWN).getType();
if (boatOn.equals(Material.STATIONARY_WATER) || boatOn.equals(Material.WATER)) {
return;
}
Humbug.info(String.format(
"Player '%s' removed from land-boat at %s",
((Player)passenger).getName(), to.toString()));
vehicle.eject();
vehicle.getWorld().dropItem(vehicle.getLocation(), new ItemStack(Material.BOAT));
vehicle.remove();
}
// Fix minecarts
public boolean checkForTeleportSpace(Location loc) {
final Block block = loc.getBlock();
final Material mat = block.getType();
if (mat.isSolid()) {
return false;
}
final Block above = block.getRelative(BlockFace.UP);
if (above.getType().isSolid()) {
return false;
}
return true;
}
public boolean tryToTeleport(Player player, Location location, String reason) {
Location loc = location.clone();
loc.setX(Math.floor(loc.getX()) + 0.500000D);
loc.setY(Math.floor(loc.getY()) + 0.02D);
loc.setZ(Math.floor(loc.getZ()) + 0.500000D);
final Location baseLoc = loc.clone();
final World world = baseLoc.getWorld();
// Check if teleportation here is viable
boolean performTeleport = checkForTeleportSpace(loc);
if (!performTeleport) {
loc.setY(loc.getY() + 1.000000D);
performTeleport = checkForTeleportSpace(loc);
}
if (performTeleport) {
player.setVelocity(new Vector());
player.teleport(loc);
Humbug.info(String.format(
"Player '%s' %s: Teleported to %s",
player.getName(), reason, loc.toString()));
return true;
}
loc = baseLoc.clone();
// Create a sliding window of block types and track how many of those
// are solid. Keep fetching the block below the current block to move down.
int air_count = 0;
LinkedList<Material> air_window = new LinkedList<Material>();
loc.setY((float)world.getMaxHeight() - 2);
Block block = world.getBlockAt(loc);
for (int i = 0; i < 4; ++i) {
Material block_mat = block.getType();
if (!block_mat.isSolid()) {
++air_count;
}
air_window.addLast(block_mat);
block = block.getRelative(BlockFace.DOWN);
}
// Now that the window is prepared, scan down the Y-axis.
while (block.getY() >= 1) {
Material block_mat = block.getType();
if (block_mat.isSolid()) {
if (air_count == 4) {
player.setVelocity(new Vector());
loc = block.getLocation();
loc.setX(Math.floor(loc.getX()) + 0.500000D);
loc.setY(loc.getY() + 1.02D);
loc.setZ(Math.floor(loc.getZ()) + 0.500000D);
player.teleport(loc);
Humbug.info(String.format(
"Player '%s' %s: Teleported to %s",
player.getName(), reason, loc.toString()));
return true;
}
} else { // !block_mat.isSolid()
++air_count;
}
air_window.addLast(block_mat);
if (!air_window.removeFirst().isSolid()) {
--air_count;
}
block = block.getRelative(BlockFace.DOWN);
}
return false;
}
@BahHumbug(opt="prevent_ender_pearl_save", def="true")
@EventHandler
public void enderPearlSave(EnderPearlUnloadEvent event) {
if(!config_.get("prevent_ender_pearl_save").getBool())
return;
event.setCancelled(true);
}
@BahHumbug(opt="fix_vehicle_logout_bug", def="true")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled=true)
public void onDisallowVehicleLogout(PlayerQuitEvent event) {
if (!config_.get("fix_vehicle_logout_bug").getBool()) {
return;
}
kickPlayerFromVehicle(event.getPlayer());
}
public void kickPlayerFromVehicle(Player player) {
Entity vehicle = player.getVehicle();
if (vehicle == null
|| !(vehicle instanceof Minecart || vehicle instanceof Horse || vehicle instanceof Arrow)) {
return;
}
Location vehicleLoc = vehicle.getLocation();
// Vehicle data has been cached, now safe to kick the player out
player.leaveVehicle();
if (!tryToTeleport(player, vehicleLoc, "logged out")) {
player.setHealth(0.000000D);
Humbug.info(String.format(
"Player '%s' logged out in vehicle: Killed", player.getName()));
}
}
@BahHumbug(opt="fix_minecart_reenter_bug", def="true")
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onFixMinecartReenterBug(VehicleExitEvent event) {
if (!config_.get("fix_minecart_reenter_bug").getBool()) {
return;
}
final Vehicle vehicle = event.getVehicle();
if (vehicle == null || !(vehicle instanceof Minecart)) {
return;
}
final Entity passengerEntity = event.getExited();
if (passengerEntity == null || !(passengerEntity instanceof Player)) {
return;
}
// Must delay the teleport 2 ticks or else the player's mis-managed
// movement still occurs. With 1 tick it could still occur.
final Player player = (Player)passengerEntity;
final Location vehicleLoc = vehicle.getLocation();
Bukkit.getScheduler().runTaskLater(this, new Runnable() {
@Override
public void run() {
if (!tryToTeleport(player, vehicleLoc, "exiting vehicle")) {
player.setHealth(0.000000D);
Humbug.info(String.format(
"Player '%s' exiting vehicle: Killed", player.getName()));
}
}
}, 2L);
}
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
public void onFixMinecartReenterBug(VehicleDestroyEvent event) {
if (!config_.get("fix_minecart_reenter_bug").getBool()) {
return;
}
final Vehicle vehicle = event.getVehicle();
if (vehicle == null || !(vehicle instanceof Minecart || vehicle instanceof Horse)) {
return;
}
final Entity passengerEntity = vehicle.getPassenger();
if (passengerEntity == null || !(passengerEntity instanceof Player)) {
return;
}
// Must delay the teleport 2 ticks or else the player's mis-managed
// movement still occurs. With 1 tick it could still occur.
final Player player = (Player)passengerEntity;
final Location vehicleLoc = vehicle.getLocation();
Bukkit.getScheduler().runTaskLater(this, new Runnable() {
@Override
public void run() {
if (!tryToTeleport(player, vehicleLoc, "in destroyed vehicle")) {
player.setHealth(0.000000D);
Humbug.info(String.format(
"Player '%s' in destroyed vehicle: Killed", player.getName()));
}
}
}, 2L);
}
// Adjust ender pearl gravity
public final static int pearlId = 368;
public final static MinecraftKey pearlKey = new MinecraftKey("ender_pearl");
@SuppressWarnings({ "rawtypes", "unchecked" })
@BahHumbug(opt="ender_pearl_gravity", type=OptType.Double, def="0.060000")
private void hookEnderPearls() {
try {
// They thought they could stop us by preventing us from registering an
// item. We'll show them
Field idRegistryField = Item.REGISTRY.getClass().getDeclaredField("a");
idRegistryField.setAccessible(true);
Object idRegistry = idRegistryField.get(Item.REGISTRY);
Field idRegistryMapField = idRegistry.getClass().getDeclaredField("a");
idRegistryMapField.setAccessible(true);
Object idRegistryMap = idRegistryMapField.get(idRegistry);
Field idRegistryItemsField = idRegistry.getClass().getDeclaredField("b");
idRegistryItemsField.setAccessible(true);
Object idRegistryItemList = idRegistryItemsField.get(idRegistry);
// Remove ItemEnderPearl from the ID Registry
Item idItem = null;
Iterator<Item> itemListIter = ((List<Item>)idRegistryItemList).iterator();
while (itemListIter.hasNext()) {
idItem = itemListIter.next();
if (idItem == null) {
continue;
}
if (!(idItem instanceof ItemEnderPearl)) {
continue;
}
itemListIter.remove();
break;
}
if (idItem != null) {
((Map<Item, Integer>)idRegistryMap).remove(idItem);
}
// Register our custom pearl Item.
Item.REGISTRY.a(pearlId, pearlKey, new CustomNMSItemEnderPearl(config_));
// Setup the custom entity
Field fieldStringToClass = EntityTypes.class.getDeclaredField("c");
Field fieldClassToString = EntityTypes.class.getDeclaredField("d");
fieldStringToClass.setAccessible(true);
fieldClassToString.setAccessible(true);
Field fieldClassToId = EntityTypes.class.getDeclaredField("f");
Field fieldStringToId = EntityTypes.class.getDeclaredField("g");
fieldClassToId.setAccessible(true);
fieldStringToId.setAccessible(true);
Map mapStringToClass = (Map)fieldStringToClass.get(null);
Map mapClassToString = (Map)fieldClassToString.get(null);
Map mapClassToId = (Map)fieldClassToId.get(null);
Map mapStringToId = (Map)fieldStringToId.get(null);
mapStringToClass.put("ThrownEnderpearl",CustomNMSEntityEnderPearl.class);
mapStringToId.put("ThrownEnderpearl", Integer.valueOf(14));
mapClassToString.put(CustomNMSEntityEnderPearl.class, "ThrownEnderpearl");
mapClassToId.put(CustomNMSEntityEnderPearl.class, Integer.valueOf(14));
} catch (Exception e) {
Humbug.severe("Exception while overriding MC's ender pearl class");
e.printStackTrace();
}
}
// Hunger Changes
// Keep track if the player just ate.
private Map<Player, Double> playerLastEat_ = new HashMap<Player, Double>();
@BahHumbug(opt="saturation_multiplier", type=OptType.Double, def="0.0")
@EventHandler
public void setSaturationOnFoodEat(PlayerItemConsumeEvent event) {
// Each food sets a different saturation.
final Player player = event.getPlayer();
ItemStack item = event.getItem();
Material mat = item.getType();
double multiplier = config_.get("saturation_multiplier").getDouble();
if (multiplier <= 0.000001 && multiplier >= -0.000001) {
return;
}
switch(mat) {
case APPLE:
playerLastEat_.put(player, multiplier*2.4);
case BAKED_POTATO:
playerLastEat_.put(player, multiplier*7.2);
case BREAD:
playerLastEat_.put(player, multiplier*6);
case CAKE:
playerLastEat_.put(player, multiplier*0.4);
case CARROT_ITEM:
playerLastEat_.put(player, multiplier*4.8);
case COOKED_FISH:
playerLastEat_.put(player, multiplier*6);
case GRILLED_PORK:
playerLastEat_.put(player, multiplier*12.8);
case COOKIE:
playerLastEat_.put(player, multiplier*0.4);
case GOLDEN_APPLE:
playerLastEat_.put(player, multiplier*9.6);
case GOLDEN_CARROT:
playerLastEat_.put(player, multiplier*14.4);
case MELON:
playerLastEat_.put(player, multiplier*1.2);
case MUSHROOM_SOUP:
playerLastEat_.put(player, multiplier*7.2);
case POISONOUS_POTATO:
playerLastEat_.put(player, multiplier*1.2);
case POTATO:
playerLastEat_.put(player, multiplier*0.6);
case RAW_FISH:
playerLastEat_.put(player, multiplier*1);
case PUMPKIN_PIE:
playerLastEat_.put(player, multiplier*4.8);
case RAW_BEEF:
playerLastEat_.put(player, multiplier*1.8);
case RAW_CHICKEN:
playerLastEat_.put(player, multiplier*1.2);
case PORK:
playerLastEat_.put(player, multiplier*1.8);
case ROTTEN_FLESH:
playerLastEat_.put(player, multiplier*0.8);
case SPIDER_EYE:
playerLastEat_.put(player, multiplier*3.2);
case COOKED_BEEF:
playerLastEat_.put(player, multiplier*12.8);
default:
playerLastEat_.put(player, multiplier);
Bukkit.getServer().getScheduler().runTaskLater(this, new Runnable() {
// In case the player ingested a potion, this removes the
// saturation from the list. Unsure if I have every item
// listed. There is always the other cases of like food
// that shares same id
@Override
public void run() {
playerLastEat_.remove(player);
}
}, 80);
}
}
@BahHumbug(opt="hunger_slowdown", type=OptType.Double, def="0.0")
@EventHandler
public void onFoodLevelChange(FoodLevelChangeEvent event) {
final Player player = (Player) event.getEntity();
final double mod = config_.get("hunger_slowdown").getDouble();
Double saturation;
if (playerLastEat_.containsKey(player)) { // if the player just ate
saturation = playerLastEat_.get(player);
if (saturation == null) {
saturation = ((Float)player.getSaturation()).doubleValue();
}
} else {
saturation = Math.min(
player.getSaturation() + mod,
20.0D + (mod * 2.0D));
}
player.setSaturation(saturation.floatValue());
}
//Remove Book Copying
@BahHumbug(opt="copy_book_enable", def= "false")
public void removeBooks() {
if (config_.get("copy_book_enable").getBool()) {
return;
}
Iterator<Recipe> it = getServer().recipeIterator();
while (it.hasNext()) {
Recipe recipe = it.next();
ItemStack resulting_item = recipe.getResult();
if ( // !copy_book_enable_ &&
isWrittenBook(resulting_item)) {
it.remove();
info("Copying Books disabled");
}
}
}
public boolean isWrittenBook(ItemStack item) {
if (item == null) {
return false;
}
Material material = item.getType();
return material.equals(Material.WRITTEN_BOOK);
}
// Prevent tree growth wrap-around
@BahHumbug(opt="prevent_tree_wraparound", def="true")
@EventHandler(priority=EventPriority.LOWEST, ignoreCancelled = true)
public void onStructureGrowEvent(StructureGrowEvent event) {
if (!config_.get("prevent_tree_wraparound").getBool()) {
return;
}
int maxY = 0, minY = 257;
for (BlockState bs : event.getBlocks()) {
final int y = bs.getLocation().getBlockY();
maxY = Math.max(maxY, y);
minY = Math.min(minY, y);
}
if (maxY - minY > 240) {
event.setCancelled(true);
final Location loc = event.getLocation();
info(String.format("Prevented structure wrap-around at %d, %d, %d",
loc.getBlockX(), loc.getBlockY(), loc.getBlockZ()));
}
}
// General
public void onLoad()
{
loadConfiguration();
//hookEnderPearls();
info("Loaded");
}
public void onEnable() {
registerEvents();
registerCommands();
removeRecipies();
removeBooks();
registerTimerForPearlCheck();
global_instance_ = this;
info("Enabled");
}
public void onDisable() {
if (config_.get("fix_vehicle_logout_bug").getBool()) {
for (World world: getServer().getWorlds()) {
for (Player player: world.getPlayers()) {
kickPlayerFromVehicle(player);
}
}
}
}
public boolean isInitiaized() {
return global_instance_ != null;
}
public boolean toBool(String value) {
if (value.equals("1") || value.equalsIgnoreCase("true")) {
return true;
}
return false;
}
public int toInt(String value, int default_value) {
try {
return Integer.parseInt(value);
} catch(Exception e) {
return default_value;
}
}
public double toDouble(String value, double default_value) {
try {
return Double.parseDouble(value);
} catch(Exception e) {
return default_value;
}
}
public int toMaterialId(String value, int default_value) {
try {
return Integer.parseInt(value);
} catch(Exception e) {
Material mat = Material.matchMaterial(value);
if (mat != null) {
return mat.getId();
}
}
return default_value;
}
public boolean onCommand(
CommandSender sender,
Command command,
String label,
String[] args) {
if (sender instanceof Player && command.getName().equals("invsee")) {
if (args.length < 1) {
sender.sendMessage("Provide a name");
return false;
}
onInvseeCommand((Player)sender, args[0]);
return true;
}
if (sender instanceof Player
&& command.getName().equals("introbook")) {
if (!config_.get("drop_newbie_book").getBool()) {
return true;
}
Player sendBookTo = (Player)sender;
if (args.length >= 1) {
Player possible = Bukkit.getPlayerExact(args[0]);
if (possible != null) {
sendBookTo = possible;
}
}
giveN00bBook(sendBookTo);
return true;
}
if (sender instanceof Player
&& command.getName().equals("bahhumbug")) {
giveHolidayPackage((Player)sender);
return true;
}
if (!(sender instanceof ConsoleCommandSender) ||
!command.getName().equals("humbug") ||
args.length < 1) {
return false;
}
String option = args[0];
String value = null;
String subvalue = null;
boolean set = false;
boolean subvalue_set = false;
String msg = "";
if (args.length > 1) {
value = args[1];
set = true;
}
if (args.length > 2) {
subvalue = args[2];
subvalue_set = true;
}
ConfigOption opt = config_.get(option);
if (opt != null) {
if (set) {
opt.set(value);
}
msg = String.format("%s = %s", option, opt.getString());
} else if (option.equals("debug")) {
if (set) {
config_.setDebug(toBool(value));
}
msg = String.format("debug = %s", config_.getDebug());
} else if (option.equals("loot_multiplier")) {
String entity_type = "generic";
if (set && subvalue_set) {
entity_type = value;
value = subvalue;
}
if (set) {
config_.setLootMultiplier(
entity_type, toInt(value, config_.getLootMultiplier(entity_type)));
}
msg = String.format(
"loot_multiplier(%s) = %d", entity_type, config_.getLootMultiplier(entity_type));
} else if (option.equals("remove_mob_drops")) {
if (set && subvalue_set) {
if (value.equals("add")) {
config_.addRemoveItemDrop(toMaterialId(subvalue, -1));
} else if (value.equals("del")) {
config_.removeRemoveItemDrop(toMaterialId(subvalue, -1));
}
}
msg = String.format("remove_mob_drops = %s", config_.toDisplayRemoveItemDrops());
} else if (option.equals("save")) {
config_.save();
msg = "Configuration saved";
} else if (option.equals("reload")) {
config_.reload();
msg = "Configuration loaded";
} else {
msg = String.format("Unknown option %s", option);
}
sender.sendMessage(msg);
return true;
}
public void registerCommands() {
ConsoleCommandSender console = getServer().getConsoleSender();
console.addAttachment(this, "humbug.console", true);
}
private void registerEvents() {
getServer().getPluginManager().registerEvents(this, this);
}
private void loadConfiguration() {
config_ = Config.initialize(this);
}
} |
package com.baoyz.swipemenulistview;
import android.content.Context;
import android.support.v4.view.MotionEventCompat;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Interpolator;
import android.widget.ListAdapter;
import android.widget.ListView;
/**
*
* @author baoyz
* @date 2014-8-18
*
*/
public class SwipeMenuListView extends ListView {
private static final int TOUCH_STATE_NONE = 0;
private static final int TOUCH_STATE_X = 1;
private static final int TOUCH_STATE_Y = 2;
private int MAX_Y = 5;
private int MAX_X = 3;
private float mDownX;
private float mDownY;
private int mTouchState;
private int mTouchPosition;
private SwipeMenuLayout mTouchView;
private OnSwipeListener mOnSwipeListener;
private SwipeMenuCreator mMenuCreator;
private OnMenuItemClickListener mOnMenuItemClickListener;
private Interpolator mCloseInterpolator;
private Interpolator mOpenInterpolator;
public SwipeMenuListView(Context context) {
super(context);
init();
}
public SwipeMenuListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public SwipeMenuListView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
MAX_X = dp2px(MAX_X);
MAX_Y = dp2px(MAX_Y);
mTouchState = TOUCH_STATE_NONE;
}
@Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(new SwipeMenuAdapter(getContext(), adapter) {
@Override
public void createMenu(SwipeMenu menu) {
if (mMenuCreator != null) {
mMenuCreator.create(menu);
}
}
@Override
public void onItemClick(SwipeMenuView view, SwipeMenu menu,
int index) {
boolean flag = false;
if (mOnMenuItemClickListener != null) {
flag = mOnMenuItemClickListener.onMenuItemClick(
view.getPosition(), menu, index);
}
if (mTouchView != null && !flag) {
mTouchView.smoothCloseMenu();
}
}
});
}
public void setCloseInterpolator(Interpolator interpolator) {
mCloseInterpolator = interpolator;
}
public void setOpenInterpolator(Interpolator interpolator) {
mOpenInterpolator = interpolator;
}
public Interpolator getOpenInterpolator() {
return mOpenInterpolator;
}
public Interpolator getCloseInterpolator() {
return mCloseInterpolator;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (ev.getAction() != MotionEvent.ACTION_DOWN && mTouchView == null)
return super.onTouchEvent(ev);
int action = MotionEventCompat.getActionMasked(ev);
action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
int oldPos = mTouchPosition;
mDownX = ev.getX();
mDownY = ev.getY();
mTouchState = TOUCH_STATE_NONE;
mTouchPosition = pointToPosition((int) ev.getX(), (int) ev.getY());
if (mTouchPosition == oldPos && mTouchView != null
&& mTouchView.isOpen()) {
mTouchState = TOUCH_STATE_X;
mTouchView.onSwipe(ev);
return true;
}
View view = getChildAt(mTouchPosition - getFirstVisiblePosition());
if (mTouchView != null && mTouchView.isOpen()) {
mTouchView.smoothCloseMenu();
mTouchView = null;
// return super.onTouchEvent(ev);
// try to cancel the touch event
MotionEvent cancelEvent = MotionEvent.obtain(ev);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL);
onTouchEvent(cancelEvent);
return true;
}
if (view instanceof SwipeMenuLayout) {
mTouchView = (SwipeMenuLayout) view;
}
if (mTouchView != null) {
mTouchView.onSwipe(ev);
}
break;
case MotionEvent.ACTION_MOVE:
float dy = Math.abs((ev.getY() - mDownY));
float dx = Math.abs((ev.getX() - mDownX));
if (mTouchState == TOUCH_STATE_X) {
if (mTouchView != null) {
mTouchView.onSwipe(ev);
}
getSelector().setState(new int[] { 0 });
ev.setAction(MotionEvent.ACTION_CANCEL);
super.onTouchEvent(ev);
return true;
} else if (mTouchState == TOUCH_STATE_NONE) {
if (Math.abs(dy) > MAX_Y) {
mTouchState = TOUCH_STATE_Y;
} else if (dx > MAX_X) {
mTouchState = TOUCH_STATE_X;
if (mOnSwipeListener != null) {
mOnSwipeListener.onSwipeStart(mTouchPosition);
}
}
}
break;
case MotionEvent.ACTION_UP:
if (mTouchState == TOUCH_STATE_X) {
if (mTouchView != null) {
mTouchView.onSwipe(ev);
if (!mTouchView.isOpen()) {
mTouchPosition = -1;
mTouchView = null;
}
}
if (mOnSwipeListener != null) {
mOnSwipeListener.onSwipeEnd(mTouchPosition);
}
ev.setAction(MotionEvent.ACTION_CANCEL);
super.onTouchEvent(ev);
return true;
}
break;
}
return super.onTouchEvent(ev);
}
public void smoothOpenMenu(int position) {
if (position >= getFirstVisiblePosition()
&& position <= getLastVisiblePosition()) {
View view = getChildAt(position - getFirstVisiblePosition());
if (view instanceof SwipeMenuLayout) {
mTouchPosition = position;
if (mTouchView != null && mTouchView.isOpen()) {
mTouchView.smoothCloseMenu();
}
mTouchView = (SwipeMenuLayout) view;
mTouchView.smoothOpenMenu();
}
}
}
private int dp2px(int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
getContext().getResources().getDisplayMetrics());
}
public void setMenuCreator(SwipeMenuCreator menuCreator) {
this.mMenuCreator = menuCreator;
}
public void setOnMenuItemClickListener(
OnMenuItemClickListener onMenuItemClickListener) {
this.mOnMenuItemClickListener = onMenuItemClickListener;
}
public void setOnSwipeListener(OnSwipeListener onSwipeListener) {
this.mOnSwipeListener = onSwipeListener;
}
public static interface OnMenuItemClickListener {
boolean onMenuItemClick(int position, SwipeMenu menu, int index);
}
public static interface OnSwipeListener {
void onSwipeStart(int position);
void onSwipeEnd(int position);
}
} |
package de.skuzzle.jeve;
import java.util.Collection;
import java.util.concurrent.ExecutorService;
import java.util.function.BiConsumer;
/**
* <p>EventProvider instances are the heart of jeve. They manage listener classes mapping
* to a collection of {@link Listener Listeners} to represent one kind of event.
* All listeners registered for a certain listener class can be notified about an
* {@link Event}. The way in which they are notified is an internal property of the
* actual EventProvider instance. For example, one kind of EventProvider might create a
* new thread for notifying the registered listeners or it may simply notify them using
* the current thread.</p>
*
* <p>EventProvider instances can be obtained by using the static factory methods of this
* interface or by creating an own implementation.</p>
*
* <pre>
* EventProvider eventProvider = EventProvider.newDefaultEventProvider();
* </pre>
*
* <h2>Managing and Notifying Listeners</h2>
* <p>Listeners can be registered using {@link #addListener(Class, Listener)} and
* unregistered using {@link #removeListener(Class, Listener)}. The same listener can be
* registered for distinct listener classes. The {@link Listener} interface has two
* default methods which are called when a listener is registered or removed respectively.
* Additionally there exists the default method <tt>workDone</tt>. If this method is
* implemented to return <code>true</code>, the listener will be removed automatically
* from the event provider. Listeners registered for a certain class can be obtained by
* {@link #getListeners(Class)}. Client code should avoid using this method as it is not
* needed in most cases.</p>
*
* <p>The reason why not to query the registered listeners from client code, is that
* EventProviders use <em>internal iteration</em> when notifying listeners. This reduces
* the use cases where client code explicitly needs a list of listeners. The logic of how
* listeners are iterated is moved into the framework, reducing duplicated and error prone
* code on the client side.</p>
*
* <p>To notify the registered listeners, you need to specify the class for which they
* have been registered, the Event instance which is passed to each listener and the
* actual method to call on each listener. Here is an example of notifying listeners which
* have been registered for the class <tt>UserListener</tt>.</p>
*
* <pre>
* // create an event which holds its source and some additional data
* UserEvent e = new UserEvent(this, user);
*
* // notify all UserListeners with this event.
* eventProvider.dispatch(UserListener.class, e, UserListener::userAdded);
* </pre>
*
* <p>On each listener which is registered for the class <tt>UserListener</tt>, the method
* <tt>userAdded</tt> is called and gets passed the event instance <tt>e</tt>.
* {@link #dispatch(Class, Event, BiConsumer) Dispatch} is the core of any EventProvider.
* It implements the logic of how the listeners are notified in way that is transparent
* for the user of the EventProvider.</p>
*
* <h2>Error handling</h2>
* <p>The main goal of jeve is, that event delegation must never be interrupted
* unintentionally. When handling events, you don't want the dispatching process to stop
* if one of the listeners throws an unchecked exception. Therefore, jeve uses
* {@link ExceptionCallback ExceptionCallbacks} to notify client code about any
* exception. After notifying the callback, event delegation continues with the next
* listener. If the callback method itself throws an exception, it will be swallowed.</p>
*
* <p>A default {@link ExceptionCallback} can be set by using
* {@link #setExceptionCallback(ExceptionCallback)}. Additionally, you can set a callback
* for a single dispatch action by using an override of
* {@link #dispatch(Class, Event, BiConsumer, ExceptionCallback) dispatch}. If you do not
* specify a callback, a {@link #DEFAULT_HANDLER default} instance will be used.</p>
*
* <h2>Sequential EventProviders</h2>
* <p>An EventProvider is said to be <em>sequential</em>, if it guarantees that listeners
* are notified in the order in which they were registered for a certain listener class.
* EventProviders report this property with {@link #isSequential()}. Whether an
* EventProvider actually is sequential depends on its implementation of the dispatch
* method. For example, a provider which notifies each listener within a separate thread
* is not sequential.</p>
*
* <p>Unless stated otherwise, all EventProviders which can be obtained from the static
* factory methods are sequential.</p>
*
* <h2>Aborting Event Delegation</h2>
* <p>As stated above, event delegation can not be interrupted by throwing exceptions.
* Instead, listeners can modify the passed Event instance and set its
* {@link Event#setHandled(boolean) handled} property to <code>true</code>. Before
* notifying the next listener, the EventProvider queries the
* {@link Event#isHandled() isHandled} property of the currently processed event. If it
* is handled, event delegation stops and no further listeners are notified.</p>
*
* <p>This mechanism obviously only works correctly, if the used EventProvider is
* sequential. If it is not, the behavior is unspecified.</p>
*
* @author Simon
*/
public interface EventProvider extends AutoCloseable {
/**
* Creates a new {@link EventProvider} which fires events sequentially in the thread
* which calls {@link EventProvider#dispatch(Class, Event, BiConsumer)}. The returned
* instance thus is sequential.
*
* <p>Closing the {@link EventProvider} returned by this method will have no
* effect besides removing all registered listeners.</p>
*
* @return A new EventProvider instance.
*/
public static EventProvider newDefaultEventProvider() {
return new SynchronousEventProvider();
}
/**
* Creates a new {@link EventProvider} which fires each event in a different thread.
* By default, the returned {@link EventProvider} uses a single thread executor
* service.
*
* <p>The returned instance is sequential. Even when using multiple threads to
* dispatch events, the returned EventProvider will only use one thread for one
* dispatch action. That means that for each call to
* {@link #dispatch(Class, Event, BiConsumer, ExceptionCallback) dispatch}, all
* targeted listeners are notified within the same thread. This ensures notification
* in the order the listeners have been added.</p>
*
* <p>When closing the returned {@link EventProvider}, its internal
* {@link ExecutorService} instance will be shut down. Its not possible to reuse the
* provider after closing it.</p>
*
* @return A new EventProvider instance.
*/
public static EventProvider newAsynchronousEventProvider() {
return new AsynchronousEventProvider();
}
/**
* Creates a new {@link EventProvider} which fires each event in a different thread.
* The created provider will use the given {@link ExecutorService} to fire the events
* asynchronously.
*
* <p>The returned instance is sequential. Even when using multiple threads to
* dispatch events, the returned EventProvider will only use one thread for one
* dispatch action. That means that for each call to
* {@link #dispatch(Class, Event, BiConsumer, ExceptionCallback) dispatch}, all
* targeted listeners are notified within the same thread. This ensures notification
* in the order the listeners have been added.</p>
*
* <p>If you require an EventListener which notifies each listener in a different
* thread, you need to create your own sub class of {@link AbstractEventProvider}.</p>
*
* <p>When closing the returned {@link EventProvider}, the passed
* {@link ExecutorService} instance will be shut down. Its not possible to reuse the
* provider after closing it.</p>
*
* @param dispatcher The ExecutorService to use.
* @return A new EventProvider instance.
*/
public static EventProvider newAsynchronousEventProvider(ExecutorService dispatcher) {
return new AsynchronousEventProvider(dispatcher);
}
/**
* Create a new {@link EventProvider} which dispatches all events in the AWT event
* thread and waits (blocks current thread) after dispatching until all listeners
* have been notified. The returned instance is sequential.
*
* <p>Closing the {@link EventProvider} returned by this method will have no
* effect besides removing all registered listeners.</p>
*
* @return A new EventProvider instance.
*/
public static EventProvider newWaitingAWTEventProvider() {
return new AWTEventProvider(true);
}
/**
* Creates a new {@link EventProvider} which dispatches all events in the AWT event
* thread. Dispatching with this EventProvider will return immediately and dispatching
* of an event will be scheduled to be run later by the AWT event thread. The returned
* instance is sequential.
*
* <p>Closing the {@link EventProvider} returned by this method will have no
* effect besides removing all registered listeners.</p>
*
* @return A new EventProvider instance.
*/
public static EventProvider newAsynchronousAWTEventProvider() {
return new AWTEventProvider(false);
}
/**
* The default {@link ExceptionCallback} which prints some information about the
* occurred error to the standard output. The exact format is not specified.
*/
public final static ExceptionCallback DEFAULT_HANDLER = (e, l, ev) -> {
System.err.println(
"Listener threw an exception while being notified\n" +
"Details\n" +
" Listener: " + l + "\n" +
" Event: " + ev + "\n" +
" Message: " + e.getMessage() + "\n" +
" Current Thread: " + Thread.currentThread().getName() + "\n" +
" Stacktrace: "
);
e.printStackTrace();
};
public <T extends Listener> void addListener(Class<T> listenerClass,
T listener);
/**
* Removes a listener. It will only be removed for the specified listener class and
* can thus still be registered with this event provider if it was added for
* further listener classes. The listener will no longer receive events represented
* by the given listener class. After removal, the listener's
* {@link Listener#onUnregister(RegistrationEvent) onUnregister} method gets called to
* notify the listener about being removed from a parent. This method is not subject
* to the dispatching strategy implemented by this {@link EventProvider} and is
* called from the current thread.
*
* <p>If any of the arguments is <code>null</code>, this method returns with no
* effect.</p>
*
* @param <T> Type of the listener to remove.
* @param listenerClass The class representing the event(s) for which the listener
* should be removed.
* @param listener The listener to remove.
*/
public <T extends Listener> void removeListener(Class<T> listenerClass,
T listener);
public <T extends Listener> Collection<T> getListeners(Class<T> listenerClass);
/**
* Removes all listeners which have been registered for the provided listener class.
* Every listner's {@link Listener#onUnregister(RegistrationEvent) onUnregister}
* method will be called.
*
* <p>If listenerClass is <code>null</code> this method returns with no effect.</p>
*
* @param <T> Type of the listeners to remove.
* @param listenerClass The class representing the event for which the listeners
* should be removed
*/
public <T extends Listener> void clearAllListeners(Class<T> listenerClass);
/**
* Removes all registered listeners from this EventProvider. Every listner's
* {@link Listener#onUnregister(RegistrationEvent) onUnregister} method will be
* called.
*/
public void clearAllListeners();
public <L extends Listener, E extends Event<?>> void dispatch(
Class<L> listenerClass, E event, BiConsumer<L, E> bc);
public <L extends Listener, E extends Event<?>> void dispatch(
Class<L> listenerClass, E event, BiConsumer<L, E> bc, ExceptionCallback ec);
/**
* Gets whether this EventProvider is ready for dispatching.
*
* @return Whether further events can be dispatched using
* {@link #dispatch(Class, Event, BiConsumer, ExceptionCallback) dispatch}
*/
public boolean canDispatch();
/**
* Sets the default {@link ExceptionCallback} which will be notified about
* exceptions when dispatching events without explicitly specifying an
* ExceptionCallback. The ExceptionCallback which is installed by default simply
* prints the stack traces to the error console.
*
* <p>You can reset the ExceptionCallback to the default handler by providing
* <code>null</code> as parameter.</p>
* @param ec The ExceptionCallback for handling event handler exceptions, or
* <code>null</code> to use the default behavior.
*/
public void setExceptionCallback(ExceptionCallback ec);
/**
* Returns whether this EventProvider is sequential, which means it strictly
* notifies listeners in the order in which they were registered for a certain event.
*
* @return Whether this instance is sequential.
*/
public boolean isSequential();
/**
* Closes this EventProvider and removes all registered listeners. Depending on the
* actual implementation, the EventProvider might not be able to dispatch further
* events after closing. On some implementations closing might have no additional
* effect.
*/
@Override
public void close();
} |
package edu.chl.proton.model;
import javafx.scene.text.Text;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class Document {
// Lika = document
private Cursor cursor;
private File file;
private List<String> lines = new ArrayList<String>();
DocTypeInterface docType;
public Document(DocTypeInterface type){
this.docType = type;
}
public Document(String name){
String extension = name.substring(name.lastIndexOf(".") + 1, name.length());
}
protected Cursor getCursor(){
return this.cursor;
}
protected void setCursor(Cursor cursor){
this.cursor = cursor;
}
protected File getFile(){
return this.file;
}
protected void setFile(File file){
this.file = file;
}
protected void addFile(String path){
file.setPath(path);
// setFile(rootFolder.getFileFromPath(path)); ???
}
protected void insertParts(String str){
int row = cursor.getPosition().getY();
int col = cursor.getPosition().getX();
String tmp = lines.get(row);
StringBuilder sb = new StringBuilder(tmp);
sb.insert(col, str);
lines.set(row, sb.toString());
cursor.setPosition(row, col + 1);
}
protected void addLines(String lines){
this.lines.add(lines);
}
protected void removeLines(int index){
lines.remove(index);
}
protected void removeAllLines(){
lines.clear();
}
protected void insertChar(char ch){
int row = cursor.getPosition().getY();
int col = cursor.getPosition().getX();
// check if Enter was the key pressed
if(ch == '\r'){
cursor.setPosition(row + 1, col);
} else {
String tmp = lines.get(row);
StringBuilder sb = new StringBuilder(tmp);
sb.insert(col, ch);
lines.set(row, sb.toString());
cursor.setPosition(row, col + 1);
}
}
protected void deleteChar(){
int row = cursor.getPosition().getY();
int col = cursor.getPosition().getX();
String tmp = lines.get(row);
StringBuilder sb = new StringBuilder(tmp);
sb.deleteCharAt(col);
lines.set(row, sb.toString());
cursor.setPosition(row, col - 1);
}
public List<String> getText(){
return docType.getText();
}
protected void setText(List<String> text){
docType.setText();
}
protected void save() throws IOException{
file.save(lines);
}
protected void remove(){
file.remove();
}
protected boolean isSaved(){
return file.isSaved();
}
// Aqcuires the text from the file we opened.
protected void aqcuireText() {
file.aqcuireText();
}
} |
package edu.jhu.featurize;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import java.util.Set;
import org.apache.commons.cli.ParseException;
import org.apache.log4j.Logger;
//import com.google.common.collect.Maps;
import edu.berkeley.nlp.PCFGLA.smoothing.*;
import edu.jhu.util.cli.ArgParser;
import edu.jhu.util.cli.Opt;
import edu.jhu.data.conll.CoNLL09FileReader;
import edu.jhu.data.conll.CoNLL09Sentence;
import edu.jhu.data.conll.CoNLL09Token;
import edu.jhu.data.conll.SrlGraph;
import edu.jhu.data.conll.SrlGraph.SrlEdge;
import edu.jhu.util.Alphabet;
import edu.jhu.data.Label;
/**
* Featurize sentence with CoNLL annotations.
* @author mmitchell
*
*/
public class GetFeatures {
private static final Logger log = Logger.getLogger(GetFeatures.class);
@Opt(name="train", hasArg=true, required=true, description="Training file.")
public static String trainingFile="/home/hltcoe/mgormley/working/parsing/exp/vem-conll_001/dmv_conll09-sp-dev_20_28800_True/train-parses.txt";
@Opt(name="test", hasArg=true, required=true, description="Testing file.")
public static String testingFile="/home/hltcoe/mgormley/working/parsing/exp/vem-conll_001/dmv_conll09-sp-dev_20_28800_True/test-parses.txt";
@Opt(name="language", hasArg=true, description="Language (en or es).")
public static String language = "es";
@Opt(name="out-dir", hasArg=true, description="Output directory.")
public static String outDir="train_test/";
@Opt(name="note", hasArg=true, description="Note to append to files.")
public static String note="";
@Opt(name="brown", hasArg=true, description="--brown [FILE] = Use Brown Clusters from [FILE] rather than POS tags at cut = 5.")
public static String brown="";
@Opt(name="cutoff", hasArg=true, description="Cutoff for OOV words.")
public static int cutoff=3;
@Opt(name="use-PHEAD", hasArg=false, description="Use Predicted HEAD rather than Gold HEAD.")
public static boolean goldHead = true;
@Opt(name="no-link-factor", hasArg=false, description="Do not factor model on input dependency links.")
public static boolean linkFactor = false;
@Opt(name="dep-features", hasArg=false, description="Use dependency parse as features.")
public static boolean depFeatures = false;
@Opt(name="fast-crf", hasArg=false, description="Whether to use our fast CRF framework instead of ERMA")
public static boolean crfFeatures = false;
public Set<String> allFeatures = new HashSet<String>();
public Set<String> knownWords = new HashSet<String>();
public Set<String> knownUnks = new HashSet<String>();
// Currently not using this (will it matter?);
public Set<Set<String>> knownBigrams = new HashSet<Set<String>>();
public Set<String> knownPostags = new HashSet<String>();
public Set<String> knownRoles = new HashSet<String>();
public Integer maxSentLength = 0;
private static Map<String,String> stringMap;
private Map<String,MutableInt> words = new HashMap<String,MutableInt>();
private Map<String,MutableInt> unks = new HashMap<String,MutableInt>();
private Map<Set<String>,MutableInt> bigrams = new HashMap<Set<String>,MutableInt>();
private static Alphabet<Label> lexAlphabet = new Alphabet<Label>();
private static BerkeleySignatureBuilder sig = new BerkeleySignatureBuilder(lexAlphabet);
private String trainingOut = new String();
private String testingOut = new String();
private String templateOut = new String();
public static void main(String[] args) throws IOException {
ArgParser parser = new ArgParser(GetFeatures.class);
parser.addClass(GetFeatures.class);
parser.addClass(CoNLL09Sentence.class);
try {
parser.parseArgs(args);
} catch (ParseException e) {
log.error(e.getMessage());
parser.printUsage();
System.exit(1);
}
setChars();
GetFeatures modelSpec = new GetFeatures();
modelSpec.run();
}
public void run() throws IOException {
preprocess();
knownWords = setDictionary(words);
knownUnks = setDictionary(unks);
// Currently not actually using bigram dictionary.
knownBigrams = setBigramDictionary(bigrams);
process();
}
public void preprocess() throws IOException {
makeOutFiles();
knownUnks.add("UNK");
CoNLL09FileReader cr = new CoNLL09FileReader(new File(trainingFile));
for (CoNLL09Sentence sent : cr) {
if (sent.size() > maxSentLength) {
maxSentLength = sent.size();
}
for (CoNLL09Token word : sent) {
for (int j = 0; j< word.getApreds().size(); j++) {
String[] splitRole = word.getApreds().get(j).split("-");
String role = splitRole[0].toLowerCase();
knownRoles.add(role);
}
String wordForm = word.getForm();
String cleanWord = normalize.clean(wordForm);
String unkWord = sig.getSignature(wordForm, word.getId(), language);
unkWord = normalize.escape(unkWord);
words = addWord(words, cleanWord);
unks = addWord(unks, unkWord);
if (!goldHead) {
knownPostags.add(word.getPpos());
} else {
knownPostags.add(word.getPos());
}
for (CoNLL09Token word2 : sent) {
String wordForm2 = word2.getForm();
String cleanWord2 = normalize.clean(wordForm2);
String unkWord2 = sig.getSignature(wordForm2, word2.getId(), language);
addBigrams(cleanWord, cleanWord2);
addBigrams(unkWord, unkWord2);
addBigrams(cleanWord, unkWord2);
addBigrams(unkWord, cleanWord2);
}
}
}
}
public void makeOutFiles() {
if (!note.equals("")) {
note = "." + note;
}
trainingOut = "train" + note;
templateOut = "template" + note;
testingOut = "test" + note;
}
public void process() throws IOException {
File trainOut = new File(trainingOut);
if (!trainOut.exists()) {
trainOut.createNewFile();
}
FileWriter trainFW = new FileWriter(trainOut.getAbsoluteFile());
BufferedWriter trainBW = new BufferedWriter(trainFW);
File template = new File(templateOut);
if (!template.exists()) {
template.createNewFile();
}
FileWriter templateFW = new FileWriter(template.getAbsoluteFile());
BufferedWriter templateBW = new BufferedWriter(templateFW);
File testOut = new File(testingOut);
if (!testOut.exists()) {
testOut.createNewFile();
}
FileWriter testFW = new FileWriter(testOut.getAbsoluteFile());
BufferedWriter testBW = new BufferedWriter(testFW);
featuresToPrint(trainingFile, trainBW, true);
trainBW.close();
printTemplate(templateBW);
templateBW.close();
featuresToPrint(testingFile, testBW, false);
testBW.close();
}
public void featuresToPrint(String inFile, BufferedWriter bw, boolean isTrain) throws IOException {
CoNLL09FileReader cr = new CoNLL09FileReader(new File(inFile));
int example = 0;
for (CoNLL09Sentence sent : cr) {
boolean hasPred = false;
Map<Set<Integer>,String> knownPairs = new HashMap<Set<Integer>,String>();
List<SrlEdge> srlEdges = sent.getSrlGraph().getEdges();
Set<Integer> knownPreds = new HashSet<Integer>();
// all the "Y"s
for (SrlEdge e : srlEdges) {
Integer a = e.getPred().getId();
hasPred = true;
knownPreds.add(a);
// all the args for that Y. Assigns one label for every arg it selects for.
//Map<Integer,String> knownArgs = new HashMap<Integer,String>();
for (SrlEdge e2 : e.getPred().getEdges()) {
String[] splitRole = e2.getLabel().split("-");
String role = splitRole[0].toLowerCase();
Integer b = e2.getArg().getId();
Set<Integer> key = new HashSet<Integer>();
key.add(a);
key.add(b);
knownPairs.put(key, role);
}
Set<String> variables = new HashSet<String>();
Set<String> features = new HashSet<String>();
System.out.println(example);
example++;
for (int i = 0; i < sent.size(); i++) {
for (int j = 0; j < sent.size();j++) {
Set<String> suffixes = getSuffixes(i, j, sent, knownPreds, isTrain);
variables = getVariables(i, j, sent, knownPairs, knownPreds, variables, isTrain);
features = getArgumentFeatures(i, j, suffixes, sent, features, isTrain);
}
}
if(hasPred) {
printOut(variables, features, example, bw);
}
}
}
}
// Naradowsky argument features.
public Set<String> getArgumentFeatures(int pidx, int aidx, Set<String> suffixes, CoNLL09Sentence sent, Set<String> feats, boolean isTrain) {
CoNLL09Token pred = sent.get(pidx);
CoNLL09Token arg = sent.get(aidx);
String predForm = decideForm(pred.getForm(), pidx);
String argForm = decideForm(arg.getForm(), aidx);
String predPos = pred.getPos();
String argPos = arg.getPos();
String dir;
int dist = Math.abs(aidx - pidx);
if (aidx > pidx)
dir = "RIGHT";
else if (aidx < pidx)
dir = "LEFT";
else
dir = "SAME";
Set<String> instFeats = new HashSet<String>();
instFeats.add("head_" + predForm + "dep_" + argForm + "_word");
instFeats.add("head_" + predPos + "_dep_" + argPos + "_pos");
instFeats.add("head_" + predForm + "_dep_" + argPos + "_wordpos");
instFeats.add("head_" + predPos + "_dep_" + argForm + "_posword");
instFeats.add("head_" + predForm + "_dep_" + argForm + "_head_" + predPos + "_dep_" + argPos + "_wordwordpospos");
instFeats.add("head_" + predPos + "_dep_" + argPos + "_dist_" + dist + "_posdist");
instFeats.add("head_" + predPos + "_dep_" + argPos + "_dir_" + dir + "_posdir");
instFeats.add("head_" + predPos + "_dist_" + dist + "_dir_" + dir + "_posdistdir");
instFeats.add("head_" + argPos + "_dist_" + dist + "_dir_" + dir + "_posdistdir");
instFeats.add("slen_" + sent.size());
instFeats.add("dir_" + dir);
instFeats.add("dist_" + dist);
instFeats.add("dir_dist_" + dir + dist);
instFeats.add("head_" + predForm + "_word");
instFeats.add("head_" + predPos + "_tag");
instFeats.add("arg_" + argForm + "_word");
instFeats.add("arg_" + argPos + "_tag");
for (String feat : instFeats) {
if (isTrain || allFeatures.contains(feat)) {
if (isTrain) {
//if (!allFeatures.contains(feat)) {
allFeatures.add(feat);
}
for (String suf : suffixes) {
feats.add(feat + suf);
}
}
}
return feats;
}
private String decideForm(String wordForm, int idx) {
if (!knownWords.contains(wordForm)) {
wordForm = sig.getSignature(wordForm, idx, language);
if (!knownUnks.contains(wordForm)) {
wordForm = "UNK";
return wordForm;
}
}
Iterator<Entry<String, String>> it = stringMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
wordForm = wordForm.replace((String) pairs.getKey(), (String) pairs.getValue());
}
return wordForm;
}
public Set<String> getVariables(int i, int j, CoNLL09Sentence sent, Map<Set<Integer>,String> knownPairs, Set<Integer> knownPreds, Set<String> variables, boolean isTrain) {
String variable;
// Syntactic head, from dependency parse.
int head = sent.get(j).getHead();
if (head != i) {
variable = "ARG Arg_" + Integer.toString(i) + "_" + Integer.toString(j) + "=False;";
} else {
variable = "ARG Arg_" + Integer.toString(i) + "_" + Integer.toString(j) + "=True;";
}
// Semantic relations.
Set<Integer> key = new HashSet<Integer>();
key.add(i);
key.add(j);
if (knownPreds.contains(j)) {
if (knownPairs.containsKey(key)) {
String label = knownPairs.get(key);
variable = "ROLE Role_" + Integer.toString(i) + "_" + Integer.toString(j) + "=" + label.toLowerCase() + ";";
} else {
variable = "ROLE Role_" + Integer.toString(i) + "_" + Integer.toString(j) + "=_;";
}
}
variables.add(variable);
return variables;
}
public Set<String> getSuffixes(int i, int j, CoNLL09Sentence sent, Set<Integer> knownPreds, boolean isTrain) {
Set<String> suffixes = new HashSet<String>();
// If this is testing data, or training data where i is a pred
if (!isTrain || knownPreds.contains(i)) {
suffixes.add("_role(Role_" + Integer.toString(i) + "_" + Integer.toString(j) + ");");
}
suffixes.add("_arg(Arg_" + Integer.toString(i) + "_" + Integer.toString(j) + ",Role_" + Integer.toString(i) + "_" + Integer.toString(j) + ");");
return suffixes;
}
public void printOut(Set<String> sentenceVariables, Set<String> sentenceFeatures, int example, BufferedWriter bw) throws IOException {
bw.write("//example " + Integer.toString(example));
bw.newLine();
bw.write("example:");
bw.newLine();
for (String var : sentenceVariables) {
bw.write(var);
bw.newLine();
}
bw.write("features:");
bw.newLine();
for (String feat : sentenceFeatures) {
bw.write(feat);
bw.newLine();
}
}
public void printTemplate(BufferedWriter tw) throws IOException {
StringBuilder sb = new StringBuilder();
String delim = "";
tw.write("types:");
tw.newLine();
sb.append("ROLE:=[");
for (String role : knownRoles) {
sb.append(delim).append(role);
delim = ",";
}
sb.append("]");
tw.write(sb.toString());
tw.newLine();
tw.newLine();
tw.write("features:");
tw.newLine();
for (String feature : allFeatures) {
tw.write(feature + "_role(ROLE):=[*]");
tw.newLine();
}
}
private static void setChars() {
// Really this would be nicer using guava...
stringMap = new HashMap<String,String>();
stringMap.put("1","2");
stringMap.put(".","_P_");
stringMap.put(",","_C_");
stringMap.put("'","_A_");
stringMap.put("%","_PCT_");
stringMap.put("-","_DASH_");
stringMap.put("$","_DOL_");
stringMap.put("&","_AMP_");
stringMap.put(":","_COL_");
stringMap.put(";","_SCOL_");
stringMap.put("\\/","_BSL_");
stringMap.put("/","_SL_");
stringMap.put("`","_QT_");
stringMap.put("?","_Q_");
stringMap.put("¿","_QQ_");
stringMap.put("=","_EQ_");
stringMap.put("*","_ST_");
stringMap.put("!","_E_");
stringMap.put("¡","_EE_");
stringMap.put("#","_HSH_");
stringMap.put("@","_AT_");
stringMap.put("(","_LBR_");
stringMap.put(")","_RBR_");
stringMap.put("\"","_QT1_");
stringMap.put("Á","_A_ACNT_");
stringMap.put("É","_E_ACNT_");
stringMap.put("Í","_I_ACNT_");
stringMap.put("Ó","_O_ACNT_");
stringMap.put("Ú","_U_ACNT_");
stringMap.put("Ü","_U_ACNT2_");
stringMap.put("Ñ","_N_ACNT_");
stringMap.put("á","_a_ACNT_");
stringMap.put("é","_e_ACNT_");
stringMap.put("í","_i_ACNT_");
stringMap.put("ó","_o_ACNT_");
stringMap.put("ú","_u_ACNT_");
stringMap.put("ü","_u_ACNT2_");
stringMap.put("ñ","_n_ACNT_");
stringMap.put("º","_deg_ACNT_");
}
private void addBigrams(String w1, String w2) {
HashSet<String> pair = new HashSet<String>(Arrays.asList(w1, w2));
MutableInt count = bigrams.get(pair);
if (count == null) {
bigrams.put(pair, new MutableInt());
} else {
count.increment();
}
}
private Map<String, MutableInt> addWord(Map<String,MutableInt> inputHash, String w) {
MutableInt count = inputHash.get(w);
if (count == null) {
inputHash.put(w, new MutableInt());
} else {
count.increment();
}
return inputHash;
}
private Set<Set<String>> setBigramDictionary(Map<Set<String>,MutableInt> inputHash) {
// Version of below, for bigrams.
Set<Set<String>> knownHash = new HashSet<Set<String>>();
Iterator<Entry<Set<String>, MutableInt>> it = inputHash.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
int count = ((MutableInt) pairs.getValue()).get();
if (count > cutoff) {
knownHash.add((Set<String>) pairs.getKey());
}
}
return knownHash;
}
private Set<String> setDictionary(Map<String,MutableInt> inputHash) {
Set<String> knownHash = new HashSet<String>();
Iterator<Entry<String, MutableInt>> it = inputHash.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
int count = ((MutableInt) pairs.getValue()).get();
if (count > cutoff) {
knownHash.add((String) pairs.getKey());
}
}
return knownHash;
}
public static class normalize {
private static final Pattern digits = Pattern.compile("\\d+");
private static final Pattern punct = Pattern.compile("[^A-Za-z0-9_ÁÉÍÓÚÜÑáéíóúüñ]");
public static String escape(String s) {
Iterator<Entry<String, String>> it = stringMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
String key = (String)entry.getKey();
String val = (String)entry.getValue();
s.replace(key,val);
}
return punct.matcher(s).replaceAll("_");
}
public static String norm_digits(String s) {
return digits.matcher(s).replaceAll("0");
}
public static String clean(String s) {
s = escape(s);
s = norm_digits(s.toLowerCase());
return s;
}
}
} |
package com.lightcrafts.image.types;
import java.awt.*;
import java.awt.color.ICC_Profile;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.image.*;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.BufferUnderflowException;
import java.nio.channels.FileChannel;
import java.util.List;
import com.lightcrafts.mediax.jai.*;
import org.w3c.dom.Document;
import com.lightcrafts.image.BadColorProfileException;
import com.lightcrafts.image.BadImageFileException;
import com.lightcrafts.image.ColorProfileException;
import com.lightcrafts.image.export.*;
import com.lightcrafts.image.ImageInfo;
import com.lightcrafts.image.metadata.*;
import com.lightcrafts.image.metadata.providers.PreviewImageProvider;
import com.lightcrafts.image.metadata.values.ImageMetaValue;
import com.lightcrafts.image.UnknownImageTypeException;
import com.lightcrafts.image.libs.InputStreamImageDataProvider;
import com.lightcrafts.image.libs.LCImageLibException;
import com.lightcrafts.image.libs.LCJPEGReader;
import com.lightcrafts.image.libs.LCJPEGWriter;
import com.lightcrafts.utils.bytebuffer.*;
import com.lightcrafts.utils.ColorProfileInfo;
import com.lightcrafts.utils.thread.ProgressThread;
import com.lightcrafts.utils.UserCanceledException;
import com.lightcrafts.utils.file.FileUtil;
import com.lightcrafts.utils.xml.XmlNode;
import com.lightcrafts.utils.xml.XMLException;
import com.lightcrafts.utils.xml.XMLUtil;
import com.lightcrafts.jai.JAIContext;
import com.lightcrafts.jai.opimage.CachedImage;
import static com.lightcrafts.image.libs.LCJPEGConstants.*;
import static com.lightcrafts.image.metadata.CoreTags.*;
import static com.lightcrafts.image.metadata.EXIFConstants.*;
import static com.lightcrafts.image.metadata.EXIFTags.*;
import static com.lightcrafts.image.metadata.ImageOrientation.ORIENTATION_UNKNOWN;
import static com.lightcrafts.image.types.JPEGConstants.*;
/**
* A <code>JPEGImageType</code> is-an {@link ImageType} for JPEG images.
*
* @author Paul J. Lucas [paul@lightcrafts.com]
*/
public class JPEGImageType extends ImageType implements TrueImageTypeProvider {
////////// public /////////////////////////////////////////////////////////
/** The singleton instance of <code>JPEGImageType</code>. */
public static final JPEGImageType INSTANCE = new JPEGImageType();
/**
* <code>ExportOptions</code> are {@link ImageFileExportOptions} for JPEG
* images.
*/
public static class ExportOptions extends ImageFileExportOptions {
////////// public /////////////////////////////////////////////////////
public final QualityOption quality;
/**
* Construct an <code>ExportOptions</code>.
*/
public ExportOptions() {
this( INSTANCE );
}
/**
* {@inheritDoc}
*/
@Override
public void readFrom( ImageExportOptionReader r ) throws IOException {
super.readFrom( r );
quality.readFrom( r );
}
/**
* {@inheritDoc}
*/
@Override
public void writeTo( ImageExportOptionWriter w ) throws IOException {
super.writeTo( w );
quality.writeTo( w );
}
////////// protected //////////////////////////////////////////////////
/**
* Construct an <code>ExportOptions</code>.
*
* @param instance The singleton instance of {@link ImageType} that
* this <code>ExportOptions</code> is for.
*/
protected ExportOptions( ImageType instance ) {
super( instance );
quality = new QualityOption( 85, this );
}
/**
* @deprecated
*/
@Override
protected void save(XmlNode node) {
super.save( node );
quality.save( node );
}
/**
* @deprecated
*/
@Override
protected void restore( XmlNode node ) throws XMLException {
super.restore( node );
try {
quality.restore(node);
}
catch (XMLException e) {
// Files saved with v4.1.6 cause this, just ignore it.
System.err.println("Failed to restore JPEG quality");
}
}
}
/**
* Checks whether the application can export to JPEG images.
*
* @return Always returns <code>true</code>.
*/
@Override
public boolean canExport() {
return true;
}
/**
* Gets all JPEG data segments having the given ID.
*
* @param imageInfo The image to get the segments for.
* @param segID The ID of the segments to get.
* @return Returns a {@link List} of {@link ByteBuffer}s where each
* {@link ByteBuffer} is the raw bytes of the segment or returns
* <code>null</code> if there are no such segments.
* @see #getAllSegments(ImageInfo,byte,JPEGSegmentFilter)
* @see #getFirstSegment(ImageInfo,byte)
* @see #getFirstSegment(ImageInfo,byte,JPEGSegmentFilter)
* @see JPEGImageInfo#getAllSegmentsFor(Byte,JPEGSegmentFilter)
*/
public static List<ByteBuffer> getAllSegments( ImageInfo imageInfo,
byte segID )
throws BadImageFileException, IOException, UnknownImageTypeException
{
return getAllSegments( imageInfo, segID, null );
}
/**
* Gets all JPEG data segments having the given ID that satisfy the given
* {@link JPEGSegmentFilter}.
*
* @param imageInfo The image to get the segments for.
* @param segID The ID of the segments to get.
* @param filter The {@link JPEGSegmentFilter} to use.
* @return Returns a {@link List} of {@link ByteBuffer}s where each
* {@link ByteBuffer} is the raw bytes of the segment or returns
* <code>null</code> if there are no such segments.
* @see #getAllSegments(ImageInfo,byte)
* @see #getFirstSegment(ImageInfo,byte)
* @see #getFirstSegment(ImageInfo,byte,JPEGSegmentFilter)
* @see JPEGImageInfo#getAllSegmentsFor(Byte,JPEGSegmentFilter)
*/
public static List<ByteBuffer> getAllSegments( ImageInfo imageInfo,
byte segID,
JPEGSegmentFilter filter )
throws BadImageFileException, IOException, UnknownImageTypeException
{
final AuxiliaryImageInfo auxInfo = imageInfo.getAuxiliaryInfo();
if ( !(auxInfo instanceof JPEGImageInfo) )
return null;
final JPEGImageInfo jpegInfo = (JPEGImageInfo)auxInfo;
return jpegInfo.getAllSegmentsFor( segID, filter );
}
/**
* {@inheritDoc}
*/
@Override
public String[] getExtensions() {
return EXTENSIONS;
}
/**
* Gets the first JPEG data segment having the given ID.
*
* @param imageInfo The image to get the segments for.
* @param segID The ID of the segments to get.
* @return Returns a {@link ByteBuffer} of the raw bytes of the segment or
* <code>null</code> if there is no such segment.
* @see #getAllSegments(ImageInfo,byte)
* @see #getAllSegments(ImageInfo,byte,JPEGSegmentFilter)
* @see #getFirstSegment(ImageInfo,byte,JPEGSegmentFilter)
* @see JPEGImageInfo#getFirstSegmentFor(Byte,JPEGSegmentFilter)
*/
public static ByteBuffer getFirstSegment( ImageInfo imageInfo, byte segID )
throws BadImageFileException, IOException, UnknownImageTypeException
{
return getFirstSegment( imageInfo, segID, null );
}
/**
* Gets the first JPEG data segment having the given ID that satisfies the
* given {@link JPEGSegmentFilter}.
*
* @param imageInfo The image to get the segments for.
* @param segID The ID of the segments to get.
* @param filter The {@link JPEGSegmentFilter} to use.
* @return Returns a {@link ByteBuffer} of the raw bytes of the segment or
* <code>null</code> if there is no such segment.
* @see #getAllSegments(ImageInfo,byte)
* @see #getAllSegments(ImageInfo,byte,JPEGSegmentFilter)
* @see #getFirstSegment(ImageInfo,byte)
* @see JPEGImageInfo#getFirstSegmentFor(Byte,JPEGSegmentFilter)
*/
public static ByteBuffer getFirstSegment( ImageInfo imageInfo, byte segID,
JPEGSegmentFilter filter )
throws BadImageFileException, IOException, UnknownImageTypeException
{
final AuxiliaryImageInfo auxInfo = imageInfo.getAuxiliaryInfo();
if ( !(auxInfo instanceof JPEGImageInfo) )
return null;
final JPEGImageInfo jpegInfo = (JPEGImageInfo)auxInfo;
return jpegInfo.getFirstSegmentFor( segID, filter );
}
/**
* {@inheritDoc}
*/
@Override
public Dimension getDimension( ImageInfo imageInfo )
throws BadImageFileException, IOException, UnknownImageTypeException
{
Dimension d = null;
try {
LCJPEGReader reader = null;
try {
final String path = imageInfo.getFile().getAbsolutePath();
reader = new LCJPEGReader( path );
d = new Dimension( reader.getWidth(), reader.getHeight() );
}
finally {
if ( reader != null )
reader.dispose();
}
}
catch ( LCImageLibException e ) {
// ignore
}
return d;
}
/**
* {@inheritDoc}
*/
@Override
public ICC_Profile getICCProfile( ImageInfo imageInfo )
throws BadImageFileException, ColorProfileException, IOException,
UnknownImageTypeException
{
final List<ByteBuffer> iccSegBufs = getAllSegments(
imageInfo, JPEG_APP2_MARKER, new ICCProfileJPEGSegmentFilter()
);
if ( iccSegBufs == null ) {
final String path = imageInfo.getFile().getAbsolutePath();
try {
switch ( new LCJPEGReader(path).getColorsPerPixel() ) {
case 1:
return JAIContext.gray22Profile;
case 3: // sRGB or uncalibrated
return getICCProfileFromEXIF( imageInfo );
case 4:
return JAIContext.CMYKProfile;
default:
throw new BadColorProfileException( path );
}
} catch (LCImageLibException e) {
// ignore
}
}
final byte[] iccProfileData;
try {
iccProfileData = assembleICCProfile( iccSegBufs );
}
catch ( BufferUnderflowException e ) {
throw new BadImageFileException( imageInfo.getFile() );
}
catch ( IllegalArgumentException e ) {
throw new BadImageFileException( imageInfo.getFile() );
}
try {
return ICC_Profile.getInstance( iccProfileData );
}
catch ( IllegalArgumentException e ) {
throw new BadColorProfileException( imageInfo.getFile().getName() );
}
}
/**
* {@inheritDoc}
*/
@Override
public PlanarImage getImage( ImageInfo imageInfo, ProgressThread thread )
throws BadImageFileException, IOException, UserCanceledException,
UnknownImageTypeException
{
return getImage( imageInfo, thread, 0, 0 );
}
/**
* Gets a JPEG image from the file given by {@link ImageInfo#getFile()}.
*
* @param imageInfo The {@link ImageInfo} to get the actual image from.
* @param thread The thread that will do othe getting.
* @param maxWidth The maximum width of the image to get, rescaling if
* necessary. A value of 0 means don't scale.
* @param maxHeight The maximum height of the image to get, rescaling if
* necessary. A value of 0 means don't scale.
* @return Returns said image data.
*/
public PlanarImage getImage( ImageInfo imageInfo, ProgressThread thread,
int maxWidth, int maxHeight )
throws BadImageFileException, IOException, UserCanceledException,
UnknownImageTypeException
{
try {
ICC_Profile profile;
try {
profile = getICCProfile( imageInfo );
}
catch ( ColorProfileException e ) {
profile = null;
}
final LCJPEGReader reader = new LCJPEGReader(
imageInfo.getFile().getAbsolutePath(), maxWidth, maxHeight,
(JPEGImageInfo)imageInfo.getAuxiliaryInfo()
);
final PlanarImage image = reader.getImage(
thread, profile != null ? new ICC_ColorSpace( profile ) : null
);
assert image instanceof CachedImage
&& image.getTileWidth() == JAIContext.TILE_WIDTH
&& image.getTileHeight() == JAIContext.TILE_HEIGHT;
return image;
}
catch ( LCImageLibException e ) {
throw new BadImageFileException( imageInfo.getFile(), e );
}
}
/**
* Gets a JPEG image from the given byte array.
*
* @param buf The byte array to get the JPEG image from.
* @param offset The offset into the buffer where the JPEG image data
* starts.
* @param length The length in bytes of the JPEG image.
* @param cs The {@link ColorSpace} to use. It may be <code>null</code>.
* @param maxWidth The maximum width of the image to get, rescaling if
* necessary. A value of 0 means don't scale.
* @param maxHeight The maximum height of the image to get, rescaling if
* necessary. A value of 0 means don't scale.
* @return Returns said image.
*/
public static RenderedImage getImageFromBuffer( byte[] buf, int offset,
int length, ColorSpace cs,
int maxWidth,
int maxHeight )
throws BadImageFileException
{
final InputStream is = new ByteArrayInputStream( buf, offset, length );
return getImageFromInputStream( is, cs, maxWidth, maxHeight );
}
/**
* Gets a JPEG image from the given buffer.
*
* @param buf The {@link LCByteBuffer} to get the JPEG image from.
* @param offsetValue The {@link ImageMetaValue} specifying the offset into
* the buffer where the JPEG image data starts.
* @param offsetAdjustment An adjustment to be added to
* <code>offsetValue</code> since some values need adjustment due to file
* headers.
* @param lengthValue The {@link ImageMetaValue} specifying the length in
* bytes of the JPEG image.
* @param maxWidth The maximum width of the image to get, rescaling if
* necessary. A value of 0 means don't scale.
* @param maxHeight The maximum height of the image to get, rescaling if
* necessary. A value of 0 means don't scale.
* @return Returns said image.
*/
public static RenderedImage getImageFromBuffer( LCByteBuffer buf,
ImageMetaValue offsetValue,
int offsetAdjustment,
ImageMetaValue lengthValue,
int maxWidth,
int maxHeight )
throws BadImageFileException
{
return getImageFromBuffer(
buf, offsetValue, offsetAdjustment, lengthValue, null,
maxWidth, maxHeight
);
}
/**
* Gets a JPEG image from the given buffer.
*
* @param buf The {@link LCByteBuffer} to get the JPEG image from.
* @param offsetValue The {@link ImageMetaValue} specifying the offset into
* the buffer where the JPEG image data starts.
* @param offsetAdjustment An adjustment to be added to
* <code>offsetValue</code> since some values need adjustment due to file
* headers.
* @param lengthValue The {@link ImageMetaValue} specifying the length in
* bytes of the JPEG image.
* @param cs The {@link ColorSpace} to use. It may be <code>null</code>.
* @param maxWidth The maximum width of the image to get, rescaling if
* necessary. A value of 0 means don't scale.
* @param maxHeight The maximum height of the image to get, rescaling if
* necessary. A value of 0 means don't scale.
* @return Returns said image.
*/
public static RenderedImage getImageFromBuffer( LCByteBuffer buf,
ImageMetaValue offsetValue,
int offsetAdjustment,
ImageMetaValue lengthValue,
ColorSpace cs,
int maxWidth,
int maxHeight )
throws BadImageFileException
{
if ( buf == null || offsetValue == null || lengthValue == null )
return null;
final int offset = offsetValue.getIntValue();
final int length = lengthValue.getIntValue();
if ( offset < 0 || length <= 0 )
return null;
return getImageFromBuffer(
buf, offset + offsetAdjustment, length, cs, maxWidth, maxHeight
);
}
/**
* Gets a JPEG image from the given buffer.
*
* @param buf The {@link LCByteBuffer} to get the JPEG image from.
* @param offset The offset into the buffer where the JPEG image data
* starts.
* @param length The length in bytes of the JPEG image.
* @param cs The {@link ColorSpace} to use. It may be <code>null</code>.
* @param maxWidth The maximum width of the image to get, rescaling if
* necessary. A value of 0 means don't scale.
* @param maxHeight The maximum height of the image to get, rescaling if
* necessary. A value of 0 means don't scale.
* @return Returns said image.
*/
public static RenderedImage getImageFromBuffer( LCByteBuffer buf,
int offset, int length,
ColorSpace cs,
int maxWidth,
int maxHeight )
throws BadImageFileException
{
final byte[] imageBuf;
try {
imageBuf = buf.getBytes( offset, length );
}
catch ( Exception e ) {
// Assume that any exception generated by the above is because the
// image is corrupt.
throw new BadImageFileException( e );
}
final InputStream is = new ByteArrayInputStream( imageBuf );
return getImageFromInputStream( is, cs, maxWidth, maxHeight );
}
/**
* Gets a JPEG image from the given {@link InputStream}.
*
* @param stream The {@link InputStream} to get the image from.
* @param cs The {@link ColorSpace} to use.
* @param maxWidth The maximum width of the image to get, rescaling if
* necessary. A value of 0 means don't scale.
* @param maxHeight The maximum height of the image to get, rescaling if
* necessary. A value of 0 means don't scale.
* @return Returns said image.
*/
public static RenderedImage getImageFromInputStream( InputStream stream,
ColorSpace cs,
int maxWidth,
int maxHeight )
throws BadImageFileException
{
try {
final LCJPEGReader reader = new LCJPEGReader(
new InputStreamImageDataProvider( stream ),
maxWidth, maxHeight
);
return reader.getImage( cs );
}
catch ( UserCanceledException e ) {
// This never actually happens.
return null;
}
catch ( Exception e ) {
// Assume that any other exception generated by the above is
// because the image is corrupt.
throw new BadImageFileException( e );
}
}
/**
* {@inheritDoc}
*/
@Override
public String getName() {
return "JPEG";
}
/**
* {@inheritDoc}
*/
@Override
public RenderedImage getPreviewImage( ImageInfo imageInfo, int maxWidth,
int maxHeight )
throws BadImageFileException, ColorProfileException, IOException,
UnknownImageTypeException
{
final ImageMetadata metadata = imageInfo.getMetadata();
final ImageMetadataDirectory dir =
metadata.findProviderOf( PreviewImageProvider.class );
if ( dir != null )
return ((PreviewImageProvider)dir).getPreviewImage(
imageInfo, maxWidth, maxHeight
);
return super.getPreviewImage( imageInfo, maxWidth, maxHeight );
}
/**
* {@inheritDoc}
*/
@Override
public RenderedImage getThumbnailImage( ImageInfo imageInfo )
throws BadImageFileException, ColorProfileException, IOException,
UnknownImageTypeException
{
final ImageMetadataDirectory dir =
imageInfo.getMetadata().getDirectoryFor( EXIFDirectory.class );
if ( dir == null ) {
// This should never be null, but just in case ...
return null;
}
final ByteBuffer exifSegBuf =
getFirstSegment( imageInfo, JPEG_APP1_MARKER );
if ( exifSegBuf == null )
return null;
final ICC_Profile profile = getICCProfile( imageInfo );
return getImageFromBuffer(
new ArrayByteBuffer( exifSegBuf ),
dir.getValue( EXIF_JPEG_INTERCHANGE_FORMAT ),
EXIF_HEADER_START_SIZE,
dir.getValue( EXIF_JPEG_INTERCHANGE_FORMAT_LENGTH ),
profile != null ? new ICC_ColorSpace( profile ) : null,
0, 0
);
}
/**
* {@inheritDoc}
*/
@Override
public final ImageType getTrueImageTypeOf( ImageInfo imageInfo )
throws BadImageFileException, IOException
{
try {
ByteBuffer buf = getFirstSegment( imageInfo, JPEG_APP4_MARKER );
if ( buf != null ) {
SidecarJPEGImageType sidecar = SidecarJPEGImageType.INSTANCE;
// sanity checking on the contents
try {
if ( sidecar.getLZNDocument(buf) != null )
return sidecar;
}
catch ( IOException e ) {
// not lzn APP4 contents
}
}
}
catch ( UnknownImageTypeException e ) {
// should never happen at this stage
}
return null;
}
/**
* {@inheritDoc}
*/
@Override
public Document getXMP( ImageInfo imageInfo )
throws BadImageFileException, IOException, UnknownImageTypeException
{
final ByteBuffer xmpSegBuf = getFirstSegment(
imageInfo, JPEG_APP1_MARKER, new XMPJPEGSegmentFilter()
);
if ( xmpSegBuf == null)
return null;
byte[] xmpBytes;
if ( xmpSegBuf.hasArray() ) {
xmpBytes = xmpSegBuf.array();
}
else {
xmpBytes = new byte[xmpSegBuf.remaining()];
xmpSegBuf.get(xmpBytes);
}
final ByteArrayInputStream bis = new ByteArrayInputStream(
xmpBytes, JPEG_XMP_HEADER_SIZE,
xmpBytes.length - JPEG_XMP_HEADER_SIZE
);
return XMLUtil.readDocumentFrom( bis );
}
/**
* {@inheritDoc}
*/
@Override
public boolean hasFastPreview() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
public JPEGImageInfo newAuxiliaryInfo( ImageInfo imageInfo )
throws BadImageFileException, IOException
{
return new JPEGImageInfo(
imageInfo,
JPEG_APP1_MARKER, // EXIF or XMP
JPEG_APP2_MARKER, // ICC profile
JPEG_APP4_MARKER, // LightZone
JPEG_APPD_MARKER, // IPTC
JPEG_APPE_MARKER // Adobe
);
}
/**
* {@inheritDoc}
*/
@Override
public ExportOptions newExportOptions() {
return new ExportOptions();
}
/**
* {@inheritDoc}
*/
@Override
public void putImage( ImageInfo imageInfo, PlanarImage image,
ImageExportOptions options, Document lznDoc,
ProgressThread thread ) throws IOException {
final ExportOptions jpegOptions = (ExportOptions)options;
ImageMetadata metadata;
try {
metadata = imageInfo.getMetadata();
}
catch ( BadImageFileException e ) {
metadata = new ImageMetadata( this );
}
catch ( UnknownImageTypeException e ) {
metadata = new ImageMetadata( this );
}
try {
final int numComponents = image.getColorModel().getNumComponents();
final int colorSpace =
LCJPEGWriter.getColorSpaceFromNumComponents( numComponents );
if ( colorSpace == CS_UNKNOWN )
throw new LCImageLibException(
"Unsupported number of components: " + numComponents
);
final LCJPEGWriter writer = new LCJPEGWriter(
options.getExportFile().getPath(),
image.getWidth(), image.getHeight(),
numComponents, colorSpace,
jpegOptions.quality.getValue(),
jpegOptions.resolution.getValue(),
jpegOptions.resolutionUnit.getValue()
);
ICC_Profile profile = ColorProfileInfo.getExportICCProfileFor(
jpegOptions.colorProfile.getValue()
);
if ( profile == null )
profile = JAIContext.sRGBExportColorProfile;
writer.setICCProfile( profile );
if ( lznDoc != null ) {
final byte[] buf = XMLUtil.encodeDocument( lznDoc, false );
writer.writeSegment( JPEG_APP4_MARKER, buf );
}
writer.putMetadata( metadata );
writer.putImage( image, thread );
}
catch ( LCImageLibException e ) {
final IOException ioe = new IOException( "JPEG export failed" );
ioe.initCause( e );
throw ioe;
}
}
/**
* Reads all the metadata for a given JPEG image.
*
* @param imageInfo The image to read the metadata from.
*/
@Override
public void readMetadata( ImageInfo imageInfo )
throws BadImageFileException, IOException, UnknownImageTypeException
{
BadImageFileException exceptionOnHold = null;
////////// EXIF
final ByteBuffer exifSegBuf = getFirstSegment(
imageInfo, JPEG_APP1_MARKER, new EXIFJPEGSegmentFilter()
);
if ( exifSegBuf != null ) {
final ImageMetadataReader reader = new EXIFMetadataReader(
imageInfo, new ArrayByteBuffer( exifSegBuf ), false
);
try {
reader.readMetadata();
}
catch ( BadImageFileException e ) {
// Catch any BadImageFileException and hold it so we can
// continue and try to read additional metadata.
exceptionOnHold = e;
}
}
////////// IPTC
final ByteBuffer iptcSegBuf = getFirstSegment(
imageInfo, JPEG_APPD_MARKER, new IPTCJPEGSegmentFilter()
);
if ( iptcSegBuf != null ) {
final ImageMetadataReader reader = new IPTCMetadataReader(
imageInfo, new ArrayByteBuffer( iptcSegBuf ), this
);
try {
reader.readMetadata();
}
catch ( BadImageFileException e ) {
if ( exceptionOnHold == null )
exceptionOnHold = e;
}
}
////////// XMP
final Document xmpDoc = getXMP( imageInfo );
if ( xmpDoc != null ) {
final ImageMetadata xmpMetadata =
XMPMetadataReader.readFrom( xmpDoc );
imageInfo.getCurrentMetadata().mergeFrom( xmpMetadata );
}
if ( exceptionOnHold != null )
throw exceptionOnHold;
}
/**
* Writes the metadata for JPEG files back to the metadata inside the JPEG
* itself.
*
* @param imageInfo The image to write the metadata for.
*/
@Override
public void writeMetadata( ImageInfo imageInfo )
throws BadImageFileException, IOException, UnknownImageTypeException
{
// We check to see if a foo_jpg.xmp file exists that was used in
// LightZone versions 2.2-2.4. If so, we migrate the orientation and
// rating metadata and delete the XMP file.
final File xmpFile = new File( imageInfo.getXMPFilename() );
final boolean xmpExists = xmpFile.exists();
final ImageMetadata metadata = imageInfo.getCurrentMetadata();
ImageMetadata xmpMetadata = null;
final Document oldXMPDoc = INSTANCE.getXMP( imageInfo );
if ( oldXMPDoc != null )
xmpMetadata = XMPMetadataReader.readFrom( oldXMPDoc );
////////// Core directory
final ImageMetadataDirectory coreDir =
metadata.getDirectoryFor( CoreDirectory.class );
final ImageMetaValue orientation =
coreDir.getValue( CORE_IMAGE_ORIENTATION );
if ( orientation != null && (orientation.isEdited() || xmpExists) ) {
final ImageOrientation xmpOrientation = xmpMetadata != null ?
xmpMetadata.getOrientation() : ORIENTATION_UNKNOWN;
modifyMetadata(
imageInfo, EXIF_ORIENTATION, orientation.getShortValue(),
xmpOrientation != ORIENTATION_UNKNOWN ?
xmpOrientation.getTIFFConstant() : NO_META_VALUE,
false
);
orientation.clearEdited();
}
final ImageMetaValue rating = coreDir.getValue( CORE_RATING );
if ( rating != null && (rating.isEdited() || xmpExists) ) {
final short xmpRating = xmpMetadata != null ?
(short)xmpMetadata.getRating() : NO_META_VALUE;
final short newRating = rating.getShortValue();
boolean removeRating = false;
if ( newRating == 0 ) {
metadata.removeValues( CoreDirectory.class, CORE_RATING );
metadata.removeValues( SubEXIFDirectory.class, EXIF_MS_RATING );
removeRating = true;
}
modifyMetadata(
imageInfo, EXIF_MS_RATING, newRating, xmpRating, removeRating
);
rating.clearEdited();
}
// TODO: must do something about unrating a photo
////////// IPTC directory
final ImageMetadataDirectory iptcDir =
metadata.getDirectoryFor( IPTCDirectory.class );
if ( iptcDir != null && iptcDir.isChanged() ) {
// Write both the binary and XMP forms of IPTC metadata: the binary
// form to enable non-XMP-aware applications to read it and the XMP
// form to write all the metadata, i.e., the additional IPTC tags
// present in XMP.
final byte[] iptcSegBuf = ((IPTCDirectory)iptcDir).encode( true );
Document newXMPDoc = metadata.toXMP( true, true );
if ( oldXMPDoc != null )
newXMPDoc = XMPUtil.mergeMetadata( newXMPDoc, oldXMPDoc );
final byte[] xmpSegBuf = XMLUtil.encodeDocument( newXMPDoc, true );
new JPEGCopier().copyAndInsertSegments(
imageInfo.getFile(),
new NotJPEGSegmentFilter(
new OrJPEGSegmentFilter(
new IPTCJPEGSegmentFilter(),
new XMPJPEGSegmentFilter()
)
),
new JPEGCopier.SegmentInfo( JPEG_APP1_MARKER, xmpSegBuf ),
new JPEGCopier.SegmentInfo( JPEG_APPD_MARKER, iptcSegBuf )
);
iptcDir.clearEdited();
}
CoreDirectory.syncEditableMetadata( metadata );
if ( xmpExists )
xmpFile.delete();
}
////////// protected //////////////////////////////////////////////////////
/**
* Construct a <code>JPEGImageType</code>.
*/
protected JPEGImageType() {
// do nothing
}
////////// private ////////////////////////////////////////////////////////
/**
* An {@link EXIFSegmentFinder} is-a {@link JPEGParserEventHandler} that
* finds the EXIF segment of a JPEG file.
*/
private static final class EXIFSegmentFinder
implements JPEGParserEventHandler {
/**
* {@inheritDoc}
*/
@Override
public boolean gotSegment( byte segID, int segLength, File jpegFile,
LCByteBuffer buf ) throws IOException {
if ( segID == JPEG_APP1_MARKER &&
buf.getEquals( "Exif", "ASCII" ) ) {
m_exifSegBuf = new LCMappedByteBuffer(
jpegFile, buf.position() - 4, segLength - 4,
FileChannel.MapMode.READ_WRITE
);
return false;
}
return true;
}
////////// package ////////////////////////////////////////////////////
/**
* Gets the EXIF segment, if any, of the JPEG file.
*
* @param jpegFile The JPEG file to get the EXIF segment of.
* @return Returns an {@link LCMappedByteBuffer} mapped to the EXIF
* segment or <code>null</code> if there is no EXIF segment.
*/
LCMappedByteBuffer getEXIFSegmentOf( File jpegFile )
throws BadImageFileException, IOException
{
final LCMappedByteBuffer buf = new LCMappedByteBuffer( jpegFile );
try {
JPEGParser.parse( this, jpegFile, buf );
return m_exifSegBuf;
}
finally {
buf.close();
}
}
////////// private ////////////////////////////////////////////////////
/** The EXIF segment data is put here. */
private LCMappedByteBuffer m_exifSegBuf;
}
/**
* An <code>InPlaceModifier</code> attempts to perform an in-place
* modification of the value of the given EXIF tag in a JPEG file. The
* modification will fail if it doesn't contain an existing value for the
* given EXIF tag.
*/
private static final class InPlaceModifier
extends EXIFMetadataReader {
/**
* The {@link EXIFParser} just parsed a tag: see if it's the one whose
* value we want to modify in-place: if it is, modify it and stop.
*
* @param tagID The tag ID.
* @param fieldType Not used.
* @param numValues Not used.
* @param byteCount Not used.
* @param valueOffset The offset of the first value.
* @param valueOffsetAdjustment Not used.
* @param subdirOffset Not used.
* @param imageFile Not used.
* @param buf The {@link LCByteBuffer} the raw metadata is in.
* @param dir Not used.
*/
@Override
public void gotTag( int tagID, int fieldType, int numValues,
int byteCount, int valueOffset,
int valueOffsetAdjustment, int subdirOffset,
File imageFile, LCByteBuffer buf,
ImageMetadataDirectory dir ) throws IOException {
if ( tagID == m_tagID ) {
buf.position( valueOffset );
buf.putShort( m_newValue );
m_exifParser.stopParsing();
m_succeeded = true;
}
}
////////// package ////////////////////////////////////////////////////
/**
* Construct an <code>InPlaceModifier</code>.
*
* @param jpegInfo The JPEG image to modify.
* @param exifSegBuf The {@link LCByteBuffer} containing the raw bytes
* of the EXIF segment.
*/
InPlaceModifier( ImageInfo jpegInfo, LCByteBuffer exifSegBuf ) {
super( jpegInfo, exifSegBuf, false );
}
/**
* Attempt to modify the metadata in-place.
*
* @param tagID The tag ID of the value to modify.
* @param newValue The new value.
* @return Returns <code>true</code> only if the in-place modification
* succeeded.
*/
boolean modify( int tagID, short newValue )
throws BadImageFileException, IOException
{
m_newValue = newValue;
m_tagID = tagID;
readMetadata();
if ( m_succeeded ) {
// Ensure the modification time of the file is updated so the
// browser will notice.
FileUtil.touch( m_imageInfo.getFile() );
}
return m_succeeded;
}
////////// private ////////////////////////////////////////////////////
private short m_newValue;
private boolean m_succeeded;
private int m_tagID;
}
/**
* A <code>JPEGCopier</code> is-an {@link JPEGParserEventHandler} to copy
* a JPEG file and insert/replace segment(s) during the copy.
*/
private static final class JPEGCopier implements JPEGParserEventHandler {
////////// public /////////////////////////////////////////////////////
/**
* A <code>SegmentInfo</code> holds information about a segment to
* insert.
*
* @see JPEGCopier#copyAndInsertSegments(File,JPEGSegmentFilter,SegmentInfo...)
*/
static final class SegmentInfo {
final byte m_segID;
final byte[] m_segData;
SegmentInfo( byte segID, byte[] segData ) {
m_segID = segID;
m_segData = segData;
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean gotSegment( byte segID, int segLength, File jpegFile,
LCByteBuffer buf ) throws IOException {
if ( segID == JPEG_SOS_MARKER ) {
// We've run into the start of the JPEG image data: copy the
// remainder of the JPEG file as-is; but first insert the new
// segment(s) if we haven't already done so.
if ( m_segInfo != null )
insertSegments();
buf.skipBytes( -2 );
copy( buf, m_raf, buf.remaining() );
m_copied = true;
return false;
}
// Check whether the current segment should be copied.
if ( m_segFilter != null ) {
// Extract a small chunk of the segment data, enough for the
// filter to work on.
final int chunkSize = Math.min( segLength, 32 );
final byte[] chunk = buf.getBytes( buf.position(), chunkSize );
final ByteBuffer chunkBuf = ByteBuffer.wrap( chunk );
if ( !m_segFilter.accept( segID, chunkBuf ) )
return true; // don't copy the current segment
}
// Insert the segment(s) if we haven't already done so.
if ( m_segInfo != null )
insertSegments();
// Copy the current segment as-is.
buf.skipBytes( -4 );
copy( buf, m_raf, segLength + 4 );
return true;
}
////////// package ////////////////////////////////////////////////////
/**
* Copy a JPEG file inserting a new segment(s).
*
* @param jpegFile The JPEG file to copy.
* @param segFilter The {@link JPEGSegmentFilter} to use to filter out
* segments that should not be copied.
* @param segments The segments to insert.
*/
void copyAndInsertSegments( File jpegFile, JPEGSegmentFilter segFilter,
SegmentInfo... segments )
throws BadImageFileException, IOException
{
m_segFilter = segFilter;
m_segInfo = segments;
final LCMappedByteBuffer buf = new LCMappedByteBuffer( jpegFile );
File newFile = null;
try {
try {
newFile = File.createTempFile(
"LZcp", null, jpegFile.getParentFile()
);
m_raf = new RandomAccessFile( newFile, "rw" );
m_raf.writeByte( JPEG_MARKER_BYTE );
m_raf.writeByte( JPEG_SOI_MARKER );
JPEGParser.parse( this, jpegFile, buf );
}
finally {
if ( m_raf != null )
m_raf.close();
buf.close();
if ( m_copied ) {
// In order to rename an image file, we must make sure
// the files involved are closed first.
ImageInfo.closeAll();
// Ensure that the buf.close() takes effect.
for (int i = 0; !jpegFile.delete() && i < 5; i++) {
System.gc();
}
FileUtil.renameFile( newFile, jpegFile );
}
}
}
finally {
// We need to ensure newFile is deleted regardless of whether
// (1) the copy failed or (2) the copy succeeded but the rename
// failed; hence this extra try/finally.
if ( newFile != null )
newFile.delete();
}
}
////////// private ////////////////////////////////////////////////////
/**
* Copies bytes from the given {@link LCByteBuffer} to the given
* {@link RandomAccessFile}. Bytes are read starting at the buffer's
* current position and written to the file's current position. Upon
* completion, the buffer's and file's positions are advanced by the
* number of bytes copied.
*
* @param from The {@link LCByteBuffer} to copy from.
* @param to The {@link RandomAccessFile} to copy to.
* @param byteCount The number of bytes to copy.
*/
private static void copy( LCByteBuffer from, RandomAccessFile to,
int byteCount ) throws IOException {
final byte[] chunk = new byte[ Math.min( byteCount, 64 * 1024 ) ];
while ( byteCount > 0 ) {
final int bytesToCopy = Math.min( byteCount, chunk.length );
from.get( chunk, 0, bytesToCopy );
to.write( chunk, 0, bytesToCopy );
byteCount -= bytesToCopy;
}
}
/**
* Inserts the new segments.
*/
private void insertSegments() throws IOException {
for ( SegmentInfo seg : m_segInfo )
if ( seg.m_segData != null && seg.m_segData.length > 0 ) {
m_raf.writeByte( JPEG_MARKER_BYTE );
m_raf.writeByte( seg.m_segID );
m_raf.writeShort( seg.m_segData.length + 2 );
m_raf.write( seg.m_segData );
}
m_segInfo = null;
}
/**
* This is set to <code>true</code> only when the copy has been
* successfully completed.
*/
private boolean m_copied;
/**
* The {@link RandomAccessFile} to copy to.
*/
private RandomAccessFile m_raf;
/**
* The {@link JPEGSegmentFilter} to use, if any.
*/
private JPEGSegmentFilter m_segFilter;
/**
* The segments to insert.
*/
private SegmentInfo[] m_segInfo;
}
/**
* Modify the EXIF metadata of a JPEG image as non-destructively and as
* efficiently as possible.
*
* @param jpegInfo The JPEG image to modify the EXIF metadata of.
* @param tagID The EXIF tag whose value is to be modified.
* @param newValue The new value.
* @param oldXMPValue The old value from XMP or 0 if none.
* @param removeValue If <code>true</code>, remove the value for the given
* tag instead.
*/
public static void modifyMetadata( ImageInfo jpegInfo, int tagID,
short newValue, short oldXMPValue,
boolean removeValue )
throws BadImageFileException, IOException, UnknownImageTypeException
{
final File jpegFile = jpegInfo.getFile();
ImageMetadata metadata = jpegInfo.getCurrentMetadata();
final Document oldXMPDoc = INSTANCE.getXMP( jpegInfo );
// We can attempt cases 1 and 2 only if there's no XMP metadata for the
// JPEG. If there is XMP metadata, we need to modify that instead
// (because XMP metadata always wins).
if ( oldXMPValue == NO_META_VALUE ) {
// Case 1a: see if the JPEG has no EXIF metadata at all: if not,
// create a new JPEG containing a newly constructed EXIF segment.
// Case 1b: if we're removing the value, we also need to create a
// new JPEG containing a newly constructed EXIF segment.
final LCMappedByteBuffer exifSegBuf =
new EXIFSegmentFinder().getEXIFSegmentOf( jpegFile );
if ( exifSegBuf == null || removeValue ) {
metadata = metadata.prepForExport( INSTANCE, true );
final ByteBuffer newEXIFSegBuf =
EXIFEncoder.encode( metadata, true );
new JPEGCopier().copyAndInsertSegments(
jpegInfo.getFile(), null,
new JPEGCopier.SegmentInfo(
JPEG_APP1_MARKER, newEXIFSegBuf.array()
)
);
return;
}
// Case 2: see if the JPEG's EXIF metadata contains the tag: if so,
// modify it in-place.
try {
final InPlaceModifier modifier =
new InPlaceModifier( jpegInfo, exifSegBuf );
if ( modifier.modify( tagID, newValue ) )
return;
}
finally {
exifSegBuf.close();
}
}
// Case 3: the JPEG has EXIF metadata, but no relevant tag: we're
// forced to modify the XMP metadata instead (and leave the existing
// EXIF metadata alone), so create a new JPEG containing the modified
// XMP metadata.
Document newXMPDoc = metadata.toXMP( true, true );
if ( oldXMPDoc != null )
newXMPDoc = XMPUtil.mergeMetadata( newXMPDoc, oldXMPDoc );
final byte[] newXMPSegBuf = XMLUtil.encodeDocument( newXMPDoc, true );
new JPEGCopier().copyAndInsertSegments(
jpegInfo.getFile(),
new NotJPEGSegmentFilter( new XMPJPEGSegmentFilter() ),
new JPEGCopier.SegmentInfo( JPEG_APP1_MARKER, newXMPSegBuf )
);
}
/**
* Assemble a complete ICC profile from one or more chunks of data
* extracted from one or more APP2 segments in a JPEG file.
*
* @param list The {@link List} of {@link ByteBuffer}s containing the
* chunks of ICC profile data.
* @return Returns the raw ICC profile data (with the header stripped) or
* <code>null</code> if none.
*/
private static byte[] assembleICCProfile( List<ByteBuffer> list ) {
if ( list.size() == 1 ) {
// The easy and common case of just 1 segment for the entire
// profile.
final ByteBuffer buf = list.get( 0 );
return ByteBufferUtil.getBytes(
buf,
ICC_PROFILE_HEADER_SIZE,
buf.limit() - ICC_PROFILE_HEADER_SIZE
);
}
// The harder case of a profile being split across multiple segments.
final ByteBuffer firstBuf = list.get( 0 );
final int numSegments = firstBuf.get( 13 );
final ByteBuffer[] sortedList = new ByteBuffer[ numSegments ];
int totalProfileSize = 0;
// Although they probably are, we don't assume that the profile chunks
// are in the file in order. Each chunk has its correct index, so we
// sort the chunks.
// While we're iterating over all the chunks anyway, also compute the
// total profile size.
for ( ByteBuffer buf : list ) {
final int chunkIndex = buf.get( 12 ) - 1;
sortedList[ chunkIndex ] = buf;
totalProfileSize += buf.limit() - ICC_PROFILE_HEADER_SIZE;
}
// Finally, assemble the chunks into a single, complete ICC profile.
final byte[] iccProfileData = new byte[ totalProfileSize ];
int dataOffset = 0;
for ( ByteBuffer buf : sortedList ) {
final int chunkSize = buf.limit() - ICC_PROFILE_HEADER_SIZE;
ByteBufferUtil.getBytes(
buf, ICC_PROFILE_HEADER_SIZE, iccProfileData, dataOffset,
chunkSize
);
dataOffset += chunkSize;
}
return iccProfileData;
}
/**
* Gets the {@link ICC_Profile} specified in the EXIF metadata for the
* ColorSpace tag.
*
* @param imageInfo The image to get the EXIF metadata from.
* @return If ColorSpace contains "sRGB", returns that profile; if it
* contains "uncalibrated", returns the Adobe RGB profile. This may not be
* correct in all cases, but it's better than using the sRGB profile. If
* there is no EXIF metadata or it doesn't contain the ColorSpace tag,
* returns <code>null</code>.
*/
private static ICC_Profile getICCProfileFromEXIF( ImageInfo imageInfo )
throws BadImageFileException, IOException
{
try {
final ImageMetaValue colorSpace =
imageInfo.getMetadata().getValue(
EXIFDirectory.class, EXIF_COLOR_SPACE
);
if ( colorSpace != null )
switch ( colorSpace.getIntValue() ) {
case 1: // sRGB
return JAIContext.sRGBColorProfile;
default: // uncalibrated or something else
return JAIContext.adobeRGBProfile;
}
}
catch ( UnknownImageTypeException e ) {
// ignore
}
return null;
}
/**
* All the possible filename extensions for JPEG files. All must be lower
* case and the preferred one must be first.
*/
private static final String EXTENSIONS[] = {
"jpg", "jpe", "jpeg"
};
/**
* The value that is used to indicate that no pre-existing metadata value
* is present.
*/
private static final short NO_META_VALUE = 0;
}
/* vim:set et sw=4 ts=4: */ |
package gui.centerarea;
import control.CountUtilities;
import static gui.centerarea.TimetableBlock.DraggingTypes.Move;
import gui.misc.TweakingHelper;
import gui.root.RootCenterArea;
import javafx.event.EventHandler;
import javafx.geometry.Bounds;
import javafx.geometry.Point2D;
import javafx.scene.Cursor;
import javafx.scene.Node;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Label;
import javafx.scene.effect.BlendMode;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.GaussianBlur;
import javafx.scene.image.ImageView;
import javafx.scene.image.WritableImage;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import lombok.Getter;
/**
* Class that resembles a draggable, resizable block inside the timetable,
* whose sole purpose is to display information.
* Highly volatile. Do not poke the dragging-dragon too much.
*/
public abstract class TimetableBlock extends Pane {
public enum DraggingTypes { Move, Resize_Top, Resize_Right, Resize_Bottom, Resize_Left }
/**
* Styling variables.
* For tweaking the styling.
*/
private double verticalBorderSize = 6.0;
private double margin = 5.0;
private double blurRadius = 20.0;
/**
* Content variables.
* Directly displaying block content, such as the name.
*/
@Getter
private Label titleNormalLabel;
@Getter
private Label titleDraggedLabel;
@Getter
private Label countNormalLabel;
@Getter
private Label countDraggedLabel;
@Getter
private Label descriptionNormalLabel;
@Getter
private Label descriptionDraggedLabel;
/**
* Misc variables.
* For dragging, panes etc
*/
@Getter
private TimetableBlock thisBlock;
@Getter
private Pane draggedPane; // rootCenterArea shown when dragging
@Getter
private Pane feedbackPane; // rootCenterArea shown when snapping
@Getter
private VBox contentPane; // content of this rootCenterArea
@Getter
private VBox draggedContentPane; // content of rootCenterArea shown when dragging
// for feedbackPane
@Getter
private WritableImage feedbackImage; // content of feedbackPane (is just an image, sneaky!)
@Getter
private GaussianBlur gaussianBlur;
@Getter
private ColorAdjust darken;
@Getter
private double dragXOffset;
@Getter
private double dragYOffset;
@Getter
private RootCenterArea rootCenterArea;
@Getter
private boolean dragging;
@Getter
private DraggingTypes draggingType;
@Getter
private double mouseCurrentXPosition;
@Getter
private double mouseCurrentYPosition;
@Getter
private double mouseCurrentXMovement;
@Getter
private double mouseCurrentYMovement;
@Getter
private ShotBlock parentBlock;
@Getter
private double startingY;
/**
* Constructor for TimetableBlock class.
* @param pane - the parent rootCenterArea.
* @param parent - the parent node
*/
TimetableBlock(RootCenterArea pane, ShotBlock parent) {
this.dragging = false;
this.thisBlock = this;
this.parentBlock = parent;
this.rootCenterArea = pane;
}
/**
* Inits the necessary eventhandlers for this block.
* @param horizontalAllowed - specifies if horizontal dragging (between timelines)
* is allowed
*/
void addMouseEventHandlers(boolean horizontalAllowed) {
// mouse event handlers
setOnMousePressed(getOnPressedHandler(horizontalAllowed));
setOnMouseDragged(getOnDraggedHandler(horizontalAllowed));
setOnMouseReleased(getOnreleaseHandler(horizontalAllowed));
setOnMouseMoved(getOnMouseMovedHandler());
}
/**
* Helper function to initialize normal (visible) blocks.
*/
void initNormalPane() {
setBlendMode(BlendMode.MULTIPLY);
// content rootCenterArea for our
// actual rootCenterArea, which holds content (text and stuff)
contentPane = new VBox();
contentPane.minWidthProperty().bind(widthProperty());
contentPane.maxWidthProperty().bind(widthProperty());
contentPane.minHeightProperty().bind(heightProperty());
contentPane.maxHeightProperty().bind(heightProperty());
// add some labels etc
titleNormalLabel = initTitleLabel(contentPane);
countNormalLabel = initCountLabel(contentPane);
descriptionNormalLabel = initDescriptionLabel(contentPane);
descriptionNormalLabel.setWrapText(true);
addWithClipRegion(contentPane, this);
this.getStyleClass().add("block_Background");
this.getContentPane().getStyleClass().add("block_Foreground");
this.setStyle("-fx-background-color: "
+ TweakingHelper.STRING_PRIMARY + ";"
+ "-fx-border-color: "
+ TweakingHelper.STRING_SECONDARY + ";");
this.getContentPane().setStyle("-fx-background-color: "
+ TweakingHelper.STRING_QUADRATORY + ";"
+ "-fx-border-color: "
+ TweakingHelper.STRING_TERTIARY + ";");
}
/**
* Helper function to initialize dragged (visible when dragging) blocks.
* @param anchorPane the AnchorPane drag on
*/
void initDraggedPane(AnchorPane anchorPane) {
// draggedPane itself
draggedPane = new Pane();
draggedPane.setVisible(false);
// dragged content rootCenterArea which mirrors
// our content rootCenterArea, shown when dragging.
draggedContentPane = new VBox() ;
draggedContentPane.minWidthProperty().bind(draggedPane.widthProperty());
draggedContentPane.maxWidthProperty().bind(draggedPane.widthProperty());
draggedContentPane.minHeightProperty().bind(draggedPane.heightProperty());
draggedContentPane.maxHeightProperty().bind(draggedPane.heightProperty());
// add some labels etc
titleDraggedLabel = initTitleLabel(draggedContentPane);
countDraggedLabel = initCountLabel(draggedContentPane);
descriptionDraggedLabel = initCountLabel(draggedContentPane);
descriptionDraggedLabel.setWrapText(true);
// dropshadow shown underneath dragged rootCenterArea
DropShadow ds = new DropShadow(15.0, 5.0, 5.0, Color.GRAY);
this.getDraggedPane().setEffect(ds);
addWithClipRegion(draggedContentPane, draggedPane);
anchorPane.getChildren().add(draggedPane);
this.getDraggedPane().getStyleClass().add("block_Background");
this.getDraggedContentPane().getStyleClass().add("block_Foreground");
this.getDraggedPane().setStyle("-fx-background-color: "
+ TweakingHelper.STRING_PRIMARY + ";"
+ "-fx-border-color: "
+ TweakingHelper.STRING_SECONDARY + ";");
this.getDraggedContentPane().setStyle("-fx-background-color: "
+ TweakingHelper.STRING_QUADRATORY + ";"
+ "-fx-border-color: "
+ TweakingHelper.STRING_TERTIARY + ";");
}
/**
* Helper function to initialize feedback (the snapping) blocks.
* @param gridPane the gridpane to have the feedback on
*/
public void initFeedbackPane(GridPane gridPane) {
feedbackPane = new Pane();
feedbackPane.setVisible(false);
gaussianBlur = new GaussianBlur(15.0);
darken = new ColorAdjust(0, -0.4, -0.2, 0.2);
gridPane.add(feedbackPane, 0, 0);
}
/**
* Add content to rootCenterArea, but with a clipping region bound to the rootCenterArea's size.
* @param content the Pane in which content is located.
* @param pane the Pane in which the vbox is located.
*/
private void addWithClipRegion(Node content, Pane pane) {
Rectangle clipRegion = new Rectangle(); // clip region to restrict content
clipRegion.widthProperty().bind(pane.widthProperty());
clipRegion.heightProperty().bind(pane.heightProperty().subtract(verticalBorderSize));
content.setClip(clipRegion);
pane.getChildren().add(content);
}
/**
* Helper function to add title labels to panes.
* @param vbox rootCenterArea to add this label to
* @return the label in question.
*/
private Label initTitleLabel(VBox vbox) {
Label res = new Label(parentBlock.getName());
res.maxWidthProperty().bind(this.widthProperty());
res.getStyleClass().add("block_Text_Title");
res.setStyle("-fx-text-fill:" + TweakingHelper.STRING_SECONDARY + ";");
vbox.getChildren().add(res);
return res;
}
/**
* Helper function to add the description label to panes.
* @param vbox - rootCenterArea to add this label to
* @return - the label in question
*/
private Label initDescriptionLabel(VBox vbox) {
Label res = new Label(parentBlock.getDescription());
res.maxWidthProperty().bind(this.widthProperty());
res.getStyleClass().add("block_Text_Normal");
res.setStyle("-fx-text-fill:" + TweakingHelper.STRING_TERTIARY + ";");
vbox.getChildren().add(res);
return res;
}
/**
* Helper function to add count labels to panes.
* @param vbox rootCenterArea to add this label to
* @return the label in question.
*/
private Label initCountLabel(VBox vbox) {
String labelText = parentBlock.getBeginCount() + " - " + parentBlock.getEndCount();
Label res = new Label(labelText);
res.maxWidthProperty().bind(this.widthProperty());
res.getStyleClass().add("block_Text_Normal");
res.setStyle("-fx-text-fill:" + TweakingHelper.STRING_TERTIARY + ";");
vbox.getChildren().add(res);
return res;
}
/**
* Get handler for on mouse moved (handling cursors).
* @return - the handler
*/
private EventHandler<MouseEvent> getOnMouseMovedHandler() {
return e -> {
DraggingTypes dragType = findEdgeZone(e);
Cursor newCursor = null;
switch (dragType) {
case Move:
newCursor = Cursor.CLOSED_HAND;
break;
case Resize_Bottom:
case Resize_Top:
newCursor = Cursor.N_RESIZE;
break;
case Resize_Left:
case Resize_Right:
newCursor = Cursor.E_RESIZE;
break;
default:
newCursor = Cursor.DEFAULT;
}
if (getCursor() != newCursor) {
setCursor(newCursor);
}
};
}
/**
* Event handler for on mouse pressed.
* @param isCameraTimeline true when action is on the CameraTimeline
* @return - the eventhandler
*/
private EventHandler<MouseEvent> getOnPressedHandler(boolean isCameraTimeline) {
return e -> {
onPressedHandlerHelper(e);
GridPane gridPane;
if (isCameraTimeline) {
gridPane = getRootCenterArea().getMainTimeLineGridPane();
TimelinesGridPane.setColumnIndex(
feedbackPane, TimelinesGridPane.getColumnIndex(thisBlock));
TimelinesGridPane.setRowIndex(
feedbackPane, TimelinesGridPane.getRowIndex(thisBlock));
TimelinesGridPane.setRowSpan(
feedbackPane, TimelinesGridPane.getRowSpan(thisBlock));
} else {
gridPane = getRootCenterArea().getDirectorGridPane();
DirectorGridPane.setColumnIndex(
feedbackPane, DirectorGridPane.getColumnIndex(thisBlock));
DirectorGridPane.setRowIndex(
feedbackPane, DirectorGridPane.getRowIndex(thisBlock));
DirectorGridPane.setRowSpan(
feedbackPane, DirectorGridPane.getRowSpan(thisBlock));
}
// Set startingY if dragging
double blockY = gridPane.localToScene(thisBlock.getLayoutX(),
thisBlock.getLayoutY()).getY();
if (draggingType == DraggingTypes.Resize_Top) {
startingY = blockY + thisBlock.getHeight();
} else if (draggingType == DraggingTypes.Resize_Bottom) {
startingY = blockY;
}
};
}
/**
* Helper method for on Mouse Pressed.
* @param e the MouseEvent.
*/
private void onPressedHandlerHelper(MouseEvent e) {
// init correct object ordering
feedbackPane.toFront();
draggedPane.toFront();
this.toFront();
// init draggingpane
draggingType = findEdgeZone(e);
draggedPane.setLayoutX(getLayoutX());
draggedPane.setLayoutY(getLayoutY());
// Init feedbackpane
feedbackImage = this.snapshot(new SnapshotParameters(), null);
ImageView image = new ImageView(feedbackImage);
image.fitHeightProperty().bind(feedbackPane.heightProperty());
darken.setInput(gaussianBlur);
image.setEffect(darken);
feedbackPane.getChildren().add(image);
feedbackPane.toBack();
feedbackPane.setVisible(true);
// init position
mouseCurrentXPosition = e.getSceneX();
mouseCurrentYPosition = e.getSceneY();
}
/**
* Event handler for on mouse dragged.
* @param isCameraTimeline - specifies if horizontal dragging
* (between timelines) is allowed
* @return - the eventhandler
*/
private EventHandler<MouseEvent> getOnDraggedHandler(boolean isCameraTimeline) {
return e -> {
if (!dragging) {
dragXOffset = e.getX();
dragYOffset = e.getY();
dragging = true;
draggedPane.setVisible(true);
draggedPane.setPrefHeight(getHeight());
draggedPane.setMinHeight(getHeight());
draggedPane.setMaxHeight(getHeight());
draggedPane.setPrefWidth(getWidth());
thisBlock.setVisible(false);
}
onMouseDraggedHelper(e, isCameraTimeline);
e.consume();
};
}
/**
* Event handler for on mouse release.
* @param isCameraTimeline true if the action is on a CameraTimeline
* @return - the event handler
*/
private EventHandler<MouseEvent> getOnreleaseHandler(boolean isCameraTimeline) {
return e -> {
draggedPane.setVisible(false);
thisBlock.setVisible(true);
if (dragging) {
snapPane(thisBlock, feedbackPane, e.getSceneY(), draggingType, isCameraTimeline);
}
feedbackPane.setVisible(false);
feedbackPane.getChildren().remove(0);
dragging = false;
// Update ShotBlock
if (isCameraTimeline) {
double newBeginCount = TimelinesGridPane.getRowIndex(thisBlock)
/ (double) CountUtilities.NUMBER_OF_CELLS_PER_COUNT;
parentBlock.setBeginCount(newBeginCount, false);
parentBlock.setEndCount(newBeginCount + TimelinesGridPane.getRowSpan(thisBlock)
/ (double) CountUtilities.NUMBER_OF_CELLS_PER_COUNT, false);
} else {
double newBeginCount = DirectorGridPane.getRowIndex(thisBlock)
/ (double) CountUtilities.NUMBER_OF_CELLS_PER_COUNT;
parentBlock.setBeginCount(newBeginCount, false);
parentBlock.setEndCount(newBeginCount + DirectorGridPane.getRowSpan(thisBlock)
/ (double) CountUtilities.NUMBER_OF_CELLS_PER_COUNT, false);
}
this.fireEvent(parentBlock.getShotBlockUpdatedEvent());
};
}
/**
* Helper function for MouseDragged event. Normal (actual dragging) part.
* @param event the mousedrag event in question.
* @param isCameraTimeline - specifies if horizontal dragging
* (between timelines) is allowed
*/
private void onMouseDraggedHelper(MouseEvent event, boolean isCameraTimeline) {
double x = event.getSceneX();
double y = event.getSceneY();
// Fix dragging out of grid
if (draggingType == DraggingTypes.Resize_Bottom
|| draggingType == DraggingTypes.Resize_Top) {
GridPane gridPane;
if (isCameraTimeline) {
gridPane = getRootCenterArea().getMainTimeLineGridPane();
} else {
gridPane = getRootCenterArea().getDirectorGridPane();
}
Bounds sceneBounds = gridPane.localToScene(gridPane.getLayoutBounds());
if (y < sceneBounds.getMinY()) {
y = sceneBounds.getMinY();
}
}
mouseCurrentXMovement = x - mouseCurrentXPosition;
mouseCurrentYMovement = y - mouseCurrentYPosition;
// determine what kind of dragging we're going to do, and handle it.
if (draggingType == DraggingTypes.Resize_Bottom || draggingType == DraggingTypes.Resize_Top
|| (draggingType == DraggingTypes.Move && !isCameraTimeline)) {
onMouseDraggedHelperVertical(x, y, isCameraTimeline);
} else if (draggingType == Move) {
onMouseDraggedHelperNormal(x, y, isCameraTimeline);
}
// set feedbackpane
if (snapPane(feedbackPane, draggedPane, y, draggingType, isCameraTimeline)) {
feedbackPane.setVisible(true);
} else {
feedbackPane.setVisible(false);
}
mouseCurrentXPosition = x;
mouseCurrentYPosition = y;
}
/**
* Snap the targetregion to a grid using the model provided by the mappingPane.
* @param targetRegion - the target region to snap
* @param mappingPane - the model mappingPane to follow while snapping
* @param y - the Y coordinate of the mouse during this snap
* @param dragType - The type of drag used while snapping (move, resize)
* @param isCameraTimeline true if the action is on the CameraTimeline
* @return - boolean that indicates if the snap was possible and completed
*/
private boolean snapPane(Region targetRegion, Region mappingPane,
double y, DraggingTypes dragType, boolean isCameraTimeline) {
// set feedback rootCenterArea
double yCoordinate;
double xCoordinate;
if (dragType == Move) {
yCoordinate = y - dragYOffset;
} else {
yCoordinate = y;
}
xCoordinate = mappingPane.localToScene(mappingPane.getBoundsInLocal()).getMinX()
+ mappingPane.getWidth() / 2;
ScrollableGridPane gridPane;
if (isCameraTimeline) {
gridPane = rootCenterArea.getMainTimeLineGridPane();
} else {
gridPane = rootCenterArea.getDirectorGridPane();
}
SnappingPane myPane = gridPane.getMyPane(xCoordinate, yCoordinate);
if (myPane != null) {
int numCounts = (int) Math.round(mappingPane.getHeight()
/ gridPane.getVerticalElementSize());
if (myPane.isBottomHalf() && dragType == DraggingTypes.Resize_Top) {
numCounts = (int) Math.round((mappingPane.getHeight() - 5)
/ gridPane.getVerticalElementSize());
}
if (myPane.isBottomHalf() && (dragType == DraggingTypes.Resize_Top
|| dragType == Move)) {
GridPane.setRowIndex(targetRegion, myPane.getRow() + 1);
} else if (dragType == Move || dragType == DraggingTypes.Resize_Top) {
GridPane.setRowIndex(targetRegion, myPane.getRow());
}
GridPane.setColumnIndex(targetRegion, myPane.getColumn());
GridPane.setRowSpan(targetRegion, Math.max(numCounts, 1));
return true;
}
return false;
}
/**
* Helper function for MouseDragged event. Normal (actual dragging) part.
* @param x - the x coordinate needed to process the vertical dragging
* @param y - the y coordinate needed to process the vertical dragging
* @param isCameraTimeline true if the action is in the CameraTimeline
*/
private void onMouseDraggedHelperNormal(double x, double y, boolean isCameraTimeline) {
AnchorPane parentPane;
if (isCameraTimeline) {
parentPane = rootCenterArea.getMainTimeLineAnchorPane();
} else {
parentPane = rootCenterArea.getDirectorAnchorPane();
}
Bounds parentBounds = parentPane.localToScene(parentPane.getBoundsInLocal());
draggedPane.setLayoutX(x - parentBounds.getMinX() - dragXOffset);
draggedPane.setLayoutY(y - parentBounds.getMinY() - dragYOffset);
}
/**
* Helper function for MouseDragged event. Vertical part.
* @param x - the x coordinate needed to process the vertical dragging
* @param y - the y coordinate needed to process the vertical dragging
* @param isCameraTimeline true if the action is in the CameraTimeline
*/
private void onMouseDraggedHelperVertical(double x, double y, boolean isCameraTimeline) {
double newLayoutY = 0;
double newPrefHeight = 0;
AnchorPane anchorPane;
ScrollableGridPane gridPane;
if (isCameraTimeline) {
anchorPane = rootCenterArea.getMainTimeLineAnchorPane();
gridPane = rootCenterArea.getMainTimeLineGridPane();
} else {
anchorPane = rootCenterArea.getDirectorAnchorPane();
gridPane = rootCenterArea.getDirectorGridPane();
}
Point2D bounds = anchorPane.sceneToLocal(x, y);
if (thisBlock.draggingType == DraggingTypes.Resize_Top) {
newPrefHeight = startingY - y;
newLayoutY = bounds.getY();
} else if (thisBlock.draggingType == DraggingTypes.Resize_Bottom) {
newLayoutY = anchorPane.sceneToLocal(0, startingY).getY();
newPrefHeight = bounds.getY() - newLayoutY;
} else if (thisBlock.draggingType == DraggingTypes.Move && !isCameraTimeline) {
Bounds parentBounds = anchorPane.localToScene(anchorPane.getBoundsInLocal());
newLayoutY = y - parentBounds.getMinY() - dragYOffset;
newPrefHeight = getHeight();
}
if (newPrefHeight < gridPane.getVerticalElementSize()) {
newPrefHeight = gridPane.getVerticalElementSize();
if (draggingType == DraggingTypes.Resize_Top) {
newLayoutY = gridPane.sceneToLocal(0,
startingY).getY() - newPrefHeight;
}
}
draggedPane.setLayoutY(newLayoutY);
draggedPane.setPrefHeight(newPrefHeight);
draggedPane.setMinHeight(newPrefHeight);
draggedPane.setMaxHeight(newPrefHeight);
}
/**
Find out in what area of a block (0,1,2,3,4) the mouse is pressed.
0 is the center, 1 is top, 2 is right, 3 is bottom, 4 is left.
Changing margin size (see top of file) makes the side areas thicker.
@param event The MouseEvent to read for this.
@return int to what area of a block mouse is pressed in.
*/
private DraggingTypes findEdgeZone(MouseEvent event) {
if (event.getY() < margin) {
return DraggingTypes.Resize_Top;
} else if (event.getX() > getWidth() - margin) {
// Horizontal resizing disabled for now.
// return DraggingTypes.Resize_Right;
return Move;
} else if (event.getY() > getHeight() - margin) {
return DraggingTypes.Resize_Bottom;
} else if (event.getX() < margin) {
// Horizontal resizing disabled for now.
// return DraggingTypes.Resize_Left;
return Move;
} else {
return Move;
}
}
} |
package i5.las2peer.security;
import java.io.Serializable;
import java.util.LinkedList;
import java.util.Vector;
import i5.las2peer.communication.Message;
import i5.las2peer.communication.MessageException;
import i5.las2peer.execution.L2pServiceException;
import i5.las2peer.logging.NodeObserver.Event;
import i5.las2peer.p2p.AgentNotKnownException;
import i5.las2peer.p2p.Node;
import i5.las2peer.p2p.TimeoutException;
import i5.las2peer.persistency.EncodingFailedException;
import i5.las2peer.tools.SerializationException;
/**
* A Mediator acts on behalf of an {@link PassphraseAgent}. This necessary e.g. for remote
* users logged in via a {@link i5.las2peer.api.Connector} to collect incoming messages from the
* P2P network and transfer it to the connector.
* <br>
* Two ways for message handling are provided: Register a {@link MessageHandler} that will be called for each
* received message. Multiple MessageHandlers are possible (for example for different message contents).
* The second way to handle messages is to get pending messages from the Mediator directly via the provided methods.
* Handling then has to be done via the calling entity (for example a service).
*
*/
public class Mediator implements MessageReceiver {
private LinkedList<Message> pending = new LinkedList<Message>();
private Agent myAgent;
private Node runningAt = null;
private Vector<MessageHandler> registeredHandlers = new Vector<MessageHandler>();
/**
* Creates a new mediator.
*
* @param a
* @throws L2pSecurityException
*/
public Mediator(Agent a) throws L2pSecurityException {
if (a.isLocked())
throw new L2pSecurityException("You need to unlock the private key of the agent for mediating.");
myAgent = a;
}
/**
* Gets (and removes) the next pending message.
*
* @return the next collected message
*/
public Message getNextMessage() {
if (pending.size() == 0) {
return null;
}
return pending.pollFirst();
}
/**
* Does this mediator have pending messages?
*
* @return true, if messages have arrived
*/
public boolean hasMessages() {
return pending.size() > 0;
}
@Override
public void receiveMessage(Message message, Context c)
throws MessageException {
if (message.getRecipientId() != myAgent.getId())
throw new MessageException("I'm not responsible for the receiver (something went very wrong)!");
try {
message.open(myAgent, c);
// START
// This part enables message answering for all messages that were sent to an (UserAgent) mediator.
// Disable this section to reduce network traffic
if (getMyNode() != null) { // This line is needed to allow the tests to work (since they do not have a
// node..)
try {
Message response = new Message(message, "thank you");
response.setSendingNodeId(getMyNode().getNodeId());
getMyNode().sendMessage(response, null);
} catch (EncodingFailedException e) {
throw new MessageException("Unable to send response ", e);
} catch (SerializationException e) {
throw new MessageException("Unable to send response ", e);
}
}
// END
} catch (L2pSecurityException e) {
throw new MessageException("Unable to open message because of security problems! ", e);
} catch (AgentNotKnownException e) {
throw new MessageException(
"Sender unkown (since this is the receiver). Has the sending node gone offline? ", e);
}
if (!workOnMessage(message, c))
pending.add(message);
}
/**
* Method for message reception treatment.
* Will call all registered {@link MessageHandler}s for message handling.
*
* A return value of true indicates, that the received message has been treated by a MessageHandler and
* does not need further storage for later use (and will not be added to pending messages).
*
* @param message
* @param context
*
* @return true, if a message had been treated successfully
*/
public boolean workOnMessage(Message message, Context context) {
for (int i = 0; i < registeredHandlers.size(); i++) {
try {
if (registeredHandlers.get(i).handleMessage(message, context))
return true;
} catch (Exception e) {
runningAt.observerNotice(Event.MESSAGE_FAILED, runningAt.getNodeId(), this,
"Exception in MessageHandler " + registeredHandlers.get(i) + ": " + e);
}
}
return false;
}
/**
* Grants access to the node this Mediator is registered to.
*
* @return the node this Mediator is running at
*/
protected Node getMyNode() {
return runningAt;
}
@Override
public long getResponsibleForAgentId() {
return myAgent.getId();
}
@Override
public void notifyRegistrationTo(Node node) {
runningAt = node;
}
@Override
public void notifyUnregister() {
runningAt = null;
}
/**
* Invokes a service method (in the network) for the mediated agent.
*
* @param service
* @param method
* @param parameters
* @param preferLocal if a local running service should be preferred
*
* @return result of the method invocation
*
* @throws L2pSecurityException
* @throws InterruptedException
* @throws TimeoutException
* @throws L2pServiceException
* @throws AgentNotKnownException
*/
public Serializable invoke(String service, String method, Serializable[] parameters, boolean preferLocal)
throws L2pSecurityException, InterruptedException, TimeoutException, AgentNotKnownException,
L2pServiceException {
if (runningAt.hasService(service)) {
if (!preferLocal && runningAt.isBusy()) {
// local node is not prefered and busy so we try global
// this invocation may come back if there is no other node
return runningAt.invokeGlobally(myAgent, service, method, parameters);
} else {
// local node is prefered or not busy and got the service
// this means there is no need to produce networking overhead
return runningAt.invokeLocally(myAgent.getId(), service, method, parameters);
}
} else {
// service is not known locally => invokeGlobally
return runningAt.invokeGlobally(myAgent, service, method, parameters);
}
}
/**
* Gets the number of waiting messages.
*
* @return number of waiting messages
*/
public int getNumberOfWaiting() {
return pending.size();
}
/**
* Registers a MessageHandler for message processing.
*
* Message handlers will be used for handling incoming messages in the order of
* registration.
*
* @param handler
*/
public void registerMessageHandler(MessageHandler handler) {
if (handler == null)
throw new NullPointerException();
if (registeredHandlers.contains(handler))
return;
registeredHandlers.add(handler);
}
/**
* Unregisters a handler from this mediator.
*
* @param handler
*/
public void unregisterMessageHandler(MessageHandler handler) {
registeredHandlers.remove(handler);
}
/**
* Unregisters all handlers of the given class.
*
* @param cls
*
* @return number of successfully removed message handlers
*/
public int unregisterMessageHandlerClass(@SuppressWarnings("rawtypes") Class cls) {
int result = 0;
Vector<MessageHandler> newHandlers = new Vector<MessageHandler>();
for (int i = 0; i < registeredHandlers.size(); i++)
if (!cls.isInstance(registeredHandlers.get(i))) {
newHandlers.add(registeredHandlers.get(i));
} else
result++;
registeredHandlers = newHandlers;
return result;
}
/**
* Unregisters all handlers of the given class.
*
* @param classname
*
* @return number of successfully removed message handlers
*/
public int unregisterMessageHandlerClass(String classname) {
try {
return unregisterMessageHandlerClass(Class.forName(classname));
} catch (Exception e) {
// if the class cannot be found, there won't be any instances of it registered here...
return 0;
}
}
/**
* Is the given message handler registered at this mediator?
*
* @param handler
*
* @return true, if at least one message handler is registered to this mediator
*/
public boolean hasMessageHandler(MessageHandler handler) {
return registeredHandlers.contains(handler);
}
/**
* Has this mediator a registered message handler of the given class?
*
* @param cls
* @return true, if this mediator has a message handler of the given class
*/
public boolean hasMessageHandlerClass(@SuppressWarnings("rawtypes") Class cls) {
for (MessageHandler handler : registeredHandlers)
if (cls.isInstance(handler))
return true;
return false;
}
} |
package io.projectreactor;
import java.net.URI;
import reactor.ipc.netty.http.server.HttpServer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.codec.BodyInserters;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.web.reactive.function.RouterFunction;
import org.springframework.web.reactive.function.RouterFunctions;
import static org.springframework.http.HttpStatus.FOUND;
import static org.springframework.web.reactive.function.RequestPredicates.GET;
import static org.springframework.web.reactive.function.RouterFunctions.route;
import static org.springframework.web.reactive.function.ServerResponse.ok;
import static org.springframework.web.reactive.function.ServerResponse.status;
/**
* Main Application for the Project Reactor home site.
*/
public class Application {
public static void main(String... args) throws InterruptedException {
HttpHandler httpHandler = RouterFunctions.toHttpHandler(routes());
HttpServer.create("localhost")
.newHandler(new ReactorHttpHandlerAdapter(httpHandler))
.doOnNext(d -> System.out.println("Server started on "+d.address()))
.block()
.onClose()
.block();
}
private static RouterFunction<?> routes() { |
package jp.co.flect.sql;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import jp.co.flect.sql.Condition.LogicalOp;
import jp.co.flect.sql.Condition.ComparisionOp;
import jp.co.flect.sql.Condition.CompoundCondition;
import jp.co.flect.sql.Condition.Combine;
/**
* SELECT<br>
* (Selectable)
* join
*/
public class SelectBuilder implements Selectable {
/** offset */
public static final int OFFSET_PARAM = -1;
/** limit */
public static final int LIMIT_PARAM = -1;
private SelectBuilder parent;
private String aliasPrefix = "";
private char quoteChar = 0;
private TableInfo mainTable;
private List<Select> selects = new ArrayList<Select>();
private List<Join> joins = null;
private Where where = null;
private List<OrderByEntry> orderBy = null;
private List<Column> groupBy = null;
private ForUpdate forUpdate = null;
private boolean distinct = false;
private int limit = 0;
private int offset = 0;
/** ResultSet */
private int[] rsTypes = null;
/**
* FROMSelectBuilder
*/
public SelectBuilder(Selectable table) {
this.mainTable = new TableInfo(table, "A");
}
/**
* FROM
*/
public Selectable getMainTable() {
return mainTable.getTable();
}
/**
* SELECT DISTINCT
*/
public SelectBuilder distinct() {
return distinct(true);
}
/**
* SELECT DISTINCT
*/
public SelectBuilder distinct(boolean b) {
this.distinct = b;
return this;
}
/**
* SELECT<br>
* @param field
*/
public SelectBuilder select(String field) {
Selectable t = searchTable(field);
return select(new Column(t, field));
}
/**
* SELECT<br>
* @param table
* @param field
*/
public SelectBuilder select(Selectable table, String field) {
return select(new Column(table, field));
}
/**
* SELECT<br>
* @param sel
*/
public SelectBuilder select(Select sel) {
this.selects.add(sel);
this.rsTypes = null;
return this;
}
/**
* ORDER BY()<br>
* @param field
*/
public SelectBuilder orderByAsc(String field) {
return orderBy(field, true);
}
/**
* ORDER BY()<br>
* @param field
*/
public SelectBuilder orderByDesc(String field) {
return orderBy(field, false);
}
/**
* ORDER BY<br>
* @param field
* @param asc true
*/
public SelectBuilder orderBy(String field, boolean asc) {
Selectable t = searchTable(field);
return orderBy(new Column(t, field), asc);
}
/**
* ORDER BY()<br>
* @param table
* @param field
*/
public SelectBuilder orderByAsc(Selectable t, String field) {
return orderBy(t, field, true);
}
/**
* ORDER BY()<br>
* @param table
* @param field
*/
public SelectBuilder orderByDesc(Selectable t, String field) {
return orderBy(t, field, false);
}
/**
* ORDER BY<br>
* @param table
* @param field
* @param asc true
*/
public SelectBuilder orderBy(Selectable t, String field, boolean asc) {
return orderBy(new Column(t, field), asc);
}
/**
* ORDER BY()<br>
* @param colNo SELECT
*/
public SelectBuilder orderByAsc(int colNo) {
return orderBy(colNo, true);
}
/**
* ORDER BY()<br>
* @param colNo SELECT
*/
public SelectBuilder orderByDesc(int colNo) {
return orderBy(colNo, false);
}
/**
* ORDER BY<br>
* @param colNo SELECT
* @param asc true
*/
public SelectBuilder orderBy(int colNo, boolean asc) {
return orderBy(new Column(null, Integer.toString(colNo)), asc);
}
/**
* ORDER BY()<br>
* @param sel
*/
public SelectBuilder orderByAsc(Select sel) {
return orderBy(sel, true);
}
/**
* ORDER BY()<br>
* @param sel
*/
public SelectBuilder orderByDesc(Select sel) {
return orderBy(sel, false);
}
/**
* ORDER BY<br>
* @param sel
* @param asc true
*/
public SelectBuilder orderBy(Select sel, boolean asc) {
if (this.orderBy == null) {
this.orderBy = new ArrayList<OrderByEntry>();
}
this.orderBy.add(new OrderByEntry(sel, asc));
return this;
}
/**
* GROUP BY<br>
* @param sel
*/
public SelectBuilder groupBy(String field) {
Selectable t = searchTable(field);
return groupBy(new Column(t, field));
}
/**
* GROUP BY<br>
* @param table
* @param sel
*/
public SelectBuilder groupBy(Selectable table, String field) {
return groupBy(new Column(table, field));
}
/**
* GROUP BY<br>
* @param col
*/
public SelectBuilder groupBy(Column col) {
if (this.groupBy == null) {
this.groupBy = new ArrayList<Column>();
}
this.groupBy.add(col);
return this;
}
/**
* OFFSET
*/
public SelectBuilder offset() {
return offset(OFFSET_PARAM);
}
/**
* OFFSET
*/
public SelectBuilder offset(int n) {
this.offset = n;
return this;
}
/**
* LIMIT
*/
public SelectBuilder limit() {
return limit(LIMIT_PARAM);
}
/**
* LIMIT
*/
public SelectBuilder limit(int n) {
this.limit = n;
return this;
}
/**
* tableINNER JOIN
* @param table
*/
public SelectBuilder innerJoin(Selectable table) {
return addJoin(new InnerJoin(table, calcTableAlias()));
}
/**
public SelectBuilder innerJoin(Selectable table, String alias) {
return addJoin(new InnerJoin(table, alias));
}
*/
/**
* tableLEFT JOIN
* @param table
*/
public SelectBuilder leftJoin(Selectable table) {
return addJoin(new LeftJoin(table, calcTableAlias()));
}
/*
public SelectBuilder leftJoin(Selectable table, String alias) {
return addJoin(new LeftJoin(table, alias));
}
*/
/**
* tableRIGHT JOIN
* @param table
*/
public SelectBuilder rightJoin(Selectable table) {
return addJoin(new RightJoin(table, calcTableAlias()));
}
/*
public SelectBuilder rightJoin(Selectable table, String alias) {
return addJoin(new RightJoin(table, alias));
}
*/
private SelectBuilder addJoin(Join join) {
if (this.joins == null) {
this.joins = new ArrayList<Join>();
}
this.joins.add(join);
return this;
}
/**
* Join
*/
public Join getCurrentJoin() {
return joins == null ? null : joins.get(joins.size()-1);
}
/**
* JoinON<br>
*
* <br>
* @param field
*/
public SelectBuilder on(String field) {
return getCurrentJoin().on(field);
}
/**
* JoinON<br>
* @param field1
* @param field2
*/
public SelectBuilder on(String field1, String field2) {
return getCurrentJoin().on(field1, field2);
}
/**
* JoinON<br>
* @param table1 1
* @param field1 1
* @param table2 2
* @param field2 2
*/
public SelectBuilder on(Selectable table1, String field1, Selectable table2, String field2) {
return getCurrentJoin().on(table1, field1, table2, field2);
}
/**
* JoinON<br>
* @param table1 1
* @param field1 1
* @param table2 2
* @param field2 2
* @param op
*/
public SelectBuilder on(Selectable table1, String field1, Selectable table2, String field2, ComparisionOp op) {
return getCurrentJoin().on(table1, field1, table2, field2, op);
}
/**
* ANDWHERE<br>
* (and)
* @param cond
*/
public SelectBuilder where(Condition cond) {
if (where == null) {
where = new Where(cond);
} else {
where.and(cond);
}
return this;
}
/**
* ANDWHERE<br>
* @param cond
*/
public SelectBuilder and(Condition cond) {
if (where == null) {
where = new Where(cond);
} else {
where.and(cond);
}
return this;
}
/**
* ORWHERE<br>
* @param cond
*/
public SelectBuilder or(Condition cond) {
if (where == null) {
where = new Where(cond);
} else {
where.or(cond);
}
return this;
}
/**
* FOR UPDATE
*/
public SelectBuilder forUpdate() {
this.forUpdate = new ForUpdate(false);
return this;
}
/**
* FOR UPDATE NOWAIT
*/
public SelectBuilder forUpdateNoWait() {
this.forUpdate = new ForUpdate(true);
return this;
}
public char getQuoteChar() { return this.quoteChar;}
public void setQuoteChar(char c) { this.quoteChar = c;}
public String toSQL() {
return toSQL(false);
}
public String toSQL(boolean newLine) {
StringBuilder buf = new StringBuilder();
build(buf, newLine);
return buf.toString();
}
/**
* SQL<br>
* SQL
*/
@Override
public String toString() {
StringBuilder buf = new StringBuilder();
try {
build(buf, true);
return buf.toString();
} catch (Exception e) {
e.printStackTrace();
return "Invalid SELECT: " + buf;
}
}
/**
* ResultSetMap
*/
public Map<String, Object> map(ResultSet rs) throws SQLException {
if (this.rsTypes == null) {
ResultSetMetaData meta = rs.getMetaData();
if (meta.getColumnCount() < selects.size()) {
throw new IllegalArgumentException("Invalid resultSet");
}
int[] temp = new int[selects.size()];
for (int i=0; i<selects.size(); i++) {
temp[i] = meta.getColumnType(i+1);
}
this.rsTypes = temp;
}
Map<String, Object> map = new HashMap<String, Object>();
for (int i=0; i<selects.size(); i++) {
Select sel = selects.get(i);
int sqlType = rsTypes[i];
Object value = null;
switch (sqlType) {
case Types.BIGINT:
case Types.ROWID:
value = rs.getLong(i+1);
break;
case Types.BLOB:
case Types.BINARY:
value = rs.getBytes(i+1);
break;
case Types.BIT:
case Types.BOOLEAN:
value = rs.getBoolean(i+1);
break;
case Types.CHAR:
case Types.CLOB:
case Types.NCHAR:
case Types.NCLOB:
case Types.NVARCHAR:
case Types.SQLXML:
case Types.VARCHAR:
value = rs.getString(i+1);
break;
case Types.DATE:
value = rs.getDate(i+1);
break;
case Types.DECIMAL:
case Types.NUMERIC:
value = rs.getBigDecimal(i+1);
break;
case Types.DOUBLE:
case Types.FLOAT:
case Types.REAL:
value = rs.getDouble(i+1);
break;
case Types.INTEGER:
case Types.SMALLINT:
case Types.TINYINT:
value = rs.getInt(i+1);
break;
case Types.NULL:
value = null;
break;
case Types.TIME:
value = rs.getTime(i+1);
break;
case Types.TIMESTAMP:
value = rs.getTimestamp(i+1);
break;
case Types.OTHER:
case Types.REF:
case Types.STRUCT:
case Types.VARBINARY:
break;
case Types.ARRAY:
case Types.DATALINK:
case Types.DISTINCT:
case Types.JAVA_OBJECT:
case Types.LONGNVARCHAR:
case Types.LONGVARBINARY:
case Types.LONGVARCHAR:
default:
throw new IllegalArgumentException("UnsupportedType: " + sqlType);
}
if (rs.wasNull()) {
value = null;
}
map.put(sel.getFieldName(), value);
}
return map;
}
/**
* SELECT
*/
public boolean hasField(String field) {
for (Select sel : this.selects) {
if (sel.getFieldName().equals(field)) {
return true;
}
}
return false;
}
SelectBuilder getParent() { return this.parent;}
void setParent(SelectBuilder builder) { this.parent = builder;}
protected String getAliasPrefix() { return this.aliasPrefix;}
void setAliasPrefix(String s) { this.aliasPrefix = s;}
Selectable searchTable(String field) {
Selectable ret = null;
List<Column> checkList = null;
if (mainTable.getTable().hasField(field)) {
ret = mainTable.getTable();
}
if (joins != null) {
for (int i=0; i<joins.size(); i++) {
TableInfo info = joins.get(i).getTableInfo();
if (info.getTable().hasField(field)) {
if (ret == null) {
ret = info.getTable();
} else {
if (checkList == null) {
checkList = new ArrayList<Column>();
checkList.add(new Column(ret, field));
}
checkList.add(new Column(info.getTable(), field));
}
}
}
}
if (ret == null) {
return this.parent != null ? this.parent.searchTable(field) : null;
}
if (checkList != null) {
for (Column col : checkList) {
if (!isJoinedColumn(col)) {
throw new IllegalArgumentException("Ambiguous reference: " + field);
}
}
}
return ret;
}
List<Condition> getConditions() {
if (this.where == null) {
return null;
}
List<Condition> list = new ArrayList<Condition>();
for (WhereEntry entry : where.getList()) {
list.add(entry.cond);
}
return list;
}
private boolean isJoinedColumn(Column col) {
if (joins != null) {
for (Join join : joins) {
if (join.isJoinedColumn(col)) {
return true;
}
}
}
return false;
}
private boolean contains(Selectable t) {
if (mainTable.getTable() == t) {
return true;
}
if (joins != null) {
for (Join join : joins) {
TableInfo info = join.getTableInfo();
if (info.getTable() == t) {
return true;
}
}
}
return false;
}
private String getTableAlias(Selectable t) {
if (t == mainTable.getTable()) {
return mainTable.getAlias();
}
if (joins != null) {
for (int i=0; i<joins.size(); i++) {
TableInfo info = joins.get(i).getTableInfo();
if (info.getTable() == t) {
return info.getAlias();
}
}
}
if (parent != null) {
return parent.getTableAlias(t);
}
return null;
}
/*
private Selectable getTable(String alias) {
if (alias.equals(mainTable.getAlias())) {
return mainTable.getTable();
}
if (joins != null) {
for (int i=0; i<joins.size(); i++) {
TableInfo info = joins.get(i).getTableInfo();
if (alias.equals(info.getAlias())) {
return info.getTable();
}
}
}
if (parent != null) {
return parent.getTable(alias);
}
return null;
}
*/
private String calcTableAlias() {
int prefixLen = aliasPrefix.length();
char c = 0;
String alias = mainTable.getAlias().substring(prefixLen);
if (alias.length() == 1) {
c = alias.charAt(0);
}
if (joins != null) {
for (Join join : joins) {
alias = join.getTableInfo().getAlias().substring(prefixLen);
if (alias.length() == 1) {
char c2 = alias.charAt(0);
if (c2 > c) {
c = c2;
}
}
}
}
return c == 0 ? "A" : "" + (char)(c + 1);
}
private Selectable getTableByFieldName(String field) {
if (mainTable.getTable().hasField(field)) {
return mainTable.getTable();
}
if (joins != null) {
for (Join join : joins) {
TableInfo info = join.getTableInfo();
if (info.getTable().hasField(field)) {
return info.getTable();
}
}
}
return null;
}
private void quote(StringBuilder buf, String str) {
if (quoteChar == 0) {
buf.append(str);
} else {
buf.append(quoteChar);
buf.append(str);
buf.append(quoteChar);
}
}
private void build(StringBuilder buf, boolean newLine) {
if (selects.size() == 0) {
throw new IllegalArgumentException("No select clause");
}
boolean bGroup = groupBy != null && groupBy.size() > 0;
buf.append("SELECT ");
if (distinct) {
buf.append("DISTINCT ");
}
boolean first = true;
for (Select sel : selects) {
if (first) {
first = false;
} else {
buf.append(", ");
}
if (newLine) {
buf.append("\n ");
}
sel.build(buf, this);
if (sel instanceof Aggregate) {
bGroup = true;
}
}
if (newLine) {
buf.append("\n");
} else {
buf.append(" ");
}
buf.append("FROM ");
mainTable.build(buf);
if (joins != null) {
for (Join join : joins) {
if (newLine) {
buf.append("\n");
} else {
buf.append(" ");
}
join.build(buf);
}
}
if (where != null) {
where.build(buf, newLine);
}
if (bGroup) {
List<Column> gList = groupBy != null ? groupBy : getGroupByColumn(selects);
if (gList.size() > 0) {
if (newLine) {
buf.append("\n");
} else {
buf.append(" ");
}
buf.append("GROUP BY ");
first = true;
for (Column col : gList) {
if (first) {
first = false;
} else {
buf.append(", ");
}
if (newLine) {
buf.append("\n ");
}
col.doBuild(buf, this);
}
}
}
if (orderBy != null) {
if (newLine) {
buf.append("\n");
} else {
buf.append(" ");
}
buf.append("ORDER BY ");
first = true;
for (OrderByEntry entry : orderBy) {
if (first) {
first = false;
} else {
buf.append(", ");
}
if (newLine) {
buf.append("\n ");
}
entry.sel.doBuild(buf, this);
if (!entry.asc) {
buf.append(" DESC");
}
}
}
if (offset != 0) {
if (newLine) {
buf.append("\n");
} else {
buf.append(" ");
}
buf.append("OFFSET ").append(offset == OFFSET_PARAM ? "?" : Integer.toString(offset));
}
if (limit != 0) {
if (newLine) {
buf.append("\n");
} else {
buf.append(" ");
}
buf.append("LIMIT ").append(limit == LIMIT_PARAM ? "?" : limit == 0 ? "ALL" : Integer.toString(limit));
}
if (forUpdate != null) {
buf.append(forUpdate);
}
}
private List<Column> getGroupByColumn(List<Select> list) {
List<Column> ret = new ArrayList<Column>();
for (Select sel : list) {
if (sel instanceof Column) {
ret.add((Column)sel);
}
}
return ret;
}
/**
* SELECT
*/
public static abstract class Select {
private String alias;
public Select alias(String s) {
this.alias = s;
return this;
}
public String alias() { return this.alias;}
public Select as(String s) {
return alias(s);
}
public String as() { return alias();}
public String getFieldName() {
if (this.alias != null) {
return this.alias;
}
return doGetFieldName();
}
protected abstract String doGetFieldName();
public final void build(StringBuilder buf, SelectBuilder builder) {
doBuild(buf, builder);
String a = alias();
if (a != null) {
buf.append(" AS ");
builder.quote(buf, a);
}
}
protected abstract void doBuild(StringBuilder buf, SelectBuilder builder);
}
/**
* SELECT
*/
public static class Literal extends Select {
private Object literal;
public Literal(Object literal) {
this.literal = literal;
}
protected String doGetFieldName() {
return literal.toString();
}
protected void doBuild(StringBuilder buf, SelectBuilder builder) {
buf.append(this.literal);
}
public static final Literal TRUE = new Literal(true);
public static final Literal FALSE = new Literal(false);
}
/**
* SELECT
*/
public static class Column extends Select {
private Selectable table;
private String field;
public Column(String f) {
this(null, f);
}
public Column(Selectable t, String f) {
this.table = t;
this.field = f;
}
protected String doGetFieldName() {
return field;
}
protected void doBuild(StringBuilder buf, SelectBuilder builder) {
Selectable t = this.table;
String ta = null;
if (t == null) {
t = builder.searchTable(this.field);
}
if (t != null) {
ta = builder.getTableAlias(t);
if (ta == null) {
throw new IllegalArgumentException("Unknown table: " + t);
}
}
if (ta != null) {
builder.quote(buf, ta);
buf.append(".");
}
builder.quote(buf, field);
}
public Selectable getTable() { return this.table;}
void setTable(Selectable t) { this.table = t;}
public String getField() { return this.field;}
void setField(String s) { this.field = s;}
}
public static class Function extends Select {
private String functionName;
private Object[] args;
public Function(String functionName, Object... args) {
this.functionName = functionName;
this.args = args;
}
protected String doGetFieldName() {
return this.functionName;
}
protected void doBuild(StringBuilder buf, SelectBuilder builder) {
buf.append(this.functionName)
.append("(");
if (this.args != null) {
boolean first = true;
for (Object o : args) {
if (first) {
first = false;
} else {
buf.append(", ");
}
appendObject(buf, builder, o);
}
}
buf.append(")");
}
}
public static class Aggregate extends Function {
public Aggregate(String functionName, Object... args) {
super(functionName, args);
}
}
/**
* Case
*/
public static class Case extends Select {
private List<CaseEntry> list = new ArrayList<CaseEntry>();
private Select elseValue;
public Case when(Condition cond, Select value) {
this.list.add(new CaseEntry(cond, value));
return this;
}
public Case caseElse(Select value) {
elseValue = value;
return this;
}
@Override
protected String doGetFieldName() {
return "CASE";
}
@Override
protected void doBuild(StringBuilder buf, SelectBuilder builder) {
buf.append("CASE ");
for (CaseEntry entry : list) {
buf.append("WHEN ");
entry.cond.build(buf, builder);
buf.append(" THEN ");
entry.value.build(buf, builder);
}
if (elseValue != null) {
buf.append(" ELSE ");
elseValue.build(buf, builder);
}
buf.append(" END");
}
}
/**
* JOIN
*/
public abstract class Join {
private TableInfo info;
private CompoundCondition on = new CompoundCondition(LogicalOp.AND);
public Join(Selectable t, String a) {
if (a == null) {
a = calcTableAlias();
}
this.info = new TableInfo(t, a);
}
public SelectBuilder on(String field) {
return on(field, field);
}
public SelectBuilder on(String field1, String field2) {
if (!info.getTable().hasField(field1)) {
if (!info.getTable().hasField(field2)) {
throw new IllegalArgumentException("Both " + field1 + " and " + field2 + " are not field of " + info.getTable());
} else {
return on(field2, field1);
}
}
Selectable table1 = info.getTable();
Selectable table2 = getTableByFieldName(field2);
if (table2 == null || table2 == table1) {
throw new IllegalArgumentException("Invalid field: " + field2);
}
return on(table1, field1, table2, field2, ComparisionOp.Equal);
}
public SelectBuilder on(Selectable table1, String field1, Selectable table2, String field2) {
return on(table1, field1, table2, field2, ComparisionOp.Equal);
}
public SelectBuilder on(Selectable table1, String field1, Selectable table2, String field2, ComparisionOp op) {
Column col1 = new Column(table1, field1);
Column col2 = new Column(table2, field2);
on.add(new Combine(col1, col2, op));
return SelectBuilder.this;
}
//Jointrue
public boolean isJoinedColumn(Column col) {
for (Condition c : on.getList()) {
if (c instanceof Combine) {
Combine combi = (Combine)c;
if (combi.getOp() == ComparisionOp.Equal &&
combi.getCol1() instanceof Column &&
combi.getCol2() instanceof Column)
{
Column cc1 = (Column)combi.getCol1();
Column cc2 = (Column)combi.getCol2();
if ((cc1.getTable() == col.getTable() || cc2.getTable() == col.getTable()) &&
cc1.getField().equals(col.getField()) &&
cc2.getField().equals(col.getField()))
{
return true;
}
}
}
}
return false;
}
public abstract String getJoinString();
public TableInfo getTableInfo() {
return this.info;
}
public void build(StringBuilder buf) {
buf.append(getJoinString()).append(" ");
info.build(buf);
if (on.size() > 0) {
buf.append(" ON ");
on.build(buf, SelectBuilder.this, false);
}
}
}
private class InnerJoin extends Join {
public InnerJoin(Selectable t, String a) {
super(t, a);
}
public String getJoinString() {
return "INNER JOIN";
}
}
private class LeftJoin extends Join {
public LeftJoin(Selectable t, String a) {
super(t, a);
}
public String getJoinString() {
return "LEFT JOIN";
}
}
private class RightJoin extends Join {
public RightJoin(Selectable t, String a) {
super(t, a);
}
public String getJoinString() {
return "RIGHT JOIN";
}
}
private class TableInfo {
private Selectable table;
private String alias;
public TableInfo (Selectable t, String a) {
this.table = t;
this.alias = a;
}
public void build(StringBuilder buf) {
if (table instanceof Table) {
quote(buf, ((Table)table).getTableName());
} else if (table instanceof SelectBuilder) {
buf.append("(").append(((SelectBuilder)table).toSQL()).append(")");
} else {
throw new IllegalStateException();
}
buf.append(" ");
quote(buf, getAlias());
}
public Selectable getTable() { return this.table;}
public String getAlias() { return SelectBuilder.this.aliasPrefix + this.alias;}
}
private class Where {
private List<WhereEntry> list = new ArrayList<WhereEntry>();
public Where(Condition cond) {
and(cond);
}
public List<WhereEntry> getList() { return this.list;}
public SelectBuilder and(Condition cond) {
return doAdd(cond, LogicalOp.AND);
}
public SelectBuilder or(Condition cond) {
return doAdd(cond, LogicalOp.OR);
}
private SelectBuilder doAdd(Condition cond, LogicalOp op) {
list.add(new WhereEntry(cond, op));
return SelectBuilder.this;
}
public void build(StringBuilder buf, boolean newLine) {
for (int i=0; i<list.size(); i++) {
WhereEntry entry = list.get(i);
if (newLine) {
buf.append("\n");
} else {
buf.append(" ");
}
if (i == 0) {
buf.append("WHERE ");
} else {
buf.append(entry.op).append(" ");
}
entry.cond.build(buf, SelectBuilder.this);
}
}
}
private static class WhereEntry {
private Condition cond;
private LogicalOp op;
public WhereEntry(Condition cond, LogicalOp op) {
this.cond = cond;
this.op = op;
}
}
private static class OrderByEntry {
private Select sel;
private boolean asc;
public OrderByEntry(Select sel, boolean asc) {
this.sel = sel;
this.asc = asc;
}
}
public static class CaseEntry {
public Condition cond;
public Select value;
public CaseEntry(Condition cond, Select value) {
this.cond = cond;
this.value = value;
}
}
private static class ForUpdate {
private boolean nowait;
public ForUpdate(boolean nowait) {
this.nowait = nowait;
}
public String toString() {
String ret = " FOR UPDATE";
if (nowait) {
ret += " NOWAIT";
}
return ret;
}
}
static void appendObject(StringBuilder buf, SelectBuilder builder, Object value) {
if (value instanceof String) {
String str = value.toString();
buf.append("'");
for (int i=0; i<str.length(); i++) {
char c = str.charAt(i);
if (c == '\'') {
buf.append("''");
} else {
buf.append(c);
}
}
buf.append("'");
} else if (value instanceof Date) {
buf.append("'")
.append(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format((Date)value))
.append("'");
} else if (value instanceof Select) {
((Select)value).build(buf, builder);
} else {
buf.append(value);
}
}
} |
package mtr.model;
import mtr.MTR;
import mtr.data.Train;
import mtr.data.TrainType;
import mtr.render.RenderTrains;
import net.minecraft.client.world.ClientWorld;
import net.minecraft.sound.SoundCategory;
import net.minecraft.sound.SoundEvent;
import net.minecraft.text.TranslatableText;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import java.util.*;
import java.util.function.BiConsumer;
public class TrainClientRegistry {
private static final Map<String, TrainProperties> REGISTRY = new HashMap<>();
private static final List<String> KEY_ORDER = new ArrayList<>();
private static final String SOUND_ACCELERATION = "_acceleration_";
private static final String SOUND_DECELERATION = "_deceleration_";
private static final String SOUND_DOOR_OPEN = "_door_open";
private static final String SOUND_DOOR_CLOSE = "_door_close";
public static void register(String key, TrainType baseTrainType, ModelTrainBase model, String textureId, String speedSoundBaseId, String doorSoundBaseId, String name, int color, boolean hasGangwayConnection, int speedSoundCount, float doorCloseSoundTime, boolean useAccelerationSoundsWhenCoasting) {
final String keyLower = key.toLowerCase();
if (!KEY_ORDER.contains(keyLower)) {
KEY_ORDER.add(keyLower);
}
REGISTRY.put(keyLower, new TrainProperties(baseTrainType, model, textureId, speedSoundBaseId, doorSoundBaseId, new TranslatableText(name == null ? "train.mtr." + keyLower : name), color, hasGangwayConnection, speedSoundCount, doorCloseSoundTime, useAccelerationSoundsWhenCoasting));
}
public static void reset() {
REGISTRY.clear();
KEY_ORDER.clear();
register("sp1900", TrainType.SP1900, new ModelSP1900(false), "mtr:textures/entity/sp1900", "sp1900", "sp1900", null, 0x003399, true, 120, 0.5F, false);
register("sp1900_mini", TrainType.SP1900_MINI, new ModelSP1900Mini(false), "mtr:textures/entity/sp1900", "sp1900", "sp1900", null, 0x003399, true, 120, 0.5F, false);
register("sp1900_small", TrainType.SP1900_SMALL, new ModelSP1900Small(false), "mtr:textures/entity/sp1900", "sp1900", "sp1900", null, 0x003399, true, 120, 0.5F, false);
register("c1141a", TrainType.C1141A, new ModelSP1900(true), "mtr:textures/entity/c1141a", "c1141a", "sp1900", null, 0xB42249, true, 96, 0.5F, false);
register("c1141a_mini", TrainType.C1141A_MINI, new ModelSP1900Mini(true), "mtr:textures/entity/c1141a", "c1141a", "sp1900", null, 0xB42249, true, 96, 0.5F, false);
register("c1141a_small", TrainType.C1141A_SMALL, new ModelSP1900Small(true), "mtr:textures/entity/c1141a", "c1141a", "sp1900", null, 0xB42249, true, 96, 0.5F, false);
register("m_train", TrainType.M_TRAIN, new ModelMTrain(), "mtr:textures/entity/m_train", "m_train", "m_train", null, 0x999999, true, 90, 0.5F, false);
register("m_train_mini", TrainType.M_TRAIN_MINI, new ModelMTrainMini(), "mtr:textures/entity/m_train", "m_train", "m_train", null, 0x999999, true, 90, 0.5F, false);
register("m_train_small", TrainType.M_TRAIN_SMALL, new ModelMTrainSmall(), "mtr:textures/entity/m_train", "m_train", "m_train", null, 0x999999, true, 90, 0.5F, false);
register("mlr", TrainType.MLR, new ModelMLR(), "mtr:textures/entity/mlr", "mlr", "mlr", null, 0x6CB5E2, true, 93, 0.5F, true);
register("mlr_mini", TrainType.MLR_MINI, new ModelMLRMini(), "mtr:textures/entity/mlr", "mlr", "mlr", null, 0x6CB5E2, true, 93, 0.5F, true);
register("mlr_small", TrainType.MLR_SMALL, new ModelMLRSmall(), "mtr:textures/entity/mlr", "mlr", "mlr", null, 0x6CB5E2, true, 93, 0.5F, true);
register("e44", TrainType.E44, new ModelE44(), "mtr:textures/entity/e44", "mlr", "m_train", null, 0xE7AF25, true, 93, 0.5F, true);
register("e44_mini", TrainType.E44_MINI, new ModelE44Mini(), "mtr:textures/entity/e44", "mlr", "m_train", null, 0xE7AF25, true, 93, 0.5F, true);
register("k_train", TrainType.K_TRAIN, new ModelKTrain(false), "mtr:textures/entity/k_train", "k_train", "k_train", null, 0x0EAB52, true, 66, 1, false);
register("k_train_mini", TrainType.K_TRAIN_MINI, new ModelKTrainMini(false), "mtr:textures/entity/k_train", "k_train", "k_train", null, 0x0EAB52, true, 66, 1, false);
register("k_train_small", TrainType.K_TRAIN_SMALL, new ModelKTrainSmall(false), "mtr:textures/entity/k_train", "k_train", "k_train", null, 0x0EAB52, true, 66, 1, false);
register("k_train_tcl", TrainType.K_TRAIN_TCL, new ModelKTrain(true), "mtr:textures/entity/k_train_tcl", "k_train", "k_train", null, 0x0EAB52, true, 66, 1, false);
register("k_train_tcl_small", TrainType.K_TRAIN_TCL_SMALL, new ModelKTrainSmall(true), "mtr:textures/entity/k_train_tcl", "k_train", "k_train", null, 0x0EAB52, true, 66, 1, false);
register("k_train_tcl_mini", TrainType.K_TRAIN_TCL_MINI, new ModelKTrainMini(true), "mtr:textures/entity/k_train_tcl", "k_train", "k_train", null, 0x0EAB52, true, 66, 1, false);
register("k_train_ael", TrainType.K_TRAIN_AEL, new ModelKTrain(true), "mtr:textures/entity/k_train_ael", "k_train", "k_train", null, 0x0EAB52, true, 66, 1, false);
register("k_train_ael_mini", TrainType.K_TRAIN_AEL_MINI, new ModelKTrainMini(true), "mtr:textures/entity/k_train_ael", "k_train", "k_train", null, 0x0EAB52, true, 66, 1, false);
register("k_train_ael_small", TrainType.K_TRAIN_AEL_SMALL, new ModelKTrainSmall(true), "mtr:textures/entity/k_train_ael", "k_train", "k_train", null, 0x0EAB52, true, 66, 1, false);
register("a_train_tcl", TrainType.A_TRAIN_TCL, new ModelATrain(false), "mtr:textures/entity/a_train_tcl", "a_train", "a_train", null, 0xF69447, true, 78, 0.5F, false);
register("a_train_tcl_mini", TrainType.A_TRAIN_TCL_MINI, new ModelATrainMini(false), "mtr:textures/entity/a_train_tcl", "a_train", "a_train", null, 0xF69447, true, 78, 0.5F, false);
register("a_train_tcl_small", TrainType.A_TRAIN_TCL_SMALL, new ModelATrainSmall(), "mtr:textures/entity/a_train_tcl", "a_train", "a_train", null, 0xF69447, true, 78, 0.5F, false);
register("a_train_ael", TrainType.A_TRAIN_AEL, new ModelATrain(true), "mtr:textures/entity/a_train_ael", "a_train", "a_train", null, 0x008D8D, true, 78, 0.5F, false);
register("a_train_ael_mini", TrainType.A_TRAIN_AEL_MINI, new ModelATrainMini(true), "mtr:textures/entity/a_train_ael", "a_train", "a_train", null, 0x008D8D, true, 78, 0.5F, false);
register("light_rail_1", TrainType.LIGHT_RAIL_1, new ModelLightRail(1), "mtr:textures/entity/light_rail_1", "light_rail", "light_rail_1", null, 0xD2A825, false, 48, 1, false);
register("light_rail_1r", TrainType.LIGHT_RAIL_1R, new ModelLightRail(4), "mtr:textures/entity/light_rail_1r", "light_rail", "light_rail_1", null, 0xD2A825, false, 48, 1, false);
register("light_rail_2", TrainType.LIGHT_RAIL_2, new ModelLightRail(2), "mtr:textures/entity/light_rail_2", "light_rail", "light_rail_3", null, 0xD2A825, false, 48, 1, false);
register("light_rail_3", TrainType.LIGHT_RAIL_3, new ModelLightRail(3), "mtr:textures/entity/light_rail_3", "light_rail", "light_rail_3", null, 0xD2A825, false, 48, 1, false);
register("light_rail_4", TrainType.LIGHT_RAIL_4, new ModelLightRail(4), "mtr:textures/entity/light_rail_4", "light_rail", "light_rail_4", null, 0xD2A825, false, 48, 1, false);
register("light_rail_5", TrainType.LIGHT_RAIL_5, new ModelLightRail(5), "mtr:textures/entity/light_rail_5", "light_rail", "light_rail_4", null, 0xD2A825, false, 48, 1, false);
register("light_rail_1r_old", TrainType.LIGHT_RAIL_1R, new ModelLightRail(4), "mtr:textures/entity/light_rail_1r_old", "light_rail", "light_rail_1", null, 0xD2A825, false, 48, 1, false);
register("light_rail_4_old", TrainType.LIGHT_RAIL_4, new ModelLightRail(4), "mtr:textures/entity/light_rail_4_old", "light_rail", "light_rail_4", null, 0xD2A825, false, 48, 1, false);
register("light_rail_5_old", TrainType.LIGHT_RAIL_5, new ModelLightRail(5), "mtr:textures/entity/light_rail_5_old", "light_rail", "light_rail_4", null, 0xD2A825, false, 48, 1, false);
register("light_rail_1_orange", TrainType.LIGHT_RAIL_1, new ModelLightRail(1), "mtr:textures/entity/light_rail_1", "light_rail", "light_rail_1", null, 0xD2A825, false, 48, 1, false);
register("light_rail_1r_orange", TrainType.LIGHT_RAIL_1R, new ModelLightRail(4), "mtr:textures/entity/light_rail_1r_orange", "light_rail", "light_rail_1", null, 0xD2A825, false, 48, 1, false);
register("light_rail_2_orange", TrainType.LIGHT_RAIL_2, new ModelLightRail(2), "mtr:textures/entity/light_rail_2_orange", "light_rail", "light_rail_3", null, 0xD2A825, false, 48, 1, false);
register("light_rail_3_orange", TrainType.LIGHT_RAIL_3, new ModelLightRail(3), "mtr:textures/entity/light_rail_3_orange", "light_rail", "light_rail_3", null, 0xD2A825, false, 48, 1, false);
register("light_rail_4_orange", TrainType.LIGHT_RAIL_4, new ModelLightRail(4), "mtr:textures/entity/light_rail_4_orange", "light_rail", "light_rail_4", null, 0xD2A825, false, 48, 1, false);
register("light_rail_5_orange", TrainType.LIGHT_RAIL_5, new ModelLightRail(5), "mtr:textures/entity/light_rail_5_orange", "light_rail", "light_rail_4", null, 0xD2A825, false, 48, 1, false);
register("london_underground_1995", TrainType.LONDON_UNDERGROUND_1995, new ModelLondonUnderground1995(), "mtr:textures/entity/london_underground_1995", "r179", "london_underground_1995", null, 0x333333, false, 0, 0.5F, false);
register("r179", TrainType.R179, new ModelR179(), "mtr:textures/entity/r179", "r179", "r179", null, 0xD5D5D5, false, 66, 1, false);
register("minecart", TrainType.MINECART, null, null, null, null, null, 0x666666, false, 0, 0.5F, false);
}
public static TrainProperties getTrainProperties(String key, TrainType baseTrainType) {
final String keyLower = key.toLowerCase();
if (REGISTRY.containsKey(keyLower)) {
return REGISTRY.get(keyLower);
} else {
final String fallbackKeyLower = baseTrainType.toString().toLowerCase();
return REGISTRY.containsKey(fallbackKeyLower) ? REGISTRY.get(fallbackKeyLower) : getBlankProperties(baseTrainType);
}
}
public static TrainProperties getTrainProperties(int index) {
return index >= 0 && index < KEY_ORDER.size() ? REGISTRY.get(KEY_ORDER.get(index)) : getBlankProperties(TrainType.values()[0]);
}
public static String getTrainId(int index) {
return KEY_ORDER.get(index >= 0 && index < KEY_ORDER.size() ? index : 0);
}
public static void forEach(BiConsumer<String, TrainProperties> biConsumer) {
KEY_ORDER.forEach(key -> biConsumer.accept(key, REGISTRY.get(key)));
}
private static TrainProperties getBlankProperties(TrainType baseTrainType) {
return new TrainProperties(baseTrainType, null, null, null, null, new TranslatableText(""), 0, false, 0, 0.5F, false);
}
public static class TrainProperties {
public final TrainType baseTrainType;
public final ModelTrainBase model;
public final String textureId;
public final String speedSoundBaseId;
public final String doorSoundBaseId;
public final TranslatableText name;
public final int color;
public final boolean hasGangwayConnection;
public final int speedSoundCount;
private final float doorCloseSoundTime;
private final boolean useAccelerationSoundsWhenCoasting;
private final char[] SOUND_GROUP_LETTERS = {'a', 'b', 'c'};
private final int SOUND_GROUP_SIZE = SOUND_GROUP_LETTERS.length;
private TrainProperties(TrainType baseTrainType, ModelTrainBase model, String textureId, String speedSoundBaseId, String doorSoundBaseId, TranslatableText name, int color, boolean hasGangwayConnection, int speedSoundCount, float doorCloseSoundTime, boolean useAccelerationSoundsWhenCoasting) {
this.baseTrainType = baseTrainType;
this.model = model;
this.textureId = resolvePath(textureId);
this.speedSoundBaseId = resolvePath(speedSoundBaseId);
this.doorSoundBaseId = resolvePath(doorSoundBaseId);
this.name = name;
this.color = color;
this.hasGangwayConnection = hasGangwayConnection;
this.speedSoundCount = speedSoundCount;
this.doorCloseSoundTime = doorCloseSoundTime;
this.useAccelerationSoundsWhenCoasting = useAccelerationSoundsWhenCoasting;
}
public void playSpeedSoundEffect(World world, BlockPos pos, float oldSpeed, float speed) {
if (world instanceof ClientWorld && RenderTrains.canPlaySound() && speedSoundCount > 0 && speedSoundBaseId != null) {
final int floorSpeed = (int) Math.floor(speed / Train.ACCELERATION / RenderTrains.TICKS_PER_SPEED_SOUND);
if (floorSpeed > 0) {
final int index = Math.min(floorSpeed, speedSoundCount) - 1;
final boolean isAccelerating = speed == oldSpeed ? useAccelerationSoundsWhenCoasting || new Random().nextBoolean() : speed > oldSpeed;
final String soundId = speedSoundBaseId + (isAccelerating ? SOUND_ACCELERATION : SOUND_DECELERATION) + index / SOUND_GROUP_SIZE + SOUND_GROUP_LETTERS[index % SOUND_GROUP_SIZE];
((ClientWorld) world).playSound(pos, new SoundEvent(new Identifier(MTR.MOD_ID, soundId)), SoundCategory.BLOCKS, 1, 1, true);
}
}
}
public void playDoorSoundEffect(World world, BlockPos pos, float oldDoorValue, float doorValue) {
if (world instanceof ClientWorld && doorSoundBaseId != null) {
final String soundId;
if (oldDoorValue <= 0 && doorValue > 0) {
soundId = doorSoundBaseId + SOUND_DOOR_OPEN;
} else if (oldDoorValue >= doorCloseSoundTime && doorValue < doorCloseSoundTime) {
soundId = doorSoundBaseId + SOUND_DOOR_CLOSE;
} else {
soundId = null;
}
if (soundId != null) {
((ClientWorld) world).playSound(pos, new SoundEvent(new Identifier(MTR.MOD_ID, soundId)), SoundCategory.BLOCKS, 1, 1, true);
}
}
}
private static String resolvePath(String path) {
return path == null ? null : path.toLowerCase().split("\\.png")[0];
}
}
} |
package myessentials.utils;
import net.minecraft.util.EnumChatFormatting;
/**
* Colors for characters or types of things commonly used.
*/
public class ColorUtils {
public static final String colorPlayer = EnumChatFormatting.WHITE.toString();
public static final String colorOwner = EnumChatFormatting.RED.toString();
public static final String colorTown = EnumChatFormatting.GOLD.toString();
public static final String colorSelectedTown = EnumChatFormatting.GREEN.toString();
public static final String colorInfoText = EnumChatFormatting.GRAY.toString();
public static final String colorConfigurableFlag = EnumChatFormatting.GRAY.toString();
public static final String colorUnconfigurableFlag = EnumChatFormatting.DARK_GRAY.toString();
public static final String colorValueFalse = EnumChatFormatting.RED.toString();
public static final String colorValueRegular = EnumChatFormatting.GREEN.toString();
public static final String colorDescription = EnumChatFormatting.GRAY.toString();
public static final String colorCoords = EnumChatFormatting.BLUE.toString();
public static final String colorComma = EnumChatFormatting.WHITE.toString();
public static final String colorEmpty = EnumChatFormatting.RED.toString();
public static final String colorAdmin = EnumChatFormatting.RED.toString();
public static final String colorGroupType = EnumChatFormatting.BLUE.toString();
public static final String colorGroupText = EnumChatFormatting.GRAY.toString();
public static final String colorGroupParents = EnumChatFormatting.WHITE.toString();
public static final String colorGroup = EnumChatFormatting.BLUE.toString();
//public static final String paranthColor = EnumChatFormatting.GOLD.toString();
} |
package net.emteeware.common;
public class DigitSum {
/**
* @param input
* An integer you want to calculate the sum of digits for. (Base 10)
* @return
* The sum of digits for the provided input. (Base 10)
*/
public static int getDigitSum(int input) {
int digitSum = 0;
int summedNumber = input;
int nextDigit;
do {
nextDigit = summedNumber%10;
digitSum += nextDigit;
summedNumber /= 10;
} while(summedNumber > 0);
return digitSum;
}
} |
package net.logvv.raven.push;
import net.logvv.raven.common.model.ErrorCode;
import net.logvv.raven.push.model.PushMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import net.logvv.raven.common.model.GeneralResult;
@RestController
public class PushRest {
private static final Logger LOGGER = LoggerFactory.getLogger(PushRest.class);
@Autowired
private PushMessageService pushService;
/**
* : ,</br>
* : </br>
* @param notification
* @return result
* @author wangwei
* @version 1.0
* @date 2017/1/12 15:58
*/
@RequestMapping(value = "/push/notification", method=RequestMethod.POST)
public GeneralResult notification(@RequestBody PushMessage notification)
{
GeneralResult result = new GeneralResult();
LOGGER.info("Begin to push notification.");
try {
}catch (Exception e){
LOGGER.error("failed to push notification, error:{}",e);
result.setErr(ErrorCode.PUSH_MESSAGE_FAIL);
return result;
}
return result;
}
/**
* : ,app</br>
* : ,app</br>
* @param message
* @return result
* @author wangwei
* @version 1.0
* @date 2017/1/12 15:59
*/
@RequestMapping(value = "/push/message", method = RequestMethod.POST)
public GeneralResult message(@RequestBody PushMessage message)
{
GeneralResult result = new GeneralResult();
LOGGER.info("Begin to push message.");
try{
}catch (Exception e){
LOGGER.error("failed to push message, error:{}",e);
result.setErr(ErrorCode.PUSH_MESSAGE_FAIL);
return result;
}
return result;
}
} |
package net.md_5.bungee;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import static net.md_5.bungee.Logger.$;
import net.md_5.bungee.command.CommandSender;
import net.md_5.bungee.command.ConsoleCommandSender;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
/**
* Core configuration for the proxy.
*/
public class Configuration {
/**
* Reconnect locations file.
*/
private transient File reconnect = new File("locations.yml");
/**
* Loaded reconnect locations.
*/
private transient Map<String, String> reconnectLocations;
/**
* Config file.
*/
private transient File file = new File("config.yml");
/**
* Yaml instance.
*/
private transient Yaml yaml;
/**
* Loaded config.
*/
private transient Map<String, Object> config;
/**
* Bind host.
*/
public String bindHost = "0.0.0.0:25577";
/**
* Server ping motd.
*/
public String motd = "BungeeCord Proxy Instance";
/**
* Name of default server.
*/
public String defaultServerName = "default";
/**
* Max players as displayed in list ping. Soft limit.
*/
public int maxPlayers = 1;
/**
* Socket timeout.
*/
public int timeout = 15000;
/**
* All servers.
*/
public Map<String, String> servers = new HashMap<String, String>() {
{
put(defaultServerName, "127.0.0.1:1338");
put("pvp", "127.0.0.1:1337");
}
};
/**
* Forced servers.
*/
public Map<String, String> forcedServers = new HashMap<String, String>() {
{
put("pvp.md-5.net", "pvp");
}
};
/**
* Proxy admins.
*/
public List<String> admins = new ArrayList<String>() {
{
add("md_5");
}
};
/**
* Proxy moderators.
*/
public List<String> moderators = new ArrayList<String>() {
{
add("mbaxter");
}
};
/**
* Commands which will be blocked completely.
*/
public List<String> disabledCommands = new ArrayList<String>() {
{
add("glist");
}
};
/**
* Maximum number of lines to log before old ones are removed.
*/
public int logNumLines = 1 << 14;
/**
* UUID for Metrics.
*/
public String statsUuid = UUID.randomUUID().toString();
/**
* Load the configuration and save default values.
*/
public void load() {
try {
file.createNewFile();
DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yaml = new Yaml(options);
try (InputStream is = new FileInputStream(file)) {
config = (Map) yaml.load(is);
}
if (config == null) {
config = new LinkedHashMap<>();
}
$().info("
for (Field field : getClass().getDeclaredFields()) {
if (!Modifier.isTransient(field.getModifiers())) {
String name = Util.normalize(field.getName());
try {
Object def = field.get(this);
Object value = get(name, def);
field.set(this, value);
$().info(name + ": " + value);
} catch (IllegalAccessException ex) {
$().severe("Could not get config node: " + name);
}
}
}
$().info("
if (servers.get(defaultServerName) == null) {
throw new IllegalArgumentException("Server '" + defaultServerName + "' not defined");
}
for (String server : forcedServers.values()) {
if (!servers.containsKey(server)) {
throw new IllegalArgumentException("Forced server " + server + " is not defined in servers");
}
}
reconnect.createNewFile();
try (FileInputStream recon = new FileInputStream(reconnect)) {
reconnectLocations = (Map) yaml.load(recon);
}
if (reconnectLocations == null) {
reconnectLocations = new LinkedHashMap<>();
}
} catch (IOException ex) {
$().severe("Could not load config!");
ex.printStackTrace();
}
}
private <T> T get(String path, T def) {
if (!config.containsKey(path)) {
config.put(path, def);
save(file, config);
}
return (T) config.get(path);
}
private void save(File fileToSave, Map toSave) {
try {
try (FileWriter wr = new FileWriter(fileToSave)) {
yaml.dump(toSave, wr);
}
} catch (IOException ex) {
$().severe("Could not save config file " + fileToSave);
ex.printStackTrace();
}
}
/**
* Get which server a user should be connected to, taking into account their
* name and virtual host.
*
* @param user to get a server for
* @param requestedHost the host which they connected to
* @return the name of the server which they should be connected to.
*/
public String getServer(String user, String requestedHost) {
String server = forcedServers.get(requestedHost);
if (server == null) {
server = reconnectLocations.get(user);
}
if (server == null) {
server = servers.get(defaultServerName);
}
return server;
}
/**
* Save the last server which the user was on.
*
* @param user the name of the user
* @param server which they were last on
*/
public void setServer(UserConnection user, String server) {
reconnectLocations.put(user.username, server);
}
/**
* Gets the connectable address of a server defined in the configuration.
*
* @param name the friendly name of a server
* @return the usable {@link InetSocketAddress} mapped to this server
*/
public InetSocketAddress getServer(String name) {
String server = servers.get((name == null) ? defaultServerName : name);
return (server != null) ? Util.getAddr(server) : getServer(null);
}
/**
* Save the current mappings of users to servers.
*/
public void saveHosts() {
save(reconnect, reconnectLocations);
$().info("Saved reconnect locations to " + reconnect);
}
public Permission getPermission(CommandSender sender) {
Permission permission = Permission.DEFAULT;
if (admins.contains(sender.getName()) || sender instanceof ConsoleCommandSender) {
permission = Permission.ADMIN;
} else if (moderators.contains(sender.getName())) {
permission = Permission.MODERATOR;
}
return permission;
}
} |
package net.mingsoft.config;
import java.io.File;
import org.springframework.aop.Advisor;
import net.mingsoft.basic.filter.XSSEscapeFilter;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.JdkRegexpMethodPointcut;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.context.request.RequestContextListener;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.alibaba.druid.support.spring.stat.BeanTypeAutoProxyCreator;
import com.alibaba.druid.support.spring.stat.DruidStatInterceptor;
import net.mingsoft.basic.interceptor.ActionInterceptor;
import net.mingsoft.basic.util.BasicUtil;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Bean
public ActionInterceptor actionInterceptor() {
return new ActionInterceptor();
}
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseRegisteredSuffixPatternMatch(true);
}
/**
* rest apispring mvc
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
/**
* druidServlet
*/
@Bean
public ServletRegistrationBean druidServletRegistration() {
ServletRegistrationBean registration = new ServletRegistrationBean(new StatViewServlet());
/**
* druid URI
*/
@Bean
public FilterRegistrationBean druidStatFilter() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
/**
* druid
*/
@Bean
public DruidStatInterceptor druidStatInterceptor() {
return new DruidStatInterceptor();
}
@Bean
public JdkRegexpMethodPointcut druidStatPointcut() {
JdkRegexpMethodPointcut druidStatPointcut = new JdkRegexpMethodPointcut();
String patterns = "net.mingsoft.*.biz.*";
// set
druidStatPointcut.setPatterns(patterns);
return druidStatPointcut;
}
/**
* druid
*/
@Bean
public BeanTypeAutoProxyCreator beanTypeAutoProxyCreator() {
BeanTypeAutoProxyCreator beanTypeAutoProxyCreator = new BeanTypeAutoProxyCreator();
beanTypeAutoProxyCreator.setTargetBeanType(DruidDataSource.class);
beanTypeAutoProxyCreator.setInterceptorNames("druidStatInterceptor");
return beanTypeAutoProxyCreator;
}
/**
* druid druidStatPointcut
*
* @return
*/
@Bean
public Advisor druidStatAdvisor() {
return new DefaultPointcutAdvisor(druidStatPointcut(), druidStatInterceptor());
}
/**
* xssFilter
*/
// @Bean
// public FilterRegistrationBean xssFilterRegistration() {
// XSSEscapeFilter xssFilter = new XSSEscapeFilter();
// FilterRegistrationBean registration = new FilterRegistrationBean(xssFilter);
/**
* RequestContextListener
*/
@Bean
public ServletListenerRegistrationBean<RequestContextListener> requestContextListenerRegistration() {
return new ServletListenerRegistrationBean<>(new RequestContextListener());
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("forward:/index");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
WebMvcConfigurer.super.addViewControllers(registry);
}
} |
package net.sf.jabref.gui;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.MouseAdapter;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.*;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import net.sf.jabref.*;
import net.sf.jabref.bibtex.EntryTypes;
import net.sf.jabref.exporter.*;
import net.sf.jabref.gui.actions.*;
import net.sf.jabref.gui.desktop.JabRefDesktop;
import net.sf.jabref.gui.keyboard.KeyBinding;
import net.sf.jabref.gui.keyboard.KeyBindingRepository;
import net.sf.jabref.gui.keyboard.KeyBindingsDialog;
import net.sf.jabref.gui.menus.ChangeEntryTypeMenu;
import net.sf.jabref.gui.menus.help.DonateAction;
import net.sf.jabref.gui.worker.AbstractWorker;
import net.sf.jabref.gui.worker.MarkEntriesAction;
import net.sf.jabref.gui.preftabs.PreferencesDialog;
import net.sf.jabref.gui.util.FocusRequester;
import net.sf.jabref.gui.util.PositionWindow;
import net.sf.jabref.importer.*;
import net.sf.jabref.importer.fetcher.GeneralFetcher;
import net.sf.jabref.logic.logging.GuiAppender;
import net.sf.jabref.logic.CustomEntryTypesManager;
import net.sf.jabref.logic.integrity.IntegrityCheck;
import net.sf.jabref.logic.integrity.IntegrityMessage;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.logic.preferences.LastFocusedTabPreferences;
import net.sf.jabref.logic.util.OS;
import net.sf.jabref.logic.util.io.FileUtil;
import net.sf.jabref.model.database.BibDatabase;
import net.sf.jabref.model.entry.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import net.sf.jabref.external.ExternalFileTypeEditor;
import net.sf.jabref.external.push.PushToApplicationButton;
import net.sf.jabref.external.push.PushToApplications;
import net.sf.jabref.groups.EntryTableTransferHandler;
import net.sf.jabref.groups.GroupSelector;
import net.sf.jabref.gui.menus.help.ForkMeOnGitHubAction;
import net.sf.jabref.gui.help.HelpAction;
import net.sf.jabref.gui.help.HelpDialog;
import net.sf.jabref.gui.journals.ManageJournalsAction;
import net.sf.jabref.openoffice.OpenOfficePanel;
import net.sf.jabref.specialfields.Printed;
import net.sf.jabref.specialfields.Priority;
import net.sf.jabref.specialfields.Quality;
import net.sf.jabref.specialfields.Rank;
import net.sf.jabref.specialfields.ReadStatus;
import net.sf.jabref.specialfields.Relevance;
import net.sf.jabref.specialfields.SpecialFieldsUtils;
import net.sf.jabref.sql.importer.DbImportAction;
import net.sf.jabref.util.ManageKeywordsAction;
import net.sf.jabref.util.MassSetFieldAction;
import com.jgoodies.looks.HeaderStyle;
import com.jgoodies.looks.Options;
import osx.macadapter.MacAdapter;
/**
* The main window of the application.
*/
public class JabRefFrame extends JFrame implements OutputPrinter {
private static final Log LOGGER = LogFactory.getLog(JabRefFrame.class);
private static final boolean biblatexMode = Globals.prefs.getBoolean(JabRefPreferences.BIBLATEX_MODE);
final JSplitPane contentPane = new JSplitPane();
private final JabRefPreferences prefs = Globals.prefs;
private PreferencesDialog prefsDialog;
private int lastTabbedPanelSelectionIndex = -1;
// The sidepane manager takes care of populating the sidepane.
public SidePaneManager sidePaneManager;
public JTabbedPane tabbedPane; // initialized at constructor
private final Insets marg = new Insets(1, 0, 2, 0);
private final JabRef jabRef;
private PositionWindow pw;
private final GeneralAction checkIntegrity = new GeneralAction(Actions.CHECK_INTEGRITY, Localization.menuTitle("Check integrity")) {
@Override
public void actionPerformed(ActionEvent e) {
IntegrityCheck check = new IntegrityCheck();
List<IntegrityMessage> messages = check.checkBibtexDatabase(getCurrentBasePanel().database());
if (messages.isEmpty()) {
JOptionPane.showMessageDialog(getCurrentBasePanel(), Localization.lang("No problems found."));
} else {
// prepare data model
Object[][] model = new Object[messages.size()][3];
int i = 0;
for (IntegrityMessage message : messages) {
model[i][0] = message.getEntry().getCiteKey();
model[i][1] = message.getFieldName();
model[i][2] = message.getMessage();
i++;
}
// construct view
JTable table = new JTable(
model,
new Object[]{"key", "field", "message"}
);
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
ListSelectionModel selectionModel = table.getSelectionModel();
selectionModel.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
String citeKey = (String) model[table.getSelectedRow()][0];
String fieldName = (String) model[table.getSelectedRow()][1];
getCurrentBasePanel().editEntryByKeyAndFocusField(citeKey, fieldName);
}
}
});
table.getColumnModel().getColumn(0).setPreferredWidth(80);
table.getColumnModel().getColumn(1).setPreferredWidth(30);
table.getColumnModel().getColumn(2).setPreferredWidth(250);
table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
JScrollPane scrollPane = new JScrollPane(table);
String title = Localization.lang("%0 problem(s) found", String.valueOf(messages.size()));
JDialog dialog = new JDialog(JabRefFrame.this, title, false);
dialog.add(scrollPane);
dialog.setSize(600, 500);
// show view
dialog.setVisible(true);
}
}
};
class ToolBar extends JToolBar {
void addAction(Action a) {
JButton b = new JButton(a);
b.setText(null);
if (!OS.OS_X) {
b.setMargin(marg);
}
// create a disabled Icon for FontBasedIcons as Swing does not automatically create one
Object obj = a.getValue(Action.LARGE_ICON_KEY);
if ((obj instanceof IconTheme.FontBasedIcon)) {
b.setDisabledIcon(((IconTheme.FontBasedIcon) obj).createDisabledIcon());
}
add(b);
}
void addJToogleButton(JToggleButton button) {
button.setText(null);
if (!OS.OS_X) {
button.setMargin(marg);
}
Object obj = button.getAction().getValue(Action.LARGE_ICON_KEY);
if ((obj instanceof IconTheme.FontBasedIcon)) {
button.setDisabledIcon(((IconTheme.FontBasedIcon) obj).createDisabledIcon());
}
add(button);
}
}
private final ToolBar tlb = new ToolBar();
private final JMenuBar mb = new JMenuBar();
private final GridBagLayout gbl = new GridBagLayout();
private final GridBagConstraints con = new GridBagConstraints();
final JLabel statusLine = new JLabel("", SwingConstants.LEFT);
private final JLabel statusLabel = new JLabel(
Localization.lang("Status")
+ ':', SwingConstants.LEFT);
private final JProgressBar progressBar = new JProgressBar();
private final FileHistoryMenu fileHistory = new FileHistoryMenu(prefs, this);
// The help window.
public final HelpDialog helpDiag = new HelpDialog(this);
// Here we instantiate menu/toolbar actions. Actions regarding
// the currently open database are defined as a GeneralAction
// with a unique command string. This causes the appropriate
// BasePanel's runCommand() method to be called with that command.
// Note: GeneralAction's constructor automatically gets translations
// for the name and message strings.
/* References to the toggle buttons in the toolbar */
// the groups interface
public JToggleButton groupToggle;
public JToggleButton previewToggle;
public JToggleButton fetcherToggle;
final OpenDatabaseAction open = new OpenDatabaseAction(this, true);
private final AbstractAction editModeAction = new EditModeAction();
private final AbstractAction quit = new CloseAction();
private final AbstractAction selectKeys = new SelectKeysAction();
private final AbstractAction newDatabaseAction = new NewDatabaseAction(this);
private final AbstractAction newSubDatabaseAction = new NewSubDatabaseAction(this);
private final AbstractAction forkMeOnGitHubAction = new ForkMeOnGitHubAction();
private final AbstractAction donationAction = new DonateAction();
private final AbstractAction help = new HelpAction(Localization.menuTitle("JabRef help"), helpDiag,
GUIGlobals.baseFrameHelp, Localization.lang("JabRef help"),
Globals.getKeyPrefs().getKey(KeyBinding.HELP));
private final AbstractAction contents = new HelpAction(Localization.menuTitle("Help contents"), helpDiag,
GUIGlobals.helpContents, Localization.lang("Help contents"),
IconTheme.JabRefIcon.HELP_CONTENTS.getIcon());
private final AbstractAction about = new HelpAction(Localization.menuTitle("About JabRef"), helpDiag,
GUIGlobals.aboutPage, Localization.lang("About JabRef"),
IconTheme.getImage("about"));
private final AbstractAction editEntry = new GeneralAction(Actions.EDIT, Localization.menuTitle("Edit entry"),
Localization.lang("Edit entry"), Globals.getKeyPrefs().getKey(KeyBinding.EDIT_ENTRY), IconTheme.JabRefIcon.EDIT_ENTRY.getIcon());
private final AbstractAction focusTable = new GeneralAction(Actions.FOCUS_TABLE,
Localization.menuTitle("Focus entry table"),
Localization.lang("Move the keyboard focus to the entry table"), Globals.getKeyPrefs().getKey(KeyBinding.FOCUS_ENTRY_TABLE));
private final AbstractAction save = new GeneralAction(Actions.SAVE, Localization.menuTitle("Save database"),
Localization.lang("Save database"), Globals.getKeyPrefs().getKey(KeyBinding.SAVE_DATABASE), IconTheme.JabRefIcon.SAVE.getIcon());
private final AbstractAction saveAs = new GeneralAction(Actions.SAVE_AS,
Localization.menuTitle("Save database as ..."), Localization.lang("Save database as ..."),
Globals.getKeyPrefs().getKey(KeyBinding.SAVE_DATABASE_AS));
private final AbstractAction saveAll = new SaveAllAction(JabRefFrame.this);
private final AbstractAction saveSelectedAs = new GeneralAction(Actions.SAVE_SELECTED_AS,
Localization.menuTitle("Save selected as ..."), Localization.lang("Save selected as ..."));
private final AbstractAction saveSelectedAsPlain = new GeneralAction(Actions.SAVE_SELECTED_AS_PLAIN,
Localization.menuTitle("Save selected as plain BibTeX..."),
Localization.lang("Save selected as plain BibTeX..."));
private final AbstractAction exportAll = ExportFormats.getExportAction(this, false);
private final AbstractAction exportSelected = ExportFormats.getExportAction(this, true);
private final AbstractAction importCurrent = ImportFormats.getImportAction(this, false);
private final AbstractAction importNew = ImportFormats.getImportAction(this, true);
public final AbstractAction nextTab = new ChangeTabAction(true);
public final AbstractAction prevTab = new ChangeTabAction(false);
private final AbstractAction sortTabs = new SortTabsAction(this);
private final AbstractAction undo = new GeneralAction(Actions.UNDO, Localization.menuTitle("Undo"),
Localization.lang("Undo"), Globals.getKeyPrefs().getKey(KeyBinding.UNDO), IconTheme.JabRefIcon.UNDO.getIcon());
private final AbstractAction redo = new GeneralAction(Actions.REDO, Localization.menuTitle("Redo"),
Localization.lang("Redo"), Globals.getKeyPrefs().getKey(KeyBinding.REDO), IconTheme.JabRefIcon.REDO.getIcon());
final AbstractAction forward = new GeneralAction(Actions.FORWARD, Localization.menuTitle("Forward"),
Localization.lang("Forward"), Globals.getKeyPrefs().getKey(KeyBinding.FORWARD), IconTheme.JabRefIcon.RIGHT.getIcon());
final AbstractAction back = new GeneralAction(Actions.BACK, Localization.menuTitle("Back"),
Localization.lang("Back"), Globals.getKeyPrefs().getKey(KeyBinding.BACK), IconTheme.JabRefIcon.LEFT.getIcon());
private final AbstractAction deleteEntry = new GeneralAction(Actions.DELETE, Localization.menuTitle("Delete entry"),
Localization.lang("Delete entry"), Globals.getKeyPrefs().getKey(KeyBinding.DELETE_ENTRY), IconTheme.JabRefIcon.DELETE_ENTRY.getIcon());
private final AbstractAction copy = new EditAction(Actions.COPY, Localization.menuTitle("Copy"),
Localization.lang("Copy"), Globals.getKeyPrefs().getKey(KeyBinding.COPY), IconTheme.JabRefIcon.COPY.getIcon());
private final AbstractAction paste = new EditAction(Actions.PASTE, Localization.menuTitle("Paste"),
Localization.lang("Paste"), Globals.getKeyPrefs().getKey(KeyBinding.PASTE), IconTheme.JabRefIcon.PASTE.getIcon());
private final AbstractAction cut = new EditAction(Actions.CUT, Localization.menuTitle("Cut"),
Localization.lang("Cut"), Globals.getKeyPrefs().getKey(KeyBinding.CUT), IconTheme.JabRefIcon.CUT.getIcon());
private final AbstractAction mark = new GeneralAction(Actions.MARK_ENTRIES, Localization.menuTitle("Mark entries"),
Localization.lang("Mark entries"), Globals.getKeyPrefs().getKey(KeyBinding.MARK_ENTRIES), IconTheme.JabRefIcon.MARK_ENTRIES.getIcon());
private final AbstractAction unmark = new GeneralAction(Actions.UNMARK_ENTRIES,
Localization.menuTitle("Unmark entries"), Localization.lang("Unmark entries"),
Globals.getKeyPrefs().getKey(KeyBinding.UNMARK_ENTRIES), IconTheme.JabRefIcon.UNMARK_ENTRIES.getIcon());
private final AbstractAction unmarkAll = new GeneralAction(Actions.UNMARK_ALL, Localization.menuTitle("Unmark all"));
private final AbstractAction toggleRelevance = new GeneralAction(
Relevance.getInstance().getValues().get(0).getActionName(),
Relevance.getInstance().getValues().get(0).getMenuString(),
Relevance.getInstance().getValues().get(0).getToolTipText(),
IconTheme.JabRefIcon.RELEVANCE.getIcon());
private final AbstractAction toggleQualityAssured = new GeneralAction(
Quality.getInstance().getValues().get(0).getActionName(),
Quality.getInstance().getValues().get(0).getMenuString(),
Quality.getInstance().getValues().get(0).getToolTipText(),
IconTheme.JabRefIcon.QUALITY_ASSURED.getIcon());
private final AbstractAction togglePrinted = new GeneralAction(
Printed.getInstance().getValues().get(0).getActionName(),
Printed.getInstance().getValues().get(0).getMenuString(),
Printed.getInstance().getValues().get(0).getToolTipText(),
IconTheme.JabRefIcon.PRINTED.getIcon());
private final AbstractAction manageSelectors = new GeneralAction(Actions.MANAGE_SELECTORS,
Localization.menuTitle("Manage content selectors"));
private final AbstractAction saveSessionAction = new SaveSessionAction();
public final AbstractAction loadSessionAction = new LoadSessionAction();
private final AbstractAction normalSearch = new GeneralAction(Actions.SEARCH, Localization.menuTitle("Search"),
Localization.lang("Search"), Globals.getKeyPrefs().getKey(KeyBinding.SEARCH), IconTheme.JabRefIcon.SEARCH.getIcon());
private final AbstractAction copyKey = new GeneralAction(Actions.COPY_KEY, Localization.menuTitle("Copy BibTeX key"),
Globals.getKeyPrefs().getKey(KeyBinding.COPY_BIBTEX_KEY));
private final AbstractAction copyCiteKey = new GeneralAction(Actions.COPY_CITE_KEY, Localization.menuTitle(
"Copy \\cite{BibTeX key}"),
Globals.getKeyPrefs().getKey(KeyBinding.COPY_CITE_BIBTEX_KEY));
private final AbstractAction copyKeyAndTitle = new GeneralAction(Actions.COPY_KEY_AND_TITLE,
Localization.menuTitle("Copy BibTeX key and title"),
Globals.getKeyPrefs().getKey(KeyBinding.COPY_BIBTEX_KEY_AND_TITLE));
private final AbstractAction mergeDatabaseAction = new GeneralAction(Actions.MERGE_DATABASE,
Localization.menuTitle("Append database"),
Localization.lang("Append contents from a BibTeX database into the currently viewed database"));
private final AbstractAction selectAll = new GeneralAction(Actions.SELECT_ALL, Localization.menuTitle("Select all"),
Globals.getKeyPrefs().getKey(KeyBinding.SELECT_ALL));
private final AbstractAction replaceAll = new GeneralAction(Actions.REPLACE_ALL,
Localization.menuTitle("Replace string"), Globals.getKeyPrefs().getKey(KeyBinding.REPLACE_STRING));
private final AbstractAction editPreamble = new GeneralAction(Actions.EDIT_PREAMBLE,
Localization.menuTitle("Edit preamble"),
Localization.lang("Edit preamble"),
Globals.getKeyPrefs().getKey(KeyBinding.EDIT_PREAMBLE));
private final AbstractAction editStrings = new GeneralAction(Actions.EDIT_STRINGS,
Localization.menuTitle("Edit strings"),
Localization.lang("Edit strings"),
Globals.getKeyPrefs().getKey(KeyBinding.EDIT_STRINGS),
IconTheme.JabRefIcon.EDIT_STRINGS.getIcon());
private final AbstractAction toggleToolbar = new AbstractAction(Localization.menuTitle("Hide/show toolbar")) {
{
putValue(Action.ACCELERATOR_KEY, Globals.getKeyPrefs().getKey(KeyBinding.HIDE_SHOW_TOOLBAR));
putValue(Action.SHORT_DESCRIPTION, Localization.lang("Hide/show toolbar"));
}
@Override
public void actionPerformed(ActionEvent e) {
tlb.setVisible(!tlb.isVisible());
}
};
private final AbstractAction toggleGroups = new GeneralAction(Actions.TOGGLE_GROUPS,
Localization.menuTitle("Toggle groups interface"),
Localization.lang("Toggle groups interface"),
Globals.getKeyPrefs().getKey(KeyBinding.TOGGLE_GROUPS_INTERFACE),
IconTheme.JabRefIcon.TOGGLE_GROUPS.getIcon());
private final AbstractAction addToGroup = new GeneralAction(Actions.ADD_TO_GROUP, Localization.lang("Add to group"));
private final AbstractAction removeFromGroup = new GeneralAction(Actions.REMOVE_FROM_GROUP,
Localization.lang("Remove from group"));
private final AbstractAction moveToGroup = new GeneralAction(Actions.MOVE_TO_GROUP, Localization.lang("Move to group"));
private final AbstractAction togglePreview = new GeneralAction(Actions.TOGGLE_PREVIEW,
Localization.menuTitle("Toggle entry preview"),
Localization.lang("Toggle entry preview"),
Globals.getKeyPrefs().getKey(KeyBinding.TOGGLE_ENTRY_PREVIEW),
IconTheme.JabRefIcon.TOGGLE_ENTRY_PREVIEW.getIcon());
private final AbstractAction toggleHighlightAny = new GeneralAction(Actions.TOGGLE_HIGHLIGHTS_GROUPS_MATCHING_ANY,
Localization.menuTitle("Highlight groups matching any selected entry"),
Localization.lang("Highlight groups matching any selected entry"));
private final AbstractAction toggleHighlightAll = new GeneralAction(Actions.TOGGLE_HIGHLIGHTS_GROUPS_MATCHING_ALL,
Localization.menuTitle("Highlight groups matching all selected entries"),
Localization.lang("Highlight groups matching all selected entries"));
final AbstractAction switchPreview = new GeneralAction(Actions.SWITCH_PREVIEW,
Localization.menuTitle("Switch preview layout"),
Globals.getKeyPrefs().getKey(KeyBinding.SWITCH_PREVIEW_LAYOUT));
private final AbstractAction makeKeyAction = new GeneralAction(Actions.MAKE_KEY,
Localization.menuTitle("Autogenerate BibTeX keys"),
Localization.lang("Autogenerate BibTeX keys"),
Globals.getKeyPrefs().getKey(KeyBinding.AUTOGENERATE_BIBTEX_KEYS),
IconTheme.JabRefIcon.MAKE_KEY.getIcon());
private final AbstractAction writeXmpAction = new GeneralAction(Actions.WRITE_XMP,
Localization.menuTitle("Write XMP-metadata to PDFs"),
Localization.lang("Will write XMP-metadata to the PDFs linked from selected entries."),
Globals.getKeyPrefs().getKey(KeyBinding.WRITE_XMP));
private final AbstractAction openFolder = new GeneralAction(Actions.OPEN_FOLDER,
Localization.menuTitle("Open folder"), Localization.lang("Open folder"),
Globals.getKeyPrefs().getKey(KeyBinding.OPEN_FOLDER));
private final AbstractAction openFile = new GeneralAction(Actions.OPEN_EXTERNAL_FILE,
Localization.menuTitle("Open file"),
Localization.lang("Open file"),
Globals.getKeyPrefs().getKey(KeyBinding.OPEN_FILE),
IconTheme.JabRefIcon.FILE.getIcon());
private final AbstractAction openUrl = new GeneralAction(Actions.OPEN_URL,
Localization.menuTitle("Open URL or DOI"),
Localization.lang("Open URL or DOI"),
Globals.getKeyPrefs().getKey(KeyBinding.OPEN_URL_OR_DOI),
IconTheme.JabRefIcon.WWW.getIcon());
private final AbstractAction dupliCheck = new GeneralAction(Actions.DUPLI_CHECK,
Localization.menuTitle("Find duplicates"), IconTheme.JabRefIcon.FIND_DUPLICATES.getIcon());
private final AbstractAction plainTextImport = new GeneralAction(Actions.PLAIN_TEXT_IMPORT,
Localization.menuTitle("New entry from plain text"),
Globals.getKeyPrefs().getKey(KeyBinding.NEW_FROM_PLAIN_TEXT));
private final AbstractAction customExpAction = new CustomizeExportsAction();
private final AbstractAction customImpAction = new CustomizeImportsAction();
private final AbstractAction customFileTypesAction = ExternalFileTypeEditor.getAction(this);
private final AbstractAction exportToClipboard = new GeneralAction(Actions.EXPORT_TO_CLIPBOARD,
Localization.menuTitle("Export selected entries to clipboard"),
IconTheme.JabRefIcon.EXPORT_TO_CLIPBOARD.getIcon());
private final AbstractAction autoSetFile = new GeneralAction(Actions.AUTO_SET_FILE,
Localization.lang("Synchronize file links"),
Globals.getKeyPrefs().getKey(KeyBinding.SYNCHRONIZE_FILES));
private final AbstractAction abbreviateMedline = new GeneralAction(Actions.ABBREVIATE_MEDLINE,
Localization.menuTitle("Abbreviate journal names (MEDLINE)"),
Localization.lang("Abbreviate journal names of the selected entries (MEDLINE abbreviation)"));
private final AbstractAction abbreviateIso = new GeneralAction(Actions.ABBREVIATE_ISO,
Localization.menuTitle("Abbreviate journal names (ISO)"),
Localization.lang("Abbreviate journal names of the selected entries (ISO abbreviation)"),
Globals.getKeyPrefs().getKey(KeyBinding.ABBREVIATE));
private final AbstractAction unabbreviate = new GeneralAction(Actions.UNABBREVIATE,
Localization.menuTitle("Unabbreviate journal names"),
Localization.lang("Unabbreviate journal names of the selected entries"),
Globals.getKeyPrefs().getKey(KeyBinding.UNABBREVIATE));
private final AbstractAction manageJournals = new ManageJournalsAction(this);
private final AbstractAction databaseProperties = new DatabasePropertiesAction();
private final AbstractAction bibtexKeyPattern = new BibtexKeyPatternAction();
private final AbstractAction errorConsole = new ErrorConsoleAction(this, Globals.streamEavesdropper, GuiAppender.cache);
private final AbstractAction dbConnect = new GeneralAction(Actions.DB_CONNECT,
Localization.menuTitle("Connect to external SQL database"),
Localization.lang("Connect to external SQL database"));
private final AbstractAction dbExport = new GeneralAction(Actions.DB_EXPORT,
Localization.menuTitle("Export to external SQL database"),
Localization.lang("Export to external SQL database"));
private final AbstractAction cleanupEntries = new GeneralAction(Actions.CLEANUP,
Localization.menuTitle("Cleanup entries"),
Localization.lang("Cleanup entries"),
Globals.getKeyPrefs().getKey(KeyBinding.CLEANUP),
IconTheme.JabRefIcon.CLEANUP_ENTRIES.getIcon());
private final AbstractAction mergeEntries = new GeneralAction(Actions.MERGE_ENTRIES,
Localization.menuTitle("Merge entries"),
Localization.lang("Merge entries"),
IconTheme.JabRefIcon.MERGE_ENTRIES.getIcon());
private final AbstractAction dbImport = new DbImportAction(this).getAction();
private final AbstractAction downloadFullText = new GeneralAction(Actions.DOWNLOAD_FULL_TEXT,
Localization.menuTitle("Look up full text document"),
Localization.lang("Follow DOI or URL link and try to locate PDF full text document"));
private final AbstractAction increaseFontSize = new IncreaseTableFontSizeAction();
private final AbstractAction decreseFontSize = new DecreaseTableFontSizeAction();
private final AbstractAction resolveDuplicateKeys = new GeneralAction(Actions.RESOLVE_DUPLICATE_KEYS,
Localization.menuTitle("Resolve duplicate BibTeX keys"),
Localization.lang("Find and remove duplicate BibTeX keys"),
Globals.getKeyPrefs().getKey(KeyBinding.RESOLVE_DUPLICATE_BIBTEX_KEYS));
private final AbstractAction sendAsEmail = new GeneralAction(Actions.SEND_AS_EMAIL,
Localization.lang("Send as email"), IconTheme.JabRefIcon.EMAIL.getIcon());
final MassSetFieldAction massSetField = new MassSetFieldAction(this);
final ManageKeywordsAction manageKeywords = new ManageKeywordsAction(this);
private final GeneralAction findUnlinkedFiles = new GeneralAction(
FindUnlinkedFilesDialog.ACTION_COMMAND,
FindUnlinkedFilesDialog.ACTION_MENU_TITLE, FindUnlinkedFilesDialog.ACTION_SHORT_DESCRIPTION,
Globals.getKeyPrefs().getKey(KeyBinding.FIND_UNLINKED_FILES)
);
private final AutoLinkFilesAction autoLinkFile = new AutoLinkFilesAction();
private PushToApplicationButton pushExternalButton;
private GeneralFetcher generalFetcher;
private final List<Action> fetcherActions = new LinkedList<>();
public GroupSelector groupSelector;
// The action for adding a new entry of unspecified type.
private final NewEntryAction newEntryAction = new NewEntryAction(this, Globals.getKeyPrefs().getKey(KeyBinding.NEW_ENTRY));
private final List<NewEntryAction> newSpecificEntryAction = getNewEntryActions();
private List<NewEntryAction> getNewEntryActions() {
List<NewEntryAction> actions = new ArrayList<>();
if (biblatexMode) {
for (String key : EntryTypes.getAllTypes()) {
actions.add(new NewEntryAction(this, key));
}
} else {
// Bibtex
for (EntryType type : BibtexEntryTypes.ALL) {
KeyStroke keyStroke = ChangeEntryTypeMenu.entryShortCuts.get(type.getName());
if (keyStroke == null) {
actions.add(new NewEntryAction(this, type.getName()));
} else {
actions.add(new NewEntryAction(this, type.getName(), keyStroke));
}
}
// ieeetran
for (EntryType type : IEEETranEntryTypes.ALL) {
actions.add(new NewEntryAction(this, type.getName()));
}
// custom types
for (EntryType type : CustomEntryTypesManager.ALL) {
actions.add(new NewEntryAction(this, type.getName()));
}
}
return actions;
}
public JabRefFrame(JabRef jabRef) {
this.jabRef = jabRef;
init();
updateEnabledState();
}
private JPopupMenu tabPopupMenu() {
JPopupMenu popupMenu = new JPopupMenu();
// Close actions
JMenuItem close = new JMenuItem(Localization.lang("Close"));
JMenuItem closeOthers = new JMenuItem(Localization.lang("Close Others"));
JMenuItem closeAll = new JMenuItem(Localization.lang("Close All"));
close.addActionListener(closeDatabaseAction);
closeOthers.addActionListener(closeOtherDatabasesAction);
closeAll.addActionListener(closeAllDatabasesAction);
popupMenu.add(close);
popupMenu.add(closeOthers);
popupMenu.add(closeAll);
popupMenu.addSeparator();
JMenuItem databasePropertiesBtn = new JMenuItem(Localization.lang("Database properties"));
databasePropertiesBtn.addActionListener(databaseProperties);
popupMenu.add(databasePropertiesBtn);
JMenuItem bibtexKeyPatternBtn = new JMenuItem(Localization.lang("Bibtex key patterns"));
bibtexKeyPatternBtn.addActionListener(bibtexKeyPattern);
popupMenu.add(bibtexKeyPatternBtn);
JMenuItem manageSelectorsBtn = new JMenuItem(Localization.lang("Manage content selectors"));
manageSelectorsBtn.addActionListener(manageSelectors);
popupMenu.add(manageSelectorsBtn);
return popupMenu;
}
private void init() {
tabbedPane = new DragDropPopupPane(tabPopupMenu());
MyGlassPane glassPane = new MyGlassPane();
setGlassPane(glassPane);
setTitle(GUIGlobals.frameTitle);
setIconImage(new ImageIcon(IconTheme.getIconUrl("jabrefIcon48")).getImage());
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
if (OS.OS_X) {
setState(Frame.ICONIFIED);
} else {
new CloseAction().actionPerformed(null);
}
}
});
initSidePane();
initLayout();
initActions();
// Show the toolbar if it was visible at last shutdown:
tlb.setVisible(Globals.prefs.getBoolean(JabRefPreferences.TOOLBAR_VISIBLE));
setBounds(GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds());
pw = new PositionWindow(this, JabRefPreferences.POS_X, JabRefPreferences.POS_Y, JabRefPreferences.SIZE_X,
JabRefPreferences.SIZE_Y);
positionWindowOnScreen();
// Set up a ComponentListener that saves the last size and position of the dialog
this.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
// Save dialog position
pw.storeWindowPosition();
}
@Override
public void componentMoved(ComponentEvent e) {
// Save dialog position
pw.storeWindowPosition();
}
});
tabbedPane.setBorder(null);
tabbedPane.setForeground(GUIGlobals.inActiveTabbed);
/*
* The following state listener makes sure focus is registered with the
* correct database when the user switches tabs. Without this,
* cut/paste/copy operations would some times occur in the wrong tab.
*/
tabbedPane.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
markActiveBasePanel();
BasePanel bp = getCurrentBasePanel();
if (bp != null) {
groupToggle.setSelected(sidePaneManager.isComponentVisible("groups"));
previewToggle.setSelected(Globals.prefs.getBoolean(JabRefPreferences.PREVIEW_ENABLED));
fetcherToggle.setSelected(sidePaneManager.isComponentVisible(generalFetcher.getTitle()));
Globals.focusListener.setFocused(bp.mainTable);
setWindowTitle();
// Update search autocompleter with information for the correct database:
bp.updateSearchManager();
// Set correct enabled state for Back and Forward actions:
bp.setBackAndForwardEnabledState();
new FocusRequester(bp.mainTable);
}
}
});
//Note: The registration of Apple event is at the end of initialization, because
//if the events happen too early (ie when the window is not initialized yet), the
//opened (double-clicked) documents are not displayed.
if (OS.OS_X) {
try {
new MacAdapter().registerMacEvents(this);
} catch (Exception e) {
LOGGER.fatal("Could not interface with Mac OS X methods.", e);
}
}
}
private void positionWindowOnScreen() {
if (!prefs.getBoolean(JabRefPreferences.WINDOW_MAXIMISED)) {
pw.setWindowPosition();
}
}
/**
* Tries to open a browser with the given URL
* <p>
* All errors are logged
*
* @param url the url to open
*/
public void openBrowser(String url) {
try {
JabRefDesktop.openBrowser(url);
output(Localization.lang("External viewer called") + '.');
} catch (IOException ex) {
output(Localization.lang("Error") + ": " + ex.getMessage());
LOGGER.debug("Cannot open browser.", ex);
}
}
/**
* Sets the title of the main window.
*/
public void setWindowTitle() {
BasePanel panel = getCurrentBasePanel();
String mode = biblatexMode ? " (" + Localization.lang("%0 mode", "BibLaTeX") + ")" : " (" + Localization.lang("%0 mode", "BibTeX") + ")";
// no database open
if (panel == null) {
setTitle(GUIGlobals.frameTitle + mode);
return;
}
String changeFlag = panel.isModified() ? "*" : "";
if (panel.getDatabaseFile() == null) {
setTitle(GUIGlobals.frameTitle + " - " + GUIGlobals.untitledTitle + changeFlag + mode);
} else {
String databaseFile = panel.getDatabaseFile().getPath();
setTitle(GUIGlobals.frameTitle + " - " + databaseFile + changeFlag + mode);
}
}
private void initSidePane() {
sidePaneManager = new SidePaneManager(this);
GUIGlobals.sidePaneManager = this.sidePaneManager;
GUIGlobals.helpDiag = this.helpDiag;
groupSelector = new GroupSelector(this, sidePaneManager);
generalFetcher = new GeneralFetcher(sidePaneManager, this);
sidePaneManager.register("groups", groupSelector);
}
/**
* The MacAdapter calls this method when a ".bib" file has been double-clicked from the Finder.
*/
public void openAction(String filePath) {
File file = new File(filePath);
// all the logic is done in openIt. Even raising an existing panel
open.openFile(file, true);
}
// General info dialog. The MacAdapter calls this method when "About"
// is selected from the application menu.
public void about() {
// reuse the normal about action
// null as parameter is OK as the code of actionPerformed does not rely on the data sent in the event.
about.actionPerformed(null);
}
// General preferences dialog. The MacAdapter calls this method when "Preferences..."
// is selected from the application menu.
public void preferences() {
//PrefsDialog.showPrefsDialog(JabRefFrame.this, prefs);
AbstractWorker worker = new AbstractWorker() {
@Override
public void run() {
output(Localization.lang("Opening preferences..."));
if (prefsDialog == null) {
prefsDialog = new PreferencesDialog(JabRefFrame.this, jabRef);
PositionWindow.placeDialog(prefsDialog, JabRefFrame.this);
} else {
prefsDialog.setValues();
}
}
@Override
public void update() {
prefsDialog.setVisible(true);
output("");
}
};
worker.getWorker().run();
worker.getCallBack().update();
}
public JabRefPreferences prefs() {
return prefs;
}
/**
* Tears down all things started by JabRef
* <p>
* FIXME: Currently some threads remain and therefore hinder JabRef to be closed properly
*
* @param filenames the filenames of all currently opened files - used for storing them if prefs openLastEdited is set to true
*/
private void tearDownJabRef(List<String> filenames) {
JabRefExecutorService.INSTANCE.shutdownEverything();
dispose();
if (getCurrentBasePanel() != null) {
getCurrentBasePanel().saveDividerLocation();
}
//prefs.putBoolean(JabRefPreferences.WINDOW_MAXIMISED, (getExtendedState()&MAXIMIZED_BOTH)>0);
prefs.putBoolean(JabRefPreferences.WINDOW_MAXIMISED, getExtendedState() == Frame.MAXIMIZED_BOTH);
prefs.putBoolean(JabRefPreferences.TOOLBAR_VISIBLE, tlb.isVisible());
// Store divider location for side pane:
int width = contentPane.getDividerLocation();
if (width > 0) {
prefs.putInt(JabRefPreferences.SIDE_PANE_WIDTH, width);
}
if (prefs.getBoolean(JabRefPreferences.OPEN_LAST_EDITED)) {
// Here we store the names of all current files. If
// there is no current file, we remove any
// previously stored filename.
if (filenames.isEmpty()) {
prefs.remove(JabRefPreferences.LAST_EDITED);
} else {
prefs.putStringList(JabRefPreferences.LAST_EDITED, filenames);
File focusedDatabase = getCurrentBasePanel().getDatabaseFile();
new LastFocusedTabPreferences(prefs).setLastFocusedTab(focusedDatabase);
}
}
fileHistory.storeHistory();
prefs.customExports.store();
prefs.customImports.store();
CustomEntryTypesManager.saveCustomEntryTypes(prefs);
// Clear autosave files:
if (Globals.autoSaveManager != null) {
Globals.autoSaveManager.clearAutoSaves();
}
prefs.flush();
// dispose all windows, even if they are not displayed anymore
for (Window window : Window.getWindows()) {
window.dispose();
}
// shutdown any timers that are may be active
if (Globals.autoSaveManager != null) {
Globals.stopAutoSaveManager();
}
}
/**
* General info dialog. The MacAdapter calls this method when "Quit"
* is selected from the application menu, Cmd-Q is pressed, or "Quit" is selected from the Dock.
* The function returns a boolean indicating if quitting is ok or not.
* <p>
* Non-OSX JabRef calls this when choosing "Quit" from the menu
* <p>
* SIDE EFFECT: tears down JabRef
*
* @return true if the user chose to quit; false otherwise
*/
public boolean quit() {
// Ask here if the user really wants to close, if the base
// has not been saved since last save.
boolean close = true;
List<String> filenames = new ArrayList<>();
if (tabbedPane.getTabCount() > 0) {
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
if (getBasePanelAt(i).isModified()) {
tabbedPane.setSelectedIndex(i);
String filename;
if (getBasePanelAt(i).getDatabaseFile() == null) {
filename = GUIGlobals.untitledTitle;
} else {
filename = getBasePanelAt(i).getDatabaseFile().getAbsolutePath();
}
int answer = showSaveDialog(filename);
if ((answer == JOptionPane.CANCEL_OPTION) ||
(answer == JOptionPane.CLOSED_OPTION)) {
return false;
}
if (answer == JOptionPane.YES_OPTION) {
// The user wants to save.
try {
//getCurrentBasePanel().runCommand("save");
SaveDatabaseAction saveAction = new SaveDatabaseAction(getCurrentBasePanel());
saveAction.runCommand();
if (saveAction.isCancelled() || !saveAction.isSuccess()) {
// The action was either cancelled or unsuccessful.
// Break!
output(Localization.lang("Unable to save database"));
close = false;
}
} catch (Throwable ex) {
// Something prevented the file
// from being saved. Break!!!
close = false;
break;
}
}
}
if (getBasePanelAt(i).getDatabaseFile() != null) {
filenames.add(getBasePanelAt(i).getDatabaseFile().getAbsolutePath());
}
}
}
if (close) {
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
if (getBasePanelAt(i).isSaving()) {
// There is a database still being saved, so we need to wait.
WaitForSaveOperation w = new WaitForSaveOperation(this);
w.show(); // This method won't return until cancelled or the save operation is done.
if (w.cancelled()) {
return false; // The user clicked cancel.
}
}
}
tearDownJabRef(filenames);
return true;
}
return false;
}
private void initLayout() {
tabbedPane.putClientProperty(Options.NO_CONTENT_BORDER_KEY, Boolean.TRUE);
setProgressBarVisible(false);
pushExternalButton = new PushToApplicationButton(this, PushToApplications.APPLICATIONS);
fillMenu();
createToolBar();
getContentPane().setLayout(gbl);
contentPane.setDividerSize(2);
contentPane.setBorder(null);
//getContentPane().setBackground(GUIGlobals.lightGray);
con.fill = GridBagConstraints.HORIZONTAL;
con.anchor = GridBagConstraints.WEST;
con.weightx = 1;
con.weighty = 0;
con.gridwidth = GridBagConstraints.REMAINDER;
//gbl.setConstraints(mb, con);
//getContentPane().add(mb);
setJMenuBar(mb);
con.anchor = GridBagConstraints.NORTH;
//con.gridwidth = 1;//GridBagConstraints.REMAINDER;;
gbl.setConstraints(tlb, con);
getContentPane().add(tlb);
Component lim = Box.createGlue();
gbl.setConstraints(lim, con);
//getContentPane().add(lim);
/*
JPanel empt = new JPanel();
empt.setBackground(GUIGlobals.lightGray);
gbl.setConstraints(empt, con);
getContentPane().add(empt);
con.insets = new Insets(1,0,1,1);
con.anchor = GridBagConstraints.EAST;
con.weightx = 0;
gbl.setConstraints(searchManager, con);
getContentPane().add(searchManager);*/
con.gridwidth = GridBagConstraints.REMAINDER;
con.weightx = 1;
con.weighty = 0;
con.fill = GridBagConstraints.BOTH;
con.anchor = GridBagConstraints.WEST;
con.insets = new Insets(0, 0, 0, 0);
lim = Box.createGlue();
gbl.setConstraints(lim, con);
getContentPane().add(lim);
//tabbedPane.setVisible(false);
//tabbedPane.setForeground(GUIGlobals.lightGray);
con.weighty = 1;
gbl.setConstraints(contentPane, con);
getContentPane().add(contentPane);
UIManager.put("TabbedPane.contentBorderInsets", new Insets(0,0,0,0));
contentPane.setRightComponent(tabbedPane);
contentPane.setLeftComponent(sidePaneManager.getPanel());
sidePaneManager.updateView();
JPanel status = new JPanel();
status.setLayout(gbl);
con.weighty = 0;
con.weightx = 0;
con.gridwidth = 1;
con.insets = new Insets(0, 2, 0, 0);
gbl.setConstraints(statusLabel, con);
status.add(statusLabel);
con.weightx = 1;
con.insets = new Insets(0, 4, 0, 0);
con.gridwidth = 1;
gbl.setConstraints(statusLine, con);
status.add(statusLine);
con.weightx = 0;
con.gridwidth = GridBagConstraints.REMAINDER;
con.insets = new Insets(2, 4, 2, 2);
gbl.setConstraints(progressBar, con);
status.add(progressBar);
con.weightx = 1;
con.gridwidth = GridBagConstraints.REMAINDER;
statusLabel.setForeground(GUIGlobals.entryEditorLabelColor.darker());
con.insets = new Insets(0, 0, 0, 0);
gbl.setConstraints(status, con);
getContentPane().add(status);
// Drag and drop for tabbedPane:
TransferHandler xfer = new EntryTableTransferHandler(null, this, null);
tabbedPane.setTransferHandler(xfer);
tlb.setTransferHandler(xfer);
mb.setTransferHandler(xfer);
sidePaneManager.getPanel().setTransferHandler(xfer);
}
/**
* Returns the indexed BasePanel.
*
* @param i Index of base
*/
public BasePanel getBasePanelAt(int i) {
return (BasePanel) tabbedPane.getComponentAt(i);
}
public void showBasePanelAt(int i) {
tabbedPane.setSelectedIndex(i);
}
public void showBasePanel(BasePanel bp) {
tabbedPane.setSelectedComponent(bp);
}
/**
* Returns the currently viewed BasePanel.
*/
public BasePanel getCurrentBasePanel() {
return (BasePanel) tabbedPane.getSelectedComponent();
}
/**
* @return the BasePanel count.
*/
public int getBasePanelCount() {
return tabbedPane.getComponentCount();
}
/**
* handle the color of active and inactive JTabbedPane tabs
*/
public void markActiveBasePanel() {
int now = tabbedPane.getSelectedIndex();
int len = tabbedPane.getTabCount();
if ((lastTabbedPanelSelectionIndex > -1) && (lastTabbedPanelSelectionIndex < len)) {
tabbedPane.setForegroundAt(lastTabbedPanelSelectionIndex, GUIGlobals.inActiveTabbed);
}
if ((now > -1) && (now < len)) {
tabbedPane.setForegroundAt(now, GUIGlobals.activeTabbed);
}
lastTabbedPanelSelectionIndex = now;
}
private int getTabIndex(JComponent comp) {
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
if (tabbedPane.getComponentAt(i) == comp) {
return i;
}
}
return -1;
}
public JTabbedPane getTabbedPane() {
return tabbedPane;
}
public void setTabTitle(JComponent comp, String title, String toolTip) {
int index = getTabIndex(comp);
tabbedPane.setTitleAt(index, title);
tabbedPane.setToolTipTextAt(index, toolTip);
}
class GeneralAction extends MnemonicAwareAction {
private final String command;
public GeneralAction(String command, String text) {
this.command = command;
putValue(Action.NAME, text);
}
public GeneralAction(String command, String text, String description) {
this.command = command;
putValue(Action.NAME, text);
putValue(Action.SHORT_DESCRIPTION, description);
}
public GeneralAction(String command, String text, Icon icon) {
super(icon);
this.command = command;
putValue(Action.NAME, text);
}
public GeneralAction(String command, String text, String description, Icon icon) {
super(icon);
this.command = command;
putValue(Action.NAME, text);
putValue(Action.SHORT_DESCRIPTION, description);
}
public GeneralAction(String command, String text, KeyStroke key) {
this.command = command;
putValue(Action.NAME, text);
putValue(Action.ACCELERATOR_KEY, key);
}
public GeneralAction(String command, String text, String description, KeyStroke key) {
this.command = command;
putValue(Action.NAME, text);
putValue(Action.SHORT_DESCRIPTION, description);
putValue(Action.ACCELERATOR_KEY, key);
}
public GeneralAction(String command, String text, String description, KeyStroke key, Icon icon) {
super(icon);
this.command = command;
putValue(Action.NAME, text);
putValue(Action.SHORT_DESCRIPTION, description);
putValue(Action.ACCELERATOR_KEY, key);
}
@Override
public void actionPerformed(ActionEvent e) {
if (tabbedPane.getTabCount() > 0) {
try {
((BasePanel) tabbedPane.getSelectedComponent()).runCommand(command);
} catch (Throwable ex) {
ex.printStackTrace();
}
} else {
LOGGER.info("Action '" + command + "' must be disabled when no database is open.");
}
}
}
private void fillMenu() {
//mb.putClientProperty(Options.HEADER_STYLE_KEY, HeaderStyle.BOTH);
mb.setBorder(null);
JMenu file = JabRefFrame.subMenu(Localization.menuTitle("File"));
JMenu sessions = JabRefFrame.subMenu(Localization.menuTitle("Sessions"));
JMenu edit = JabRefFrame.subMenu(Localization.menuTitle("Edit"));
JMenu search = JabRefFrame.subMenu(Localization.menuTitle("Search"));
JMenu groups = JabRefFrame.subMenu(Localization.menuTitle("Groups"));
JMenu bibtex = JabRefFrame.subMenu(Localization.menuTitle("BibTeX"));
JMenu view = JabRefFrame.subMenu(Localization.menuTitle("View"));
JMenu tools = JabRefFrame.subMenu(Localization.menuTitle("Tools"));
JMenu options = JabRefFrame.subMenu(Localization.menuTitle("Options"));
JMenu newSpec = JabRefFrame.subMenu(Localization.menuTitle("New entry..."));
JMenu helpMenu = JabRefFrame.subMenu(Localization.menuTitle("Help"));
file.add(newDatabaseAction);
file.add(open); //opendatabaseaction
file.add(mergeDatabaseAction);
file.add(save);
file.add(saveAs);
file.add(saveAll);
file.add(saveSelectedAs);
file.add(saveSelectedAsPlain);
file.addSeparator();
file.add(importNew);
file.add(importCurrent);
file.add(exportAll);
file.add(exportSelected);
file.addSeparator();
file.add(dbConnect);
file.add(dbImport);
file.add(dbExport);
file.addSeparator();
file.add(databaseProperties);
file.addSeparator();
file.add(fileHistory);
file.addSeparator();
file.add(editModeAction);
file.addSeparator();
file.add(closeDatabaseAction);
file.add(quit);
mb.add(file);
edit.add(undo);
edit.add(redo);
edit.addSeparator();
edit.add(cut);
edit.add(copy);
edit.add(paste);
edit.addSeparator();
edit.add(copyKey);
edit.add(copyCiteKey);
edit.add(copyKeyAndTitle);
edit.add(exportToClipboard);
edit.add(sendAsEmail);
edit.addSeparator();
edit.add(mark);
JMenu markSpecific = JabRefFrame.subMenu(Localization.menuTitle("Mark specific color"));
for (int i = 0; i < EntryMarker.MAX_MARKING_LEVEL; i++) {
markSpecific.add(new MarkEntriesAction(this, i).getMenuItem());
}
edit.add(markSpecific);
edit.add(unmark);
edit.add(unmarkAll);
edit.addSeparator();
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SPECIALFIELDSENABLED)) {
JMenu m;
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_RANKING)) {
m = new JMenu();
RightClickMenu.populateSpecialFieldMenu(m, Rank.getInstance(), this);
edit.add(m);
}
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_RELEVANCE)) {
edit.add(toggleRelevance);
}
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_QUALITY)) {
edit.add(toggleQualityAssured);
}
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRIORITY)) {
m = new JMenu();
RightClickMenu.populateSpecialFieldMenu(m, Priority.getInstance(), this);
edit.add(m);
}
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRINTED)) {
edit.add(togglePrinted);
}
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_READ)) {
m = new JMenu();
RightClickMenu.populateSpecialFieldMenu(m, ReadStatus.getInstance(), this);
edit.add(m);
}
edit.addSeparator();
}
edit.add(manageKeywords);
edit.addSeparator();
edit.add(selectAll);
mb.add(edit);
search.add(normalSearch);
search.add(replaceAll);
search.add(massSetField);
search.addSeparator();
search.add(dupliCheck);
search.add(resolveDuplicateKeys);
//search.add(strictDupliCheck);
search.addSeparator();
search.add(generalFetcher.getAction());
if (prefs.getBoolean(JabRefPreferences.WEB_SEARCH_VISIBLE)) {
sidePaneManager.register(generalFetcher.getTitle(), generalFetcher);
sidePaneManager.show(generalFetcher.getTitle());
}
mb.add(search);
groups.add(toggleGroups);
groups.addSeparator();
groups.add(addToGroup);
groups.add(removeFromGroup);
groups.add(moveToGroup);
groups.addSeparator();
groups.add(toggleHighlightAny);
groups.add(toggleHighlightAll);
mb.add(groups);
view.add(back);
view.add(forward);
view.add(focusTable);
view.add(nextTab);
view.add(prevTab);
view.add(sortTabs);
view.addSeparator();
view.add(increaseFontSize);
view.add(decreseFontSize);
view.addSeparator();
view.add(toggleToolbar);
view.add(generalFetcher.getAction());
view.add(toggleGroups);
view.add(togglePreview);
view.add(switchPreview);
mb.add(view);
bibtex.add(newEntryAction);
for(NewEntryAction a : newSpecificEntryAction) {
newSpec.add(a);
}
bibtex.add(newSpec);
bibtex.add(plainTextImport);
bibtex.addSeparator();
bibtex.add(editEntry);
bibtex.add(editPreamble);
bibtex.add(editStrings);
bibtex.addSeparator();
bibtex.add(deleteEntry);
mb.add(bibtex);
tools.add(makeKeyAction);
tools.add(cleanupEntries);
tools.add(mergeEntries);
tools.add(downloadFullText);
tools.add(newSubDatabaseAction);
tools.add(writeXmpAction);
OpenOfficePanel otp = OpenOfficePanel.getInstance();
otp.init(this, sidePaneManager);
tools.add(otp.getMenuItem());
tools.add(pushExternalButton.getMenuAction());
tools.addSeparator();
tools.add(manageSelectors);
tools.addSeparator();
tools.add(openFolder);
tools.add(openFile);
tools.add(openUrl);
//tools.add(openSpires);
tools.addSeparator();
tools.add(autoSetFile);
tools.add(findUnlinkedFiles);
tools.add(autoLinkFile);
tools.addSeparator();
tools.add(abbreviateIso);
tools.add(abbreviateMedline);
tools.add(unabbreviate);
tools.addSeparator();
tools.add(checkIntegrity);
mb.add(tools);
options.add(showPrefs);
AbstractAction customizeAction = new CustomizeEntryTypeAction();
AbstractAction genFieldsCustomization = new GenFieldsCustomizationAction();
options.add(customizeAction);
options.add(genFieldsCustomization);
options.add(customExpAction);
options.add(customImpAction);
options.add(customFileTypesAction);
options.add(manageJournals);
options.add(selectKeys);
mb.add(options);
helpMenu.add(help);
helpMenu.add(contents);
helpMenu.addSeparator();
helpMenu.add(errorConsole);
helpMenu.addSeparator();
helpMenu.add(forkMeOnGitHubAction);
helpMenu.add(donationAction);
helpMenu.addSeparator();
helpMenu.add(about);
mb.add(helpMenu);
createDisabledIconsForMenuEntries(mb);
}
public static JMenu subMenu(String name) {
int i = name.indexOf('&');
JMenu res;
if (i >= 0) {
res = new JMenu(name.substring(0, i) + name.substring(i + 1));
char mnemonic = Character.toUpperCase(name.charAt(i + 1));
res.setMnemonic((int) mnemonic);
} else {
res = new JMenu(name);
}
return res;
}
public void addParserResult(ParserResult pr, boolean raisePanel) {
if (pr.toOpenTab()) {
// Add the entries to the open tab.
BasePanel panel = getCurrentBasePanel();
if (panel == null) {
// There is no open tab to add to, so we create a new tab:
addTab(pr.getDatabase(), pr.getFile(), pr.getMetaData(), pr.getEncoding(), raisePanel);
} else {
List<BibEntry> entries = new ArrayList<>(pr.getDatabase().getEntries());
addImportedEntries(panel, entries, false);
}
} else {
addTab(pr.getDatabase(), pr.getFile(), pr.getMetaData(), pr.getEncoding(), raisePanel);
}
}
private void createToolBar() {
tlb.putClientProperty(Options.HEADER_STYLE_KEY, HeaderStyle.BOTH);
tlb.setBorder(null);
tlb.setRollover(true);
//tlb.setBorderPainted(true);
//tlb.setBackground(GUIGlobals.lightGray);
//tlb.setForeground(GUIGlobals.lightGray);
tlb.setFloatable(false);
tlb.addAction(newDatabaseAction);
tlb.addAction(open);
tlb.addAction(save);
tlb.addAction(saveAll);
//tlb.addAction(dbConnect);
//tlb.addAction(dbExport);
tlb.addSeparator();
tlb.addAction(cut);
tlb.addAction(copy);
tlb.addAction(paste);
tlb.addAction(undo);
tlb.addAction(redo);
tlb.addSeparator();
tlb.addAction(back);
tlb.addAction(forward);
tlb.addSeparator();
tlb.addAction(newEntryAction);
tlb.addAction(editEntry);
tlb.addAction(editStrings);
tlb.addAction(deleteEntry);
tlb.addSeparator();
tlb.addAction(makeKeyAction);
tlb.addAction(cleanupEntries);
tlb.addAction(mergeEntries);
tlb.addSeparator();
tlb.addAction(mark);
tlb.addAction(unmark);
tlb.addSeparator();
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SPECIALFIELDSENABLED)) {
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_RANKING)) {
tlb.add(net.sf.jabref.specialfields.SpecialFieldDropDown.generateSpecialFieldButtonWithDropDown(Rank.getInstance(), this));
}
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_RELEVANCE)) {
tlb.addAction(toggleRelevance);
}
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_QUALITY)) {
tlb.addAction(toggleQualityAssured);
}
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRIORITY)) {
tlb.add(net.sf.jabref.specialfields.SpecialFieldDropDown.generateSpecialFieldButtonWithDropDown(Priority.getInstance(), this));
}
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_PRINTED)) {
tlb.addAction(togglePrinted);
}
if (Globals.prefs.getBoolean(SpecialFieldsUtils.PREF_SHOWCOLUMN_READ)) {
tlb.add(net.sf.jabref.specialfields.SpecialFieldDropDown.generateSpecialFieldButtonWithDropDown(ReadStatus.getInstance(), this));
}
tlb.addSeparator();
}
fetcherToggle = new JToggleButton(generalFetcher.getAction());
tlb.addJToogleButton(fetcherToggle);
previewToggle = new JToggleButton(togglePreview);
tlb.addJToogleButton(previewToggle);
groupToggle = new JToggleButton(toggleGroups);
tlb.addJToogleButton(groupToggle);
tlb.addSeparator();
tlb.add(pushExternalButton.getComponent());
tlb.addSeparator();
tlb.add(donationAction);
}
public void output(final String s) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
statusLine.setText(s);
statusLine.repaint();
}
});
}
public void stopShowingSearchResults() {
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
getBasePanelAt(i).getFilterSearchToggle().stop();
}
}
private List<Object> openDatabaseOnlyActions = new LinkedList<>();
private List<Object> severalDatabasesOnlyActions = new LinkedList<>();
private void initActions() {
openDatabaseOnlyActions = new LinkedList<>();
openDatabaseOnlyActions.addAll(Arrays.asList(manageSelectors, mergeDatabaseAction, newSubDatabaseAction, save,
saveAs, saveSelectedAs, saveSelectedAsPlain, undo, redo, cut, deleteEntry, copy, paste, mark, unmark,
unmarkAll, editEntry, selectAll, copyKey, copyCiteKey, copyKeyAndTitle, editPreamble, editStrings,
toggleGroups, makeKeyAction, normalSearch, mergeEntries, cleanupEntries, exportToClipboard,
replaceAll, sendAsEmail, downloadFullText, writeXmpAction,
findUnlinkedFiles, addToGroup, removeFromGroup, moveToGroup, autoLinkFile, resolveDuplicateKeys,
openUrl, openFolder, openFile, togglePreview, dupliCheck, autoSetFile,
newEntryAction, plainTextImport, massSetField, manageKeywords, pushExternalButton.getMenuAction(),
closeDatabaseAction, switchPreview, checkIntegrity, toggleHighlightAny, toggleHighlightAll,
databaseProperties, abbreviateIso, abbreviateMedline, unabbreviate, exportAll, exportSelected,
importCurrent, saveAll, dbConnect, dbExport, focusTable));
openDatabaseOnlyActions.addAll(fetcherActions);
openDatabaseOnlyActions.addAll(newSpecificEntryAction);
severalDatabasesOnlyActions = new LinkedList<>();
severalDatabasesOnlyActions.addAll(Arrays
.asList(nextTab, prevTab, sortTabs));
tabbedPane.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent event) {
updateEnabledState();
}
});
}
/**
* Takes a list of Object and calls the method setEnabled on them, depending on whether it is an Action or a Component.
*
* @param list List that should contain Actions and Components.
* @param enabled
*/
private static void setEnabled(List<Object> list, boolean enabled) {
for (Object o : list) {
if (o instanceof Action) {
((Action) o).setEnabled(enabled);
}
if (o instanceof Component) {
((Component) o).setEnabled(enabled);
}
}
}
private int previousTabCount = -1;
/**
* Enable or Disable all actions based on the number of open tabs.
* <p>
* The action that are affected are set in initActions.
*/
public void updateEnabledState() {
int tabCount = tabbedPane.getTabCount();
if (tabCount != previousTabCount) {
previousTabCount = tabCount;
JabRefFrame.setEnabled(openDatabaseOnlyActions, tabCount > 0);
JabRefFrame.setEnabled(severalDatabasesOnlyActions, tabCount > 1);
}
if (tabCount == 0) {
back.setEnabled(false);
forward.setEnabled(false);
}
}
/**
* This method causes all open BasePanels to set up their tables
* anew. When called from PrefsDialog3, this updates to the new
* settings.
*/
public void setupAllTables() {
// This action can be invoked without an open database, so
// we have to check if we have one before trying to invoke
// methods to execute changes in the preferences.
// We want to notify all tabs about the changes to
// avoid problems when changing the column set.
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
BasePanel bf = getBasePanelAt(i);
// Update tables:
if (bf.getDatabase() != null) {
bf.setupMainPanel();
}
}
}
public BasePanel addTab(BibDatabase db, File file, MetaData metaData, Charset encoding, boolean raisePanel) {
// ensure that non-null parameters are really non-null
if (metaData == null) {
metaData = new MetaData();
}
if (encoding == null) {
encoding = Globals.prefs.getDefaultEncoding();
}
BasePanel bp = new BasePanel(JabRefFrame.this, db, file, metaData, encoding);
addTab(bp, file, raisePanel);
return bp;
}
private List<String> collectDatabaseFilePaths() {
List<String> dbPaths = new ArrayList<>(getBasePanelCount());
for (int i = 0; i < getBasePanelCount(); i++) {
try {
// db file exists
if(getBasePanelAt(i).getDatabaseFile() == null) {
dbPaths.add("");
} else {
dbPaths.add(getBasePanelAt(i).getDatabaseFile().getCanonicalPath());
}
} catch (IOException ex) {
LOGGER.error("Invalid database file path: " + ex.getMessage());
}
}
return dbPaths;
}
private List<String> getUniquePathParts() {
List<String> dbPaths = collectDatabaseFilePaths();
return FileUtil.uniquePathSubstrings(dbPaths);
}
public void updateAllTabTitles() {
List<String> paths = getUniquePathParts();
for (int i = 0; i < getBasePanelCount(); i++) {
String uniqPath = paths.get(i);
File file = getBasePanelAt(i).getDatabaseFile();
if ((file != null) && !uniqPath.equals(file.getName())) {
// remove filename
uniqPath = uniqPath.substring(0, uniqPath.lastIndexOf(File.separator));
tabbedPane.setTitleAt(i, getBasePanelAt(i).getTabTitle() + " \u2014 " + uniqPath);
} else if((file != null) && uniqPath.equals(file.getName())) {
// set original filename (again)
tabbedPane.setTitleAt(i, getBasePanelAt(i).getTabTitle());
}
}
}
public void addTab(BasePanel bp, File file, boolean raisePanel) {
// add tab
tabbedPane.add(bp.getTabTitle(), bp);
tabbedPane.setToolTipTextAt(tabbedPane.getTabCount() - 1, file == null ? null : file.getAbsolutePath());
// update all tab titles
updateAllTabTitles();
if (raisePanel) {
tabbedPane.setSelectedComponent(bp);
}
}
/**
* Creates icons for the disabled state for all JMenuItems with FontBasedIcons in the given menuElement.
* This is necessary as Swing is not able to generate default disabled icons for font based icons.
*
* @param menuElement the menuElement for which disabled icons should be generated
*/
public void createDisabledIconsForMenuEntries(MenuElement menuElement) {
for (MenuElement subElement : menuElement.getSubElements()) {
if ((subElement instanceof JMenu) || (subElement instanceof JPopupMenu)) {
createDisabledIconsForMenuEntries(subElement);
} else if (subElement instanceof JMenuItem) {
JMenuItem item = (JMenuItem) subElement;
if (item.getIcon() instanceof IconTheme.FontBasedIcon) {
item.setDisabledIcon(((IconTheme.FontBasedIcon) item.getIcon()).createDisabledIcon());
}
}
}
}
class SelectKeysAction extends AbstractAction {
public SelectKeysAction() {
super(Localization.lang("Customize key bindings"));
this.putValue(Action.SMALL_ICON, IconTheme.JabRefIcon.KEY_BINDINGS.getSmallIcon());
}
@Override
public void actionPerformed(ActionEvent e) {
KeyBindingsDialog d = new KeyBindingsDialog(new KeyBindingRepository(Globals.getKeyPrefs().getKeyBindings()));
d.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
d.pack(); //setSize(300,500);
PositionWindow.placeDialog(d, JabRefFrame.this);
d.setVisible(true);
}
}
/**
* The action concerned with closing the window.
*/
class CloseAction extends MnemonicAwareAction {
public CloseAction() {
putValue(Action.NAME, Localization.menuTitle("Quit"));
putValue(Action.SHORT_DESCRIPTION, Localization.lang("Quit JabRef"));
putValue(Action.ACCELERATOR_KEY, Globals.getKeyPrefs().getKey(KeyBinding.QUIT_JABREF));
}
@Override
public void actionPerformed(ActionEvent e) {
quit();
}
}
// The action for closing the current database and leaving the window open.
private final CloseDatabaseAction closeDatabaseAction = new CloseDatabaseAction();
private final CloseAllDatabasesAction closeAllDatabasesAction = new CloseAllDatabasesAction();
private final CloseOtherDatabasesAction closeOtherDatabasesAction = new CloseOtherDatabasesAction();
// The action for opening the preferences dialog.
private final AbstractAction showPrefs = new ShowPrefsAction();
class ShowPrefsAction extends MnemonicAwareAction {
public ShowPrefsAction() {
super(IconTheme.JabRefIcon.PREFERENCES.getIcon());
putValue(Action.NAME, Localization.menuTitle("Preferences"));
putValue(Action.SHORT_DESCRIPTION, Localization.lang("Preferences"));
}
@Override
public void actionPerformed(ActionEvent e) {
preferences();
}
}
/**
* This method does the job of adding imported entries into the active
* database, or into a new one. It shows the ImportInspectionDialog if
* preferences indicate it should be used. Otherwise it imports directly.
*
* @param panel The BasePanel to add to.
* @param entries The entries to add.
* @param openInNew Should the entries be imported into a new database?
*/
private void addImportedEntries(final BasePanel panel, final List<BibEntry> entries, final boolean openInNew) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
ImportInspectionDialog diag = new ImportInspectionDialog(JabRefFrame.this,
panel, BibtexFields.DEFAULT_INSPECTION_FIELDS, Localization.lang("Import"),
openInNew);
diag.addEntries(entries);
diag.entryListComplete();
PositionWindow.placeDialog(diag, JabRefFrame.this);
diag.setVisible(true);
diag.toFront();
}
});
}
public FileHistoryMenu getFileHistory() {
return fileHistory;
}
/**
* Set the preview active state for all BasePanel instances.
*
* @param enabled
*/
public void setPreviewActive(boolean enabled) {
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
getBasePanelAt(i).setPreviewActive(enabled);
}
}
public void removeCachedEntryEditors() {
for (int j = 0; j < tabbedPane.getTabCount(); j++) {
BasePanel bp = (BasePanel) tabbedPane.getComponentAt(j);
bp.entryEditors.clear();
}
}
/**
* This method shows a wait cursor and blocks all input to the JFrame's contents.
*/
public void block() {
getGlassPane().setVisible(true);
}
/**
* This method reverts the cursor to normal, and stops blocking input to the JFrame's contents.
* There are no adverse effects of calling this method redundantly.
*/
public void unblock() {
getGlassPane().setVisible(false);
}
/**
* Set the visibility of the progress bar in the right end of the
* status line at the bottom of the frame.
* <p>
* If not called on the event dispatch thread, this method uses
* SwingUtilities.invokeLater() to do the actual operation on the EDT.
*/
public void setProgressBarVisible(final boolean visible) {
if (SwingUtilities.isEventDispatchThread()) {
progressBar.setVisible(visible);
} else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
progressBar.setVisible(visible);
}
});
}
}
/**
* Sets the current value of the progress bar.
* <p>
* If not called on the event dispatch thread, this method uses
* SwingUtilities.invokeLater() to do the actual operation on the EDT.
*/
public void setProgressBarValue(final int value) {
if (SwingUtilities.isEventDispatchThread()) {
progressBar.setValue(value);
} else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
progressBar.setValue(value);
}
});
}
}
/**
* Sets the indeterminate status of the progress bar.
* <p>
* If not called on the event dispatch thread, this method uses
* SwingUtilities.invokeLater() to do the actual operation on the EDT.
*/
public void setProgressBarIndeterminate(final boolean value) {
if (SwingUtilities.isEventDispatchThread()) {
progressBar.setIndeterminate(value);
} else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
progressBar.setIndeterminate(value);
}
});
}
}
/**
* Sets the maximum value of the progress bar. Always call this method
* before using the progress bar, to set a maximum value appropriate to
* the task at hand.
* <p>
* If not called on the event dispatch thread, this method uses
* SwingUtilities.invokeLater() to do the actual operation on the EDT.
*/
public void setProgressBarMaximum(final int value) {
if (SwingUtilities.isEventDispatchThread()) {
progressBar.setMaximum(value);
} else {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
progressBar.setMaximum(value);
}
});
}
}
class SaveSessionAction
extends MnemonicAwareAction {
public SaveSessionAction() {
super();
putValue(Action.NAME, Localization.menuTitle("Save session"));
putValue(Action.ACCELERATOR_KEY, Globals.getKeyPrefs().getKey(KeyBinding.SAVE_SESSION));
}
@Override
public void actionPerformed(ActionEvent e) {
// Here we store the names of all current files. If
// there is no current file, we remove any
// previously stored filename.
List<String> filenames = new ArrayList<>();
if (tabbedPane.getTabCount() > 0) {
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
if (tabbedPane.getTitleAt(i).equals(GUIGlobals.untitledTitle)) {
tabbedPane.setSelectedIndex(i);
int answer = JOptionPane.showConfirmDialog
(JabRefFrame.this, Localization.lang
("This untitled database must be saved first to be "
+ "included in the saved session. Save now?"),
Localization.lang("Save database"),
JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION) {
// The user wants to save.
try {
getCurrentBasePanel().runCommand(Actions.SAVE);
} catch (Throwable ignored) {
// Ignored
}
}
}
if (getBasePanelAt(i).getDatabaseFile() != null) {
filenames.add(getBasePanelAt(i).getDatabaseFile().getPath());
}
}
}
if (filenames.isEmpty()) {
output(Localization.lang("Not saved (empty session)") + '.');
} else {
prefs.putStringList(JabRefPreferences.SAVED_SESSION, filenames);
output(Localization.lang("Saved session") + '.');
}
}
}
public class LoadSessionAction extends MnemonicAwareAction {
private volatile boolean running;
public LoadSessionAction() {
super();
putValue(Action.NAME, Localization.menuTitle("Load session"));
putValue(Action.ACCELERATOR_KEY, Globals.getKeyPrefs().getKey(KeyBinding.LOAD_SESSION));
}
@Override
public void actionPerformed(ActionEvent e) {
if (prefs.get(JabRefPreferences.SAVED_SESSION) == null) {
output(Localization.lang("No saved session found."));
return;
}
if (running) {
return;
} else {
running = true;
}
output(Localization.lang("Loading session..."));
JabRefExecutorService.INSTANCE.execute(new Runnable() {
@Override
public void run() {
HashSet<String> currentFiles = new HashSet<>();
if (tabbedPane.getTabCount() > 0) {
for (int i = 0; i < tabbedPane.getTabCount(); i++) {
if (getBasePanelAt(i).getDatabaseFile() != null) {
currentFiles.add(getBasePanelAt(i).getDatabaseFile().getPath());
}
}
}
List<String> names = prefs.getStringList(JabRefPreferences.SAVED_SESSION);
ArrayList<File> filesToOpen = new ArrayList<>();
for (String name : names) {
filesToOpen.add(new File(name));
}
open.openFiles(filesToOpen, true);
running = false;
}
});
}
}
class ChangeTabAction extends MnemonicAwareAction {
private final boolean next;
public ChangeTabAction(boolean next) {
putValue(Action.NAME, next ? Localization.menuTitle("Next tab") :
Localization.menuTitle("Previous tab"));
this.next = next;
putValue(Action.ACCELERATOR_KEY,
next ? Globals.getKeyPrefs().getKey(KeyBinding.NEXT_TAB) : Globals.getKeyPrefs().getKey(KeyBinding.PREVIOUS_TAB));
}
@Override
public void actionPerformed(ActionEvent e) {
int i = tabbedPane.getSelectedIndex();
int newI = next ? i + 1 : i - 1;
if (newI < 0) {
newI = tabbedPane.getTabCount() - 1;
}
if (newI == tabbedPane.getTabCount()) {
newI = 0;
}
tabbedPane.setSelectedIndex(newI);
}
}
/**
* Class for handling general actions; cut, copy and paste. The focused component is
* kept track of by Globals.focusListener, and we call the action stored under the
* relevant name in its action map.
*/
class EditAction extends MnemonicAwareAction {
private final String command;
public EditAction(String command, String menuTitle, String description, KeyStroke key, Icon icon) {
super(icon);
this.command = command;
putValue(Action.NAME, menuTitle);
putValue(Action.ACCELERATOR_KEY, key);
putValue(Action.SHORT_DESCRIPTION, description);
}
@Override public void actionPerformed(ActionEvent e) {
LOGGER.debug(Globals.focusListener.getFocused().toString());
JComponent source = Globals.focusListener.getFocused();
try {
source.getActionMap().get(command).actionPerformed(new ActionEvent(source, 0, command));
} catch (NullPointerException ex) {
// No component is focused, so we do nothing.
}
}
}
class CustomizeExportsAction extends MnemonicAwareAction {
public CustomizeExportsAction() {
putValue(Action.NAME, Localization.menuTitle("Manage custom exports"));
}
@Override
public void actionPerformed(ActionEvent e) {
ExportCustomizationDialog ecd = new ExportCustomizationDialog(JabRefFrame.this);
ecd.setVisible(true);
}
}
class CustomizeImportsAction extends MnemonicAwareAction {
public CustomizeImportsAction() {
putValue(Action.NAME, Localization.menuTitle("Manage custom imports"));
}
@Override
public void actionPerformed(ActionEvent e) {
ImportCustomizationDialog ecd = new ImportCustomizationDialog(JabRefFrame.this);
ecd.setVisible(true);
}
}
class CustomizeEntryTypeAction extends MnemonicAwareAction {
public CustomizeEntryTypeAction() {
putValue(Action.NAME, Localization.menuTitle("Customize entry types"));
}
@Override
public void actionPerformed(ActionEvent e) {
JDialog dl = new EntryCustomizationDialog2(JabRefFrame.this);
PositionWindow.placeDialog(dl, JabRefFrame.this);
dl.setVisible(true);
}
}
class GenFieldsCustomizationAction extends MnemonicAwareAction {
public GenFieldsCustomizationAction() {
putValue(Action.NAME, Localization.menuTitle("Set up general fields"));
}
@Override
public void actionPerformed(ActionEvent e) {
GenFieldsCustomizer gf = new GenFieldsCustomizer(JabRefFrame.this);
PositionWindow.placeDialog(gf, JabRefFrame.this);
gf.setVisible(true);
}
}
class DatabasePropertiesAction extends MnemonicAwareAction {
private DatabasePropertiesDialog propertiesDialog;
public DatabasePropertiesAction() {
putValue(Action.NAME, Localization.menuTitle("Database properties"));
}
@Override
public void actionPerformed(ActionEvent e) {
if (propertiesDialog == null) {
propertiesDialog = new DatabasePropertiesDialog(JabRefFrame.this);
}
propertiesDialog.setPanel(getCurrentBasePanel());
PositionWindow.placeDialog(propertiesDialog, JabRefFrame.this);
propertiesDialog.setVisible(true);
}
}
class BibtexKeyPatternAction extends MnemonicAwareAction {
private BibtexKeyPatternDialog bibtexKeyPatternDialog;
public BibtexKeyPatternAction() {
putValue(Action.NAME, Localization.lang("Bibtex key patterns"));
}
@Override
public void actionPerformed(ActionEvent e) {
JabRefPreferences.getInstance();
if (bibtexKeyPatternDialog == null) {
// if no instance of BibtexKeyPatternDialog exists, create new one
bibtexKeyPatternDialog = new BibtexKeyPatternDialog(JabRefFrame.this, getCurrentBasePanel());
} else {
// BibtexKeyPatternDialog allows for updating content based on currently selected panel
bibtexKeyPatternDialog.setPanel(getCurrentBasePanel());
}
PositionWindow.placeDialog(bibtexKeyPatternDialog, JabRefFrame.this);
bibtexKeyPatternDialog.setVisible(true);
}
}
class IncreaseTableFontSizeAction extends MnemonicAwareAction {
public IncreaseTableFontSizeAction() {
putValue(Action.NAME, Localization.menuTitle("Increase table font size"));
putValue(Action.ACCELERATOR_KEY, Globals.getKeyPrefs().getKey(KeyBinding.INCREASE_TABLE_FONT_SIZE));
}
@Override
public void actionPerformed(ActionEvent event) {
int currentSize = GUIGlobals.CURRENTFONT.getSize();
GUIGlobals.CURRENTFONT = new Font(GUIGlobals.CURRENTFONT.getFamily(), GUIGlobals.CURRENTFONT.getStyle(),
currentSize + 1);
Globals.prefs.putInt(JabRefPreferences.FONT_SIZE, currentSize + 1);
for (int i = 0; i < getBasePanelCount(); i++) {
getBasePanelAt(i).updateTableFont();
}
}
}
class DecreaseTableFontSizeAction extends MnemonicAwareAction {
public DecreaseTableFontSizeAction() {
putValue(Action.NAME, Localization.menuTitle("Decrease table font size"));
putValue(Action.ACCELERATOR_KEY, Globals.getKeyPrefs().getKey(KeyBinding.DECREASE_TABLE_FONT_SIZE));
}
@Override
public void actionPerformed(ActionEvent event) {
int currentSize = GUIGlobals.CURRENTFONT.getSize();
if (currentSize < 2) {
return;
}
GUIGlobals.CURRENTFONT = new Font(GUIGlobals.CURRENTFONT.getFamily(), GUIGlobals.CURRENTFONT.getStyle(),
currentSize - 1);
Globals.prefs.putInt(JabRefPreferences.FONT_SIZE, currentSize - 1);
for (int i = 0; i < getBasePanelCount(); i++) {
getBasePanelAt(i).updateTableFont();
}
}
}
private static class MyGlassPane extends JPanel {
//ForegroundLabel infoLabel = new ForegroundLabel("Showing search");
public MyGlassPane() {
addKeyListener(new KeyAdapter() {
// Nothing
});
addMouseListener(new MouseAdapter() {
// Nothing
});
/* infoLabel.setForeground(new Color(255, 100, 100, 124));
setLayout(new BorderLayout());
add(infoLabel, BorderLayout.CENTER);*/
super.setCursor(
Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
// Override isOpaque() to prevent the glasspane from hiding the window contents:
@Override
public boolean isOpaque() {
return false;
}
}
@Override
public void showMessage(Object message, String title, int msgType) {
JOptionPane.showMessageDialog(this, message, title, msgType);
}
@Override
public void setStatus(String s) {
output(s);
}
@Override
public void showMessage(String message) {
JOptionPane.showMessageDialog(this, message);
}
public int showSaveDialog(String filename) {
Object[] options = {Localization.lang("Save changes"),
Localization.lang("Discard changes"),
Localization.lang("Return to JabRef")};
return JOptionPane.showOptionDialog(JabRefFrame.this,
Localization.lang("Database '%0' has changed.", filename),
Localization.lang("Save before closing"), JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE, null, options, options[2]);
}
private void closeTab(BasePanel panel) {
// empty tab without database
if (panel == null) {
return;
}
if (panel.isModified()) {
if(confirmClose(panel)) {
removeTab(panel);
}
} else {
removeTab(panel);
}
}
// Ask if the user really wants to close, if the base has not been saved
private boolean confirmClose(BasePanel panel) {
boolean close = false;
String filename;
if (panel.getDatabaseFile() == null) {
filename = GUIGlobals.untitledTitle;
} else {
filename = panel.getDatabaseFile().getAbsolutePath();
}
int answer = showSaveDialog(filename);
if (answer == JOptionPane.YES_OPTION) {
// The user wants to save.
try {
SaveDatabaseAction saveAction = new SaveDatabaseAction(panel);
saveAction.runCommand();
if (saveAction.isSuccess()) {
close = true;
}
} catch (Throwable ex) {
// do not close
}
} else if(answer == JOptionPane.NO_OPTION) {
// discard changes
close = true;
}
return close;
}
private void removeTab(BasePanel panel) {
panel.cleanUp();
AutoSaveManager.deleteAutoSaveFile(panel);
tabbedPane.remove(panel);
if (tabbedPane.getTabCount() > 0) {
markActiveBasePanel();
}
setWindowTitle();
updateEnabledState();
output(Localization.lang("Closed database") + '.');
// update tab titles
updateAllTabTitles();
}
public class CloseDatabaseAction extends MnemonicAwareAction {
public CloseDatabaseAction() {
super(IconTheme.JabRefIcon.CLOSE.getSmallIcon());
putValue(Action.NAME, Localization.menuTitle("Close database"));
putValue(Action.SHORT_DESCRIPTION, Localization.lang("Close the current database"));
putValue(Action.ACCELERATOR_KEY, Globals.getKeyPrefs().getKey(KeyBinding.CLOSE_DATABASE));
}
@Override
public void actionPerformed(ActionEvent e) {
closeTab(getCurrentBasePanel());
}
}
public class CloseAllDatabasesAction extends MnemonicAwareAction {
@Override
public void actionPerformed(ActionEvent e) {
final Component[] panels = tabbedPane.getComponents();
for(Component p : panels) {
closeTab((BasePanel) p);
}
}
}
public class CloseOtherDatabasesAction extends MnemonicAwareAction {
@Override
public void actionPerformed(ActionEvent e) {
final BasePanel active = getCurrentBasePanel();
final Component[] panels = tabbedPane.getComponents();
for(Component p : panels) {
if(p != active) {
closeTab((BasePanel) p);
}
}
}
}
} |
package no.cantara;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import java.util.Timer;
import java.util.TimerTask;
public class PerformanceSampler {
private class PerformanceSamplerTimerTask extends TimerTask {
@Override
public void run() {
getPrintableTimewindowLatencyStatistics().printToStandardOutput();
getPrintableTimewindowThroughputStatistics().printToStandardOutput();
resetTimeWindow();
}
}
protected final Object initializationLock = new Object();
protected Timer timer;
protected final Object cumulativeStatisticsLock = new Object();
protected final DescriptiveStatistics latencyStatistics = new DescriptiveStatistics();
protected long minSentTimeNanos = Long.MAX_VALUE;
protected final DescriptiveStatistics throughputStatistics = new DescriptiveStatistics();
protected final Object timewindowLock = new Object();
protected long timewindowStartNanos = -1;
protected DescriptiveStatistics timewindowLatencyStatistics = new DescriptiveStatistics();
protected long timewindowMinSentTimeNanos = Long.MAX_VALUE;
protected DescriptiveStatistics timewindowThroughputStatistics = new DescriptiveStatistics();
public PerformanceSampler() {
}
private void resetTimeWindow() {
synchronized (timewindowLock) {
minSentTimeNanos = Long.MAX_VALUE;
timewindowLatencyStatistics = new DescriptiveStatistics();
timewindowMinSentTimeNanos = Long.MAX_VALUE;
timewindowThroughputStatistics = new DescriptiveStatistics();
timewindowStartNanos = System.nanoTime();
}
}
public PrintableStatistics getPrintableLatencyStatistics() {
synchronized (cumulativeStatisticsLock) {
return new PrintableStatistics("\"Cumulative statistics for Latency", latencyStatistics.copy());
}
}
public PrintableStatistics getPrintableThroughputStatistics() {
synchronized (cumulativeStatisticsLock) {
return new PrintableStatistics("\"Cumulative statistics for Throughput", throughputStatistics.copy());
}
}
public PrintableStatistics getPrintableTimewindowLatencyStatistics() {
synchronized (timewindowLock) {
return new PrintableStatistics("\"Time-window statistics for Latency\nwindow-size: " + timewindowStartNanos, timewindowLatencyStatistics.copy());
}
}
public PrintableStatistics getPrintableTimewindowThroughputStatistics() {
synchronized (timewindowLock) {
return new PrintableStatistics("\"Time-window statistics for Throughput", timewindowThroughputStatistics.copy());
}
}
public void addMessage(long sentTimeNanos, long receivedTimeNanos) {
synchronized (initializationLock) {
if (timer == null) {
timer = new Timer(true);
timer.scheduleAtFixedRate(new PerformanceSamplerTimerTask(), 1000, 1000);
resetTimeWindow();
}
}
synchronized (cumulativeStatisticsLock) {
addLatency(sentTimeNanos, receivedTimeNanos);
addThroughput(sentTimeNanos, receivedTimeNanos);
}
synchronized (timewindowLock) {
addTimewindowLatency(receivedTimeNanos);
addTimewindowThroughput(sentTimeNanos, receivedTimeNanos);
}
}
private void addLatency(long sentTimeNanos, long receivedTimeNanos) {
long durationNanos = receivedTimeNanos - sentTimeNanos;
double latencyMicro = durationNanos / 1000.0;
latencyStatistics.addValue(latencyMicro);
}
private void addThroughput(long sentTimeNanos, long receivedTimeNanos) {
if (sentTimeNanos < minSentTimeNanos) {
minSentTimeNanos = sentTimeNanos;
}
double throughput = (receivedTimeNanos - minSentTimeNanos) / (double) throughputStatistics.getN();
throughputStatistics.addValue(throughput);
}
private void addTimewindowLatency(long receivedTimeNanos) {
long timewindowDurationNanos = receivedTimeNanos - timewindowMinSentTimeNanos;
double timewindowLatencyMicro = timewindowDurationNanos / 1000.0;
timewindowLatencyStatistics.addValue(timewindowLatencyMicro);
}
private void addTimewindowThroughput(long sentTimeNanos, long receivedTimeNanos) {
if (sentTimeNanos < timewindowMinSentTimeNanos) {
timewindowMinSentTimeNanos = sentTimeNanos;
}
double timewindowThroughput = (receivedTimeNanos - timewindowMinSentTimeNanos) / (double) timewindowThroughputStatistics.getN();;
timewindowThroughputStatistics.addValue(timewindowThroughput);
}
} |
package org.analogweb;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
/**
* @author snowgoose
*/
public interface ResponseContext {
/**
*
* HTTP
* @param context {@link RequestContext}
*/
void commmit(RequestContext context);
/**
* HTTP{@link Headers}
* @return {@link Headers}
*/
Headers getResponseHeaders();
/**
* {@link ResponseWriter}
* @return {@link ResponseWriter}
*/
ResponseWriter getResponseWriter();
/**
* HTTP
* @param status HTTP
*/
void setStatus(int status);
/**
* HTTP
*
*
* @param length HTTP
*/
void setContentLength(long length);
/**
*
* @author snowgoose
*/
public static interface ResponseWriter {
/**
*
* {@link InputStream}
* @param entity {@link InputStream}
*/
void writeEntity(InputStream entity);
/**
*
* {@link String}<br/>
* {@link Charset#defaultCharset()}
*
* @param entity {@link String}
*/
void writeEntity(String entity);
/**
*
* {@link String}<br/>
* @param entity {@link String}
* @param charset {@link Charset}
*/
void writeEntity(String entity, Charset charset);
/**
*
* {@link ResponseEntity}
* @param entity {@link ResponseEntity}
*/
void writeEntity(ResponseEntity entity);
}
/**
*
*
*
* @author snowgoose
*/
public static interface ResponseEntity {
/**
*
* @param responseBody {@link OutputStream}
*/
void writeInto(OutputStream responseBody);
}
} |
package org.basex.query.gflwor;
import java.util.*;
import org.basex.query.*;
import org.basex.query.expr.*;
import org.basex.query.func.*;
import org.basex.query.value.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.query.value.seq.*;
import org.basex.query.value.type.*;
import org.basex.query.iter.Iter;
import org.basex.query.path.*;
import org.basex.query.util.*;
import org.basex.query.var.*;
import org.basex.util.*;
import org.basex.util.hash.*;
import org.basex.util.list.*;
public final class GFLWOR extends ParseExpr {
/** Return expression. */
Expr ret;
/** FLWOR clauses. */
private final LinkedList<Clause> clauses;
/** XQuery 3.0 flag. */
private boolean xq30;
/**
* Constructor.
* @param ii input info
* @param cls FLWOR clauses
* @param rt return expression
*/
public GFLWOR(final InputInfo ii, final LinkedList<Clause> cls, final Expr rt) {
super(ii);
clauses = cls;
ret = rt;
}
@Override
public Iter iter(final QueryContext ctx) throws QueryException {
// Start evaluator, doing nothing, once.
Eval e = new Eval() {
/** First-evaluation flag. */
private boolean first = true;
@Override
public boolean next(final QueryContext c) {
if(!first) return false;
first = false;
return true;
}
};
for(final Clause cls : clauses) e = cls.eval(e);
final Eval ev = e;
return new Iter() {
/** Return iterator. */
private Iter sub = Empty.ITER;
/** If the iterator has been emptied. */
private boolean drained;
@Override
public Item next() throws QueryException {
if(drained) return null;
while(true) {
final Item it = sub.next();
if(it != null) return it;
if(!ev.next(ctx)) {
drained = true;
return null;
}
sub = ret.iter(ctx);
}
}
};
}
@Override
public Expr compile(final QueryContext ctx, final VarScope scp) throws QueryException {
int i = 0;
InputInfo ii = info;
try {
for(final Clause c : clauses) {
ii = c.info;
c.compile(ctx, scp);
// the first round of constant propagation is free
if(c instanceof Let) ((Let) c).bindConst(ctx);
i++;
}
ii = info;
ret = ret.compile(ctx, scp);
} catch(final QueryException qe) {
clauseError(qe, i, ii);
}
return optimize(ctx, scp);
}
@Override
public Expr optimize(final QueryContext ctx, final VarScope scp) throws QueryException {
// split combined where clauses
final ListIterator<Clause> iter = clauses.listIterator();
while(iter.hasNext()) {
final Clause c = iter.next();
if(c instanceof Where) {
final Where wh = (Where) c;
if(wh.pred instanceof And) {
iter.remove();
for(final Expr e : ((And) wh.pred).expr) iter.add(new Where(e, wh.info));
}
}
}
// the other optimizations are applied until nothing changes any more
boolean changed;
do {
// rewrite singleton for clauses to let
changed = forToLet(ctx);
// inline let expressions if they are used only once (and not in a loop)
changed |= inlineLets(ctx, scp);
// clean unused variables from group-by and order-by expression
changed |= cleanDeadVars(ctx);
// include the clauses of nested FLWR expressions into this one
changed |= unnestFLWR(ctx, scp);
// slide let clauses out to avoid repeated evaluation
changed |= slideLetsOut(ctx);
// float where expressions upwards to filter earlier
changed |= optimizeWhere(ctx, scp);
// remove FLWOR expressions when all clauses were removed
if(clauses.isEmpty()) {
ctx.compInfo(QueryText.OPTFLWOR, this);
return ret;
}
if(clauses.getLast() instanceof For && ret instanceof VarRef) {
final For last = (For) clauses.getLast();
// for $x in E return $x ==> return E
if(!last.var.checksType() && last.var.is(((VarRef) ret).var)) {
clauses.removeLast();
ret = last.expr;
changed = true;
}
}
if(!clauses.isEmpty() && clauses.getFirst() instanceof For) {
final For fst = (For) clauses.getFirst();
if(!fst.empty && fst.expr instanceof GFLWOR) {
ctx.compInfo(QueryText.OPTFLAT, fst);
final GFLWOR sub = (GFLWOR) fst.expr;
clauses.set(0, new For(fst.var, null, fst.score, sub.ret, false, fst.info));
if(fst.pos != null) clauses.add(1, new Count(fst.pos, fst.info));
clauses.addAll(0, sub.clauses);
changed = true;
}
}
if(!clauses.isEmpty() && ret instanceof GFLWOR) {
final GFLWOR sub = (GFLWOR) ret;
if(sub.isFLWR()) {
// flatten nested FLWOR expressions
ctx.compInfo(QueryText.OPTFLAT, this);
clauses.addAll(sub.clauses);
ret = sub.ret;
changed = true;
} else if(sub.clauses.getFirst() instanceof Let) {
ctx.compInfo(QueryText.OPTFLAT, this);
final LinkedList<Clause> cls = sub.clauses;
// propagate all leading let bindings into outer clauses
do clauses.add(cls.removeFirst());
while(!cls.isEmpty() && cls.getFirst() instanceof Let);
ret = ret.optimize(ctx, scp);
changed = true;
}
}
/*
* [LW] not safe:
* for $x in 1 to 4 return
* for $y in 1 to 4 count $index return $index
* */
} while(changed);
mergeWheres();
size = calcSize();
if(size == 0 && !(uses(Use.NDT) || uses(Use.UPD))) {
ctx.compInfo(QueryText.OPTWRITE, this);
return Empty.SEQ;
}
type = SeqType.get(ret.type().type, size);
if(clauses.getFirst() instanceof Where) {
final Where wh = (Where) clauses.removeFirst();
return new If(info, wh.pred, clauses.isEmpty() ? ret : this, Empty.SEQ);
}
return this;
}
/**
* Pre-calculates the number of results of this FLWOR expression.
* @return result size if statically computable, {@code -1} otherwise
*/
private long calcSize() {
final long output = ret.size();
if(output == 0) return 0;
long tuples = 1;
for(final Clause c : clauses) if((tuples = c.calcSize(tuples)) <= 0) break;
return tuples == 0 ? 0 : output < 0 || tuples < 0 ? -1 : tuples * output;
}
/**
* Tries to convert for clauses that iterate ver a single item into let bindings.
* @param ctx query context
* @return change flag
*/
private boolean forToLet(final QueryContext ctx) {
boolean change = false;
for(int i = clauses.size(); --i >= 0;) {
final Clause c = clauses.get(i);
if(c instanceof For && ((For) c).asLet(clauses, i)) {
ctx.compInfo(QueryText.OPTFORTOLET);
change = true;
}
}
return change;
}
/**
* Inline let expressions if they are used only once (and not in a loop).
* @param ctx query context
* @param scp variable scope
* @return change flag
* @throws QueryException query exception
*/
private boolean inlineLets(final QueryContext ctx, final VarScope scp)
throws QueryException {
boolean change = false, thisRound;
do {
thisRound = false;
final ListIterator<Clause> iter = clauses.listIterator();
while(iter.hasNext()) {
final Clause c = iter.next();
final int next = iter.nextIndex();
if(c instanceof Let) {
final Let lt = (Let) c;
if(lt.expr.uses(Use.NDT)) continue;
final VarUsage uses = count(lt.var, next);
if(uses == VarUsage.NEVER) {
ctx.compInfo(QueryText.OPTVAR, lt.var);
iter.remove();
change = true;
} else if(lt.expr.isValue() || lt.expr instanceof VarRef && !lt.var.checksType()
|| uses == VarUsage.ONCE && !lt.expr.uses(Use.CTX)
|| lt.expr instanceof AxisPath && ((AxisPath) lt.expr).cheap()) {
ctx.compInfo(QueryText.OPTINLINE, lt);
inline(ctx, scp, lt.var, lt.inlineExpr(ctx, scp), next);
thisRound = change = true;
// continue from the beginning as clauses below could have been deleted
break;
}
}
}
} while(thisRound);
return change;
}
/**
* Flattens FLWR expressions in for or let clauses by including their clauses in this
* expression.
*
* @param ctx query context
* @param scp variable scope
* @return change flag
* @throws QueryException query exception
*/
private boolean unnestFLWR(final QueryContext ctx, final VarScope scp)
throws QueryException {
boolean change = false, thisRound;
do {
thisRound = false;
final ListIterator<Clause> iter = clauses.listIterator();
while(iter.hasNext()) {
final Clause cl = iter.next();
final boolean isFor = cl instanceof For;
if(isFor) {
final For fr = (For) cl;
if(!fr.empty && fr.pos == null && fr.expr instanceof GFLWOR) {
final GFLWOR fl = (GFLWOR) fr.expr;
if(fl.isFLWR()) {
ctx.compInfo(QueryText.OPTFLAT, this);
iter.remove();
for(final Clause c : fl.clauses) iter.add(c);
fr.expr = fl.ret;
iter.add(fr);
thisRound = change = true;
}
}
}
if(!thisRound && (isFor || cl instanceof Let)) {
final Expr e = isFor ? ((For) cl).expr : ((Let) cl).expr;
if(e instanceof GFLWOR) {
final GFLWOR fl = (GFLWOR) e;
final LinkedList<Clause> cls = fl.clauses;
if(cls.getFirst() instanceof Let) {
// remove the binding from the outer clauses
iter.remove();
// propagate all leading let bindings into outer clauses
do iter.add(cls.removeFirst());
while(!cls.isEmpty() && cls.getFirst() instanceof Let);
// re-add the binding with new, reduced expression at the end
final Expr rest = fl.clauses.isEmpty() ? fl.ret : fl.optimize(ctx, scp);
if(isFor) ((For) cl).expr = rest;
else ((Let) cl).expr = rest;
iter.add(cl);
thisRound = change = true;
}
}
}
}
} while(thisRound);
return change;
}
/**
* Cleans dead entries from the tuples that {@link GroupBy} and {@link OrderBy} handle.
* @param ctx query context
* @return change flag
*/
private boolean cleanDeadVars(final QueryContext ctx) {
final IntMap<Var> decl = new IntMap<Var>();
final BitArray used = new BitArray();
for(final Clause cl : clauses) for(final Var v : cl.vars()) decl.add(v.id, v);
final ASTVisitor marker = new ASTVisitor() {
@Override
public boolean used(final VarRef ref) {
final int id = ref.var.id;
if(decl.get(id) != null) used.set(id);
return true;
}
};
ret.accept(marker);
boolean change = false;
for(int i = clauses.size(); --i >= 0;) {
final Clause curr = clauses.get(i);
change |= curr.clean(ctx, decl, used);
curr.accept(marker);
for(final Var v : curr.vars()) used.clear(v.id);
}
return change;
}
/**
* Optimization pass which tries to slide let expressions out of loops. Care is taken
* that no unnecessary relocations are done.
* @param ctx query context
* @return {@code true} if there were relocations, {@code false} otherwise
*/
private boolean slideLetsOut(final QueryContext ctx) {
boolean change = false;
for(int i = 1; i < clauses.size(); i++) {
final Clause l = clauses.get(i);
if(!(l instanceof Let) || l.uses(Use.NDT) || l.uses(Use.CNS)) continue;
final Let let = (Let) l;
// find insertion position
int insert = -1;
for(int j = i; --j >= 0;) {
final Clause curr = clauses.get(j);
if(!curr.skippable(let)) break;
// insert directly above the highest skippable for or window clause
// this guarantees that no unnecessary swaps occur
if(curr instanceof For || curr instanceof Window) insert = j;
}
if(insert >= 0) {
clauses.add(insert, clauses.remove(i));
if(!change) ctx.compInfo(QueryText.OPTFORLET);
change = true;
// it's safe to go on because clauses below the current one are never touched
}
}
return change;
}
/**
* Slides where clauses upwards and removes those that do not filter anything.
* @param ctx query context
* @param scp variable scope
* @return change flag
* @throws QueryException query exception
*/
private boolean optimizeWhere(final QueryContext ctx, final VarScope scp)
throws QueryException {
boolean change = false;
for(int i = 0; i < clauses.size(); i++) {
final Clause c = clauses.get(i);
if(!(c instanceof Where) || c.uses(Use.NDT)) continue;
final Where wh = (Where) c;
if(wh.pred.isValue()) {
if(!(wh.pred instanceof Bln))
wh.pred = Bln.get(wh.pred.ebv(ctx, wh.info).bool(wh.info));
// predicate is always false: no results possible
if(!((Bln) wh.pred).bool(null)) break;
// condition is always true
clauses.remove(i
change = true;
} else {
// find insertion position
int insert = -1;
for(int j = i; --j >= 0;) {
final Clause curr = clauses.get(j);
if(!curr.skippable(wh)) break;
// where clauses are always moved to avoid unnecessary computations,
// but skipping only other where clauses can cause infinite loops
if(!(curr instanceof Where)) insert = j;
}
if(insert >= 0) {
clauses.add(insert, clauses.remove(i));
change = true;
// it's safe to go on because clauses below the current one are never touched
}
final int newPos = insert < 0 ? i : insert;
for(int b4 = newPos; --b4 >= 0;) {
final Clause before = clauses.get(b4);
if(before instanceof For && ((For) before).toPred(ctx, scp, wh.pred)) {
clauses.remove(newPos);
i
change = true;
} else if(before instanceof Where) {
continue;
}
break;
}
}
}
if(change) ctx.compInfo(QueryText.OPTWHERE2);
return change;
}
/** Merges consecutive {@code where} clauses. */
private void mergeWheres() {
Where before = null;
final Iterator<Clause> iter = clauses.iterator();
while(iter.hasNext()) {
final Clause cl = iter.next();
if(cl instanceof Where) {
final Where wh = (Where) cl;
if(wh.pred == Bln.FALSE) return;
if(before != null) {
iter.remove();
final Expr e = before.pred;
if(e instanceof And) {
final And and = (And) e;
and.expr = Array.add(and.expr, wh.pred);
} else {
before.pred = new And(before.info, new Expr[] { e, wh.pred });
}
} else {
before = wh;
}
} else {
before = null;
}
}
}
@Override
public boolean isVacuous() {
return ret.isVacuous();
}
@Override
public boolean uses(final Use u) {
if(u == Use.X30 && xq30) return true;
for(final Clause cls : clauses) if(cls.uses(u)) return true;
return ret.uses(u);
}
@Override
public boolean removable(final Var v) {
for(final Clause cl : clauses) if(!cl.removable(v)) return false;
return ret.removable(v);
}
@Override
public VarUsage count(final Var v) {
return count(v, 0);
}
/**
* Counts the number of usages of the given variable starting from the given clause.
* @param v variable
* @param p start position
* @return usage count
*/
private VarUsage count(final Var v, final int p) {
long c = 1;
VarUsage uses = VarUsage.NEVER;
final ListIterator<Clause> iter = clauses.listIterator(p);
while(iter.hasNext()) {
final Clause cl = iter.next();
uses = uses.plus(cl.count(v).times(c));
c = cl.calcSize(c);
}
return uses.plus(ret.count(v).times(c));
}
@Override
public Expr inline(final QueryContext ctx, final VarScope scp,
final Var v, final Expr e) throws QueryException {
return inline(ctx, scp, v, e, 0) ? optimize(ctx, scp) : null;
}
/**
* Inlines an expression bound to a given variable, starting at a specified clause.
* @param ctx query context
* @param scp variable scope
* @param v variable
* @param e expression to inline
* @param p clause position
* @return if changes occurred
* @throws QueryException query exception
*/
private boolean inline(final QueryContext ctx, final VarScope scp,
final Var v, final Expr e, final int p) throws QueryException {
boolean change = false;
final ListIterator<Clause> iter = clauses.listIterator(p);
while(iter.hasNext()) {
final Clause cl = iter.next();
try {
final Clause c = cl.inline(ctx, scp, v, e);
if(c != null) {
change = true;
iter.set(c);
}
} catch(final QueryException qe) {
return clauseError(qe, iter.previousIndex() + 1, cl.info);
}
}
try {
final Expr rt = ret.inline(ctx, scp, v, e);
if(rt != null) {
change = true;
ret = rt;
}
} catch(final QueryException qe) {
return clauseError(qe, clauses.size(), info);
}
return change;
}
/**
* Tries to recover from a compile-time exception inside a FLWOR clause.
* @param qe thrown exception
* @param idx index of the throwing clause, size of {@link #clauses} for return clause
* @param ii input info
* @return {@code true} if the GFLWOR expression has to stay
* @throws QueryException query exception if the whole expression fails
*/
private boolean clauseError(final QueryException qe, final int idx, final InputInfo ii)
throws QueryException {
final ListIterator<Clause> iter = clauses.listIterator(idx);
while(iter.hasPrevious()) {
final Clause b4 = iter.previous();
if(b4 instanceof For || b4 instanceof Window || b4 instanceof Where) {
iter.next();
while(iter.hasNext()) {
iter.next();
iter.remove();
}
ret = FNInfo.error(qe, ii);
return true;
}
}
throw qe;
}
@Override
public Expr copy(final QueryContext ctx, final VarScope scp, final IntMap<Var> vs) {
final LinkedList<Clause> cls = new LinkedList<Clause>();
for(final Clause cl : clauses) cls.add(cl.copy(ctx, scp, vs));
return copyType(new GFLWOR(info, cls, ret.copy(ctx, scp, vs)));
}
/**
* Checks if this FLWOR expression only used for, let and where clauses.
* @return result of check
*/
private boolean isFLWR() {
for(final Clause cl : clauses)
if(!(cl instanceof For || cl instanceof Let || cl instanceof Where)) return false;
return true;
}
@Override
public boolean accept(final ASTVisitor visitor) {
for(final Clause cl : clauses) if(!cl.accept(visitor)) return false;
return ret.accept(visitor);
}
@Override
public void plan(final FElem plan) {
final FElem e = planElem();
for(final Clause cl : clauses) cl.plan(e);
ret.plan(e);
plan.add(e);
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder();
for(final Clause cl : clauses) sb.append(cl).append(' ');
return sb.append(QueryText.RETURN).append(' ').append(ret).toString();
}
@Override
public void checkUp() throws QueryException {
for(final Clause cl : clauses) cl.checkUp();
ret.checkUp();
}
@Override
public boolean databases(final StringList db) {
for(final Clause clause : clauses) if(!clause.databases(db)) return false;
return ret.databases(db);
}
@Override
public Expr markTailCalls() {
long n = 1;
for(final Clause c : clauses) if((n = c.calcSize(n)) != 1) return this;
ret.markTailCalls();
return this;
}
@Override
public int exprSize() {
int sz = 1;
for(final Clause cl : clauses) sz += cl.exprSize();
return ret.exprSize() + sz;
}
interface Eval {
/**
* Makes the next evaluation step if available. This method is guaranteed
* to not be called again if it has once returned {@code false}.
* @param ctx query context
* @return {@code true} if step was made, {@code false} if no more
* results exist
* @throws QueryException evaluation exception
*/
boolean next(final QueryContext ctx) throws QueryException;
}
public abstract static class Clause extends ParseExpr {
/** All variables declared in this clause. */
final Var[] vars;
/**
* Constructor.
* @param ii input info
* @param vs declared variables
*/
protected Clause(final InputInfo ii, final Var... vs) {
super(ii);
vars = vs;
}
/**
* Cleans unused variables from this clause.
* @param ctx query context
* @param used list of the IDs of all variables used in the following clauses
* @param decl variables declared by this FLWOR expression
* @return {@code true} if something changed, {@code false} otherwise
*/
@SuppressWarnings("unused")
boolean clean(final QueryContext ctx, final IntMap<Var> decl, final BitArray used) {
return false;
}
/**
* Evaluates the clause.
* @param sub wrapped evaluator
* @return evaluator
*/
abstract Eval eval(final Eval sub);
@Override
public abstract Clause compile(QueryContext ctx, final VarScope scp)
throws QueryException;
@Override
public abstract Clause optimize(final QueryContext ctx, final VarScope scp)
throws QueryException;
@Override
public abstract Clause inline(QueryContext ctx, VarScope scp, Var v, Expr e)
throws QueryException;
@Deprecated
@Override
public Iter iter(final QueryContext ctx) throws QueryException {
throw Util.notexpected();
}
@Deprecated
@Override
public Value value(final QueryContext ctx) throws QueryException {
throw Util.notexpected();
}
@Deprecated
@Override
public Item item(final QueryContext ctx, final InputInfo ii) throws QueryException {
throw Util.notexpected();
}
@Override
public abstract GFLWOR.Clause copy(QueryContext ctx, VarScope scp, IntMap<Var> vs);
/**
* Checks if the given clause can be slided over this clause.
* @param cl clause
* @return result of check
*/
boolean skippable(final Clause cl) {
return cl.accept(new ASTVisitor() {
@Override
public boolean used(final VarRef ref) {
for(final Var v : vars) if(v.is(ref.var)) return false;
return true;
}
});
}
/**
* All declared variables of this clause.
* @return declared variables
*/
public final Var[] vars() {
return vars;
}
/**
* Checks if the given variable is declared by this clause.
* @param v variable
* @return {code true} if the variable was declared here, {@code false} otherwise
*/
public final boolean declares(final Var v) {
for(final Var decl : vars) if(v.is(decl)) return true;
return false;
}
/**
* Calculates the number of results.
* @param count number of incoming tuples, must be greater than zero
* @return number of outgoing tuples if known, {@code -1} otherwise
*/
abstract long calcSize(long count);
}
} |
package org.graphity.browser;
import com.hp.hpl.jena.ontology.OntDocumentManager;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.util.LocationMapper;
import javax.ws.rs.*;
import javax.ws.rs.core.Response.ResponseBuilder;
import javax.ws.rs.core.*;
import org.graphity.ldp.model.impl.ResourceBase;
import org.graphity.model.ResourceFactory;
import org.graphity.util.QueryBuilder;
import org.graphity.util.locator.PrefixMapper;
import org.graphity.util.manager.DataManager;
import org.graphity.vocabulary.Graphity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.topbraid.spin.model.SPINFactory;
import org.topbraid.spin.model.Select;
@Path("/{path: .*}")
public class Resource extends ResourceBase
{
private String uri = null;
private Model model = null;
private OntModel ontModel = null;
private String endpointUri = null;
private Query query = null;
private QueryBuilder qb = null;
private com.hp.hpl.jena.rdf.model.Resource spinRes = null;
private MediaType acceptType = MediaType.APPLICATION_XHTML_XML_TYPE;
private Request req = null;
private static final Logger log = LoggerFactory.getLogger(Resource.class);
public Resource(@Context UriInfo uriInfo,
@Context HttpHeaders headers,
@Context Request req,
@QueryParam("uri") String uri,
@QueryParam("endpoint-uri") String endpointUri,
@QueryParam("accept") MediaType acceptType,
@QueryParam("limit") @DefaultValue("10") long limit,
@QueryParam("offset") @DefaultValue("0") long offset,
@QueryParam("order-by") String orderBy,
@QueryParam("desc") @DefaultValue("true") boolean desc)
{
super(uriInfo, req);
this.uri = uri;
this.endpointUri = endpointUri;
this.req = req;
log.debug("URI: {} Endpoint URI: {}", uri, endpointUri);
if (acceptType != null) this.acceptType = acceptType;
else
if (headers.getAcceptableMediaTypes().get(0).isCompatible(org.graphity.MediaType.APPLICATION_RDF_XML_TYPE) ||
headers.getAcceptableMediaTypes().get(0).isCompatible(org.graphity.MediaType.TEXT_TURTLE_TYPE))
this.acceptType = headers.getAcceptableMediaTypes().get(0);
log.debug("AcceptType: {} Acceptable MediaTypes: {}", this.acceptType, headers.getAcceptableMediaTypes());
// ontology URI is base URI-dependent
String ontologyUri = uriInfo.getBaseUri().toString();
log.debug("Adding prefix mapping prefix: {} altName: {} ", ontologyUri, "ontology.ttl");
((PrefixMapper)LocationMapper.get()).addAltPrefixEntry(ontologyUri, "ontology.ttl");
log.debug("DataManager.get().getLocationMapper(): {}", DataManager.get().getLocationMapper());
ontModel = OntDocumentManager.getInstance().
getOntology(uriInfo.getBaseUri().toString(), OntModelSpec.OWL_MEM_RDFS_INF);
com.hp.hpl.jena.rdf.model.Resource resource = ontModel.createResource(getURI());
log.debug("Resource: {} with URI: {}", resource, getURI());
if (this.uri == null && resource.hasProperty(Graphity.query)) // only build Query if it's not default DESCRIBE
{
spinRes = resource.getPropertyResourceValue(Graphity.query);
log.trace("Explicit query resource {} for URI {}", spinRes, getURI());
if (SPINFactory.asQuery(spinRes) instanceof Select) // wrap SELECT into DESCRIBE
{
log.trace("Explicit query is SELECT, wrapping into DESCRIBE");
QueryBuilder selectBuilder = QueryBuilder.fromResource(spinRes).
limit(limit).
offset(offset);
if (orderBy != null) selectBuilder.orderBy(orderBy, desc);
qb = QueryBuilder.fromDescribe().subQuery(selectBuilder);
}
else
qb = QueryBuilder.fromResource(spinRes); // CONSTRUCT
query = qb.build();
log.debug("Query generated with QueryBuilder: {}", query);
}
if (this.endpointUri == null && resource.hasProperty(Graphity.service))
this.endpointUri = resource.getPropertyResourceValue(Graphity.service).
getPropertyResourceValue(ontModel.
getProperty("http://www.w3.org/ns/sparql-service-description#endpoint")).getURI();
}
@Override
public Model getModel()
{
if (model == null)
try
{
log.debug("Loading Model from local Model or remote URI or endpoint");
model = getResource().getModel();
if (model.isEmpty() && uri != null && endpointUri != null) // fallback to Linked Data
{
log.debug("Model not loaded from SPARQL endpoint {}, falling back to LD URI: {}", endpointUri, uri);
model = ResourceFactory.getResource(uri).getModel();
}
}
catch (Exception ex)
{
log.trace("Error while loading Model from URI: {}", uri, ex);
throw new WebApplicationException(ex, Response.Status.INTERNAL_SERVER_ERROR);
}
if (model.isEmpty())
{
log.trace("Loaded Model is empty");
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
return model;
}
private org.graphity.model.Resource getResource()
{
if (uri == null && endpointUri == null) // local URI
{
if (query != null) return ResourceFactory.getResource(getOntModel(), query);
else return ResourceFactory.getResource(getOntModel(), getURI());
}
else // remote URI or endpoint
{
if (endpointUri != null)
{
if (query != null) return ResourceFactory.getResource(endpointUri, query);
else return ResourceFactory.getResource(endpointUri, uri);
}
else return ResourceFactory.getResource(uri);
}
}
protected void setModel(Model model)
{
this.model = model;
}
protected OntModel getOntModel()
{
return ontModel;
}
public com.hp.hpl.jena.rdf.model.Resource getSPINResource()
{
return spinRes;
}
public QueryBuilder getQueryBuilder()
{
return qb;
}
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Override
public Response post(Model rdfPost)
{
log.debug("POSTed Model: {} size: {}", rdfPost, rdfPost.size());
setModel(rdfPost);
return getResponse();
}
@Override
@GET
@Produces({MediaType.APPLICATION_XHTML_XML + "; charset=UTF-8",org.graphity.MediaType.APPLICATION_RDF_XML + "; charset=UTF-8", org.graphity.MediaType.TEXT_TURTLE + "; charset=UTF-8"})
public Response getResponse()
{
if (getAcceptType() != null)
{
// uses ModelProvider
if (getAcceptType().isCompatible(org.graphity.MediaType.APPLICATION_RDF_XML_TYPE))
{
log.debug("Accept param: {}, writing RDF/XML", getAcceptType());
return Response.ok(getModel(), org.graphity.MediaType.APPLICATION_RDF_XML_TYPE).
tag(getEntityTag()).build();
}
if (getAcceptType().isCompatible(org.graphity.MediaType.TEXT_TURTLE_TYPE))
{
log.debug("Accept param: {}, writing Turtle", getAcceptType());
return Response.ok(getModel(), org.graphity.MediaType.TEXT_TURTLE_TYPE).
tag(getEntityTag()).build();
}
}
// check if resource was modified and return 304 Not Modified if not
ResponseBuilder rb = req.evaluatePreconditions(getEntityTag());
if (rb != null) return rb.build();
return Response.ok(this).tag(getEntityTag()).build(); // uses ResourceXHTMLWriter
}
protected MediaType getAcceptType()
{
return acceptType;
}
@Override
public Response put(Model model)
{
throw new WebApplicationException(405); // method not allowed
}
@Override
public Response delete()
{
throw new WebApplicationException(405); // method not allowed
}
} |
package org.ihtsdo.json;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import com.google.gson.Gson;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import org.ihtsdo.json.model.versioned.Concept;
import org.ihtsdo.json.model.versioned.Concept4F;
import org.ihtsdo.json.model.versioned.ConceptAncestor;
import org.ihtsdo.json.model.versioned.ConceptDescriptor;
import org.ihtsdo.json.model.versioned.Description;
import org.ihtsdo.json.model.versioned.LangMembership;
import org.ihtsdo.json.model.versioned.LightDescription;
import org.ihtsdo.json.model.versioned.LightLangMembership;
import org.ihtsdo.json.model.versioned.LightRefsetMembership;
import org.ihtsdo.json.model.versioned.LightRelationship;
import org.ihtsdo.json.model.versioned.RefsetMembership;
import org.ihtsdo.json.model.versioned.Relationship;
import org.ihtsdo.json.model.versioned.TextIndexDescription;
/**
*
* @author Alejandro Rodriguez
*/
public class Transformer4F {
private static final String MAXEFFTIME = "99991231";
private String MODIFIER = "Existential restriction";
private String sep = System.getProperty("line.separator");
private Map<Long, List<ConceptDescriptor>> concepts;
private Map<Long, List<LightDescription>> descriptions;
private Map<Long, List<LightRelationship>> relationships;
private Map<Long, List<LightRefsetMembership>> simpleMembers;
private Map<Long, List<LightRefsetMembership>> simpleMapMembers;
private Map<Long, List<LightLangMembership>> languageMembers;
private Map<String, String> langCodes;
private String defaultLangCode = "en";
public String fsnType = "900000000000003001";
public String synType = "900000000000013009";
private Long inferred = 900000000000011006l;
private Long stated = 900000000000010007l;
private Long isaSCTId=116680003l;
private String defaultTermType = fsnType;
private HashMap<Long, List<LightDescription>> tdefMembers;
private HashMap<Long, List<LightRefsetMembership>> attrMembers;
private HashMap<Long, List<LightRefsetMembership>> assocMembers;
private ArrayList<Long> listA;
public Transformer4F() {
concepts = new HashMap<Long, List<ConceptDescriptor>>();
descriptions = new HashMap<Long, List<LightDescription>>();
relationships = new HashMap<Long, List<LightRelationship>>();
simpleMembers = new HashMap<Long, List<LightRefsetMembership>>();
assocMembers = new HashMap<Long, List<LightRefsetMembership>>();
attrMembers = new HashMap<Long, List<LightRefsetMembership>>();
tdefMembers = new HashMap<Long, List<LightDescription>>();
simpleMapMembers = new HashMap<Long, List<LightRefsetMembership>>();
languageMembers = new HashMap<Long, List<LightLangMembership>>();
langCodes = new HashMap<String, String>();
langCodes.put("en", "english");
langCodes.put("es", "spanish");
langCodes.put("da", "danish");
langCodes.put("sv", "swedish");
langCodes.put("fr", "french");
langCodes.put("nl", "dutch");
}
public static void main(String[] args) throws Exception {
Transformer4F tr = new Transformer4F();
// tr.setDefaultLangCode("da");
// tr.setDefaultTermType(tr.synType);
// tr.loadConceptsFile(new File("/Volumes/Macintosh HD2/tmp/destination/Snapshot/sct2_Concept_Snapshot_INT_20140131.txt"));
// tr.loadConceptsFile(new File("/Volumes/Macintosh HD2/tmp/content-processing-1.17-release-files/SnomedCT_Release_DK1000005_20131018/RF2Release/Snapshot/Terminology/sct2_Concept_Snapshot_DK1000005_20131018.txt"));
// tr.loadDescriptionsFile(new File("/Volumes/Macintosh HD2/tmp/destination/Snapshot/sct2_Description_Snapshot-en_INT_20140131.txt"));
// tr.loadDescriptionsFile(new File("/Volumes/Macintosh HD2/tmp/content-processing-1.17-release-files/SnomedCT_Release_DK1000005_20131018/RF2Release/Snapshot/Terminology/sct2_Description_Snapshot_DK1000005_20131018.txt"));
// tr.loadRelationshipsFile(new File("/Volumes/Macintosh HD2/tmp/destination/Snapshot/sct2_StatedRelationship_Snapshot_INT_20140131.txt"));
// tr.loadRelationshipsFile(new File("/Volumes/Macintosh HD2/tmp/content-processing-1.17-release-files/SnomedCT_Release_DK1000005_20131018/RF2Release/Snapshot/Terminology/sct2_StatedRelationship_Snapshot_DK1000005_20131018.txt"));
// tr.loadRelationshipsFile(new File("/Volumes/Macintosh HD2/tmp/destination/Snapshot/sct2_Relationship_Snapshot_INT_20140131.txt"));
// tr.loadRelationshipsFile(new File("/Volumes/Macintosh HD2/tmp/content-processing-1.17-release-files/SnomedCT_Release_DK1000005_20131018/RF2Release/Snapshot/Terminology/sct2_Relationship_Snapshot_DK1000005_20131018.txt"));
// tr.loadSimpleRefsetFile(new File("/Volumes/Macintosh HD2/tmp/destination/Snapshot/der2_Refset_SimpleSnapshot_INT_20140131.txt"));
// tr.loadSimpleMapRefsetFile(new File("/Volumes/Macintosh HD2/tmp/destination/Snapshot/der2_sRefset_SimpleMapSnapshot_INT_20140131.txt"));
// tr.loadLanguageRefsetFile(new File("/Volumes/Macintosh HD2/tmp/destination/Snapshot/der2_cRefset_LanguageSnapshot-en_INT_20140131.txt"));
// tr.loadLanguageRefsetFile(new File("/Volumes/Macintosh HD2/tmp/content-processing-1.17-release-files/SnomedCT_Release_DK1000005_20131018/RF2Release/Snapshot/Refset/Language/der2_cRefset_LanguageSnapshot-da_DK1000005_20131018.txt"));
// tr.loadLanguageRefsetFile(new File("/Volumes/Macintosh HD2/tmp/content-processing-1.17-release-files/SnomedCT_Release_DK1000005_20131018/RF2Release/Snapshot/Refset/Language/der2_cRefset_LanguageSnapshot-en_DK1000005_20131018.txt"));
// tr.createConceptsJsonFile("target/concepts.json");
// tr.createTextIndexFile("target/text-index.json");
tr.setDefaultLangCode("en");
tr.setDefaultTermType(tr.fsnType);
tr.loadConceptsFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Full/Terminology/sct2_Concept_Full_INT_20140131.txt"));
tr.loadDescriptionsFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Full/Terminology/sct2_Description_Full-en_INT_20140131.txt"));
tr.loadTextDefinitionFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Full/Terminology/sct2_TextDefinition_Full-en_INT_20140131.txt"));
tr.loadRelationshipsFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Full/Terminology/sct2_StatedRelationship_Full_INT_20140131.txt"));
tr.loadRelationshipsFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Full/Terminology/sct2_Relationship_Full_INT_20140131.txt"));
tr.loadSimpleRefsetFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Full/Refset/Content/der2_Refset_SimpleFull_INT_20140131.txt"));
tr.loadAssociationFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Full/Refset/Content/der2_cRefset_AssociationReferenceFull_INT_20140131.txt"));
tr.loadAttributeFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Full/Refset/Content/der2_cRefset_AttributeValueFull_INT_20140131.txt"));
tr.loadSimpleMapRefsetFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Full/Refset/Map/der2_sRefset_SimpleMapFull_INT_20140131.txt"));
tr.loadLanguageRefsetFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Full/Refset/Language/der2_cRefset_LanguageFull-en_INT_20140131.txt"));
tr.createConceptsJsonFile("target/concepts.json");
}
public void createTClosures() throws IOException {
loadConceptsFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Snapshot/Terminology/sct2_Concept_Snapshot_INT_20140131.txt"));
loadRelationshipsFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Snapshot/Terminology//sct2_Relationship_Snapshot_INT_20140131.txt"));
createTClosure("target/inferred_tc.txt",inferred);
relationships = new HashMap<Long, List<LightRelationship>>();
loadRelationshipsFile(new File("/Volumes/Macintosh HD2/SnomedCT_Release_INT_20140131/RF2Release/Snapshot/Terminology/sct2_StatedRelationship_Snapshot_INT_20140131.txt"));
createTClosure("target/stated_tc.txt",stated);
}
public void loadConceptsFile(File conceptsFile) throws FileNotFoundException, IOException {
System.out.println("Starting Concepts: " + conceptsFile.getName());
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(conceptsFile), "UTF8"));
try {
List<ConceptDescriptor>conceptVer=new ArrayList<ConceptDescriptor>();
String line = br.readLine();
line = br.readLine(); // Skip header
int count = 0;
while (line != null) {
if (line.isEmpty()) {
continue;
}
String[] columns = line.split("\\t");
ConceptDescriptor loopConcept = new ConceptDescriptor();
Long conceptId = Long.parseLong(columns[0]);
loopConcept.setConceptId(conceptId);
loopConcept.setActive(columns[2].equals("1"));
loopConcept.setEffectiveTime(columns[1]);
loopConcept.setScTime(MAXEFFTIME);
loopConcept.setModule(Long.parseLong(columns[3]));
loopConcept.setDefinitionStatus(columns[4].equals("900000000000074008") ? "Primitive" : "Fully defined");
if (concepts.containsKey(conceptId)){
conceptVer=concepts.get(conceptId);
for (ConceptDescriptor concDesc:conceptVer){
if (concDesc.getScTime().equals(MAXEFFTIME)){
concDesc.setScTime(columns[1]);
}
}
}else{
conceptVer=new ArrayList<ConceptDescriptor>();
}
conceptVer.add(loopConcept);
concepts.put(conceptId, conceptVer);
line = br.readLine();
count++;
if (count % 100000 == 0) {
System.out.print(".");
}
}
System.out.println(".");
System.out.println("Concepts loaded = " + concepts.size());
} finally {
br.close();
}
}
public void loadDescriptionsFile(File descriptionsFile) throws FileNotFoundException, IOException {
System.out.println("Starting Descriptions: " + descriptionsFile.getName());
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(descriptionsFile), "UTF8"));
int descriptionsCount = 0;
try {
String line = br.readLine();
line = br.readLine(); // Skip header
boolean act;
List<ConceptDescriptor> lcdesc=new ArrayList<ConceptDescriptor>();
while (line != null) {
if (line.isEmpty()) {
continue;
}
String[] columns = line.split("\\t");
LightDescription loopDescription = new LightDescription();
loopDescription.setDescriptionId(Long.parseLong(columns[0]));
act = columns[2].equals("1");
loopDescription.setActive(act);
loopDescription.setEffectiveTime(columns[1]);
loopDescription.setScTime(MAXEFFTIME);
Long sourceId = Long.parseLong(columns[4]);
loopDescription.setConceptId(sourceId);
loopDescription.setType(Long.parseLong(columns[6]));
loopDescription.setTerm(columns[7]);
loopDescription.setIcs(Long.parseLong(columns[8]));
loopDescription.setModule(Long.parseLong(columns[3]));
loopDescription.setLang(columns[5]);
List<LightDescription> list = descriptions.get(sourceId);
if (list == null) {
list = new ArrayList<LightDescription>();
}else{
for (LightDescription item:list){
if (item.getScTime().equals(MAXEFFTIME)){
item.setScTime(columns[1]);
}
}
}
list.add(loopDescription);
descriptions.put(sourceId, list);
if (act && columns[6].equals("900000000000003001") && columns[5].equals("en")) {
lcdesc = concepts.get(sourceId);
for (ConceptDescriptor concDesc:lcdesc){
if (concDesc.getEffectiveTime().compareTo(columns[1])<=0 && concDesc.getScTime().compareTo(columns[1])>0){
concDesc.setDefaultTerm(columns[7]);
}
}
} else if (act && columns[6].equals(defaultTermType) && columns[5].equals(defaultLangCode)) {
lcdesc = concepts.get(sourceId);
for (ConceptDescriptor concDesc:lcdesc){
if (concDesc.getEffectiveTime().compareTo(columns[1])<=0 && concDesc.getScTime().compareTo(columns[1])>0){
concDesc.setDefaultTerm(columns[7]);
}
}
}
line = br.readLine();
descriptionsCount++;
if (descriptionsCount % 100000 == 0) {
System.out.print(".");
}
}
System.out.println(".");
System.out.println("Descriptions loaded = " + descriptions.size());
} finally {
br.close();
}
}
public void loadTextDefinitionFile(File textDefinitionFile) throws FileNotFoundException, IOException {
System.out.println("Starting Text Definitions: " + textDefinitionFile.getName());
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(textDefinitionFile), "UTF8"));
int descriptionsCount = 0;
try {
String line = br.readLine();
line = br.readLine(); // Skip header
boolean act;
while (line != null) {
if (line.isEmpty()) {
continue;
}
String[] columns = line.split("\\t");
LightDescription loopDescription = new LightDescription();
loopDescription.setDescriptionId(Long.parseLong(columns[0]));
act = columns[2].equals("1");
loopDescription.setActive(act);
loopDescription.setEffectiveTime(columns[1]);
loopDescription.setScTime(MAXEFFTIME);
Long sourceId = Long.parseLong(columns[4]);
loopDescription.setConceptId(sourceId);
loopDescription.setType(Long.parseLong(columns[6]));
loopDescription.setTerm(columns[7]);
loopDescription.setIcs(Long.parseLong(columns[8]));
loopDescription.setModule(Long.parseLong(columns[3]));
loopDescription.setLang(columns[5]);
List<LightDescription> list = tdefMembers.get(sourceId);
if (list == null) {
list = new ArrayList<LightDescription>();
}else{
for (LightDescription item:list){
if (item.getScTime().equals(MAXEFFTIME)){
item.setScTime(columns[1]);
}
}
}
list.add(loopDescription);
tdefMembers.put(sourceId, list);
line = br.readLine();
descriptionsCount++;
if (descriptionsCount % 100000 == 0) {
System.out.print(".");
}
}
System.out.println(".");
System.out.println("Text Definitions loaded = " + tdefMembers.size());
} finally {
br.close();
}
}
public void loadRelationshipsFile(File relationshipsFile) throws FileNotFoundException, IOException {
System.out.println("Starting Relationships: " + relationshipsFile.getName());
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(relationshipsFile), "UTF8"));
try {
String line = br.readLine();
line = br.readLine(); // Skip header
int count = 0;
while (line != null) {
if (line.isEmpty()) {
continue;
}
String[] columns = line.split("\\t");
LightRelationship loopRelationship = new LightRelationship();
loopRelationship.setActive(columns[2].equals("1"));
loopRelationship.setEffectiveTime(columns[1]);
loopRelationship.setModule(Long.parseLong(columns[3]));
loopRelationship.setScTime(MAXEFFTIME);
loopRelationship.setTarget(Long.parseLong(columns[5]));
loopRelationship.setType(Long.parseLong(columns[7]));
loopRelationship.setModifier(Long.parseLong(columns[9]));
loopRelationship.setGroupId(Integer.parseInt(columns[6]));
Long sourceId = Long.parseLong(columns[4]);
loopRelationship.setSourceId(sourceId);
loopRelationship.setCharType(Long.parseLong(columns[8]));
List<LightRelationship> relList = relationships.get(sourceId);
if (relList == null) {
relList = new ArrayList<LightRelationship>();
}else{
for (LightRelationship item:relList){
if (item.getScTime().equals(MAXEFFTIME)){
item.setScTime(columns[1]);
}
}
}
relList.add(loopRelationship);
relationships.put(sourceId, relList);
line = br.readLine();
count++;
if (count % 100000 == 0) {
System.out.print(".");
}
}
System.out.println(".");
System.out.println("Relationships loaded = " + relationships.size());
} finally {
br.close();
}
}
public void loadSimpleRefsetFile(File simpleRefsetFile) throws FileNotFoundException, IOException {
System.out.println("Starting Simple Refset Members: " + simpleRefsetFile.getName());
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(simpleRefsetFile), "UTF8"));
try {
String line = br.readLine();
line = br.readLine(); // Skip header
int count = 0;
while (line != null) {
if (line.isEmpty()) {
continue;
}
String[] columns = line.split("\\t");
if (columns[2].equals("1")) {
LightRefsetMembership loopMember = new LightRefsetMembership();
loopMember.setType(LightRefsetMembership.RefsetMembershipType.SIMPLE_REFSET.name());
loopMember.setUuid(UUID.fromString(columns[0]));
loopMember.setActive(columns[2].equals("1"));
loopMember.setEffectiveTime(columns[1]);
loopMember.setScTime(MAXEFFTIME);
loopMember.setModule(Long.parseLong(columns[3]));
Long sourceId = Long.parseLong(columns[5]);
loopMember.setReferencedComponentId(sourceId);
loopMember.setRefset(Long.parseLong(columns[4]));
List<LightRefsetMembership> list = simpleMembers.get(sourceId);
if (list == null) {
list = new ArrayList<LightRefsetMembership>();
}else{
for (LightRefsetMembership item:list){
if (item.getScTime().equals(MAXEFFTIME) && item.getRefset().equals(Long.parseLong(columns[4]))){
item.setScTime(columns[1]);
}
}
}
list.add(loopMember);
simpleMembers.put(Long.parseLong(columns[5]), list);
count++;
if (count % 100000 == 0) {
System.out.print(".");
}
}
line = br.readLine();
}
System.out.println(".");
System.out.println("SimpleRefsetMember loaded = " + simpleMembers.size());
} finally {
br.close();
}
}
public void loadAssociationFile(File associationsFile) throws FileNotFoundException, IOException {
System.out.println("Starting Association Refset Members: " + associationsFile.getName());
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(associationsFile), "UTF8"));
try {
String line = br.readLine();
line = br.readLine(); // Skip header
int count = 0;
while (line != null) {
if (line.isEmpty()) {
continue;
}
String[] columns = line.split("\\t");
if (columns[2].equals("1")) {
LightRefsetMembership loopMember = new LightRefsetMembership();
loopMember.setType(LightRefsetMembership.RefsetMembershipType.ASSOCIATION.name());
loopMember.setUuid(UUID.fromString(columns[0]));
loopMember.setActive(columns[2].equals("1"));
loopMember.setEffectiveTime(columns[1]);
loopMember.setScTime(MAXEFFTIME);
loopMember.setModule(Long.parseLong(columns[3]));
Long sourceId = Long.parseLong(columns[5]);
loopMember.setReferencedComponentId(sourceId);
loopMember.setRefset(Long.parseLong(columns[4]));
loopMember.setCidValue(Long.parseLong(columns[6]));
List<LightRefsetMembership> list = assocMembers.get(sourceId);
if (list == null) {
list = new ArrayList<LightRefsetMembership>();
}else{
for (LightRefsetMembership item:list){
if (item.getScTime().equals(MAXEFFTIME) && item.getRefset().equals(Long.parseLong(columns[4]))){
item.setScTime(columns[1]);
}
}
}
list.add(loopMember);
assocMembers.put(Long.parseLong(columns[5]), list);
count++;
if (count % 100000 == 0) {
System.out.print(".");
}
}
line = br.readLine();
}
System.out.println(".");
System.out.println("AssociationMember loaded = " + assocMembers.size());
} finally {
br.close();
}
}
public void loadAttributeFile(File attributeFile) throws FileNotFoundException, IOException {
System.out.println("Starting Attribute Refset Members: " + attributeFile.getName());
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(attributeFile), "UTF8"));
try {
String line = br.readLine();
line = br.readLine(); // Skip header
int count = 0;
while (line != null) {
if (line.isEmpty()) {
continue;
}
String[] columns = line.split("\\t");
if (columns[2].equals("1")) {
LightRefsetMembership loopMember = new LightRefsetMembership();
loopMember.setType(LightRefsetMembership.RefsetMembershipType.ATTRIBUTE_VALUE.name());
loopMember.setUuid(UUID.fromString(columns[0]));
loopMember.setActive(columns[2].equals("1"));
loopMember.setEffectiveTime(columns[1]);
loopMember.setScTime(MAXEFFTIME);
loopMember.setModule(Long.parseLong(columns[3]));
Long sourceId = Long.parseLong(columns[5]);
loopMember.setReferencedComponentId(sourceId);
loopMember.setRefset(Long.parseLong(columns[4]));
loopMember.setCidValue(Long.parseLong(columns[6]));
List<LightRefsetMembership> list = attrMembers.get(sourceId);
if (list == null) {
list = new ArrayList<LightRefsetMembership>();
}else{
for (LightRefsetMembership item:list){
if (item.getScTime().equals(MAXEFFTIME) && item.getRefset().equals(Long.parseLong(columns[4]))){
item.setScTime(columns[1]);
}
}
}
list.add(loopMember);
attrMembers.put(Long.parseLong(columns[5]), list);
count++;
if (count % 100000 == 0) {
System.out.print(".");
}
}
line = br.readLine();
}
System.out.println(".");
System.out.println("AttributeMember loaded = " + attrMembers.size());
} finally {
br.close();
}
}
public void loadSimpleMapRefsetFile(File simpleMapRefsetFile) throws FileNotFoundException, IOException {
System.out.println("Starting SimpleMap Refset Members: " + simpleMapRefsetFile.getName());
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(simpleMapRefsetFile), "UTF8"));
try {
String line = br.readLine();
line = br.readLine(); // Skip header
int count = 0;
while (line != null) {
if (line.isEmpty()) {
continue;
}
String[] columns = line.split("\\t");
if (columns[2].equals("1")) {
LightRefsetMembership loopMember = new LightRefsetMembership();
loopMember.setType(LightRefsetMembership.RefsetMembershipType.SIMPLEMAP.name());
loopMember.setUuid(UUID.fromString(columns[0]));
loopMember.setActive(columns[2].equals("1"));
loopMember.setEffectiveTime(columns[1]);
loopMember.setScTime(MAXEFFTIME);
loopMember.setModule(Long.parseLong(columns[3]));
Long sourceId = Long.parseLong(columns[5]);
loopMember.setReferencedComponentId(sourceId);
loopMember.setRefset(Long.parseLong(columns[4]));
loopMember.setOtherValue(columns[6]);
List<LightRefsetMembership> list = simpleMapMembers.get(sourceId);
if (list == null) {
list = new ArrayList<LightRefsetMembership>();
}else{
for (LightRefsetMembership item:list){
if (item.getScTime().equals(MAXEFFTIME) && item.getRefset().equals(Long.parseLong(columns[4]))){
item.setScTime(columns[1]);
}
}
}
list.add(loopMember);
simpleMapMembers.put(sourceId, list);
count++;
if (count % 100000 == 0) {
System.out.print(".");
}
}
line = br.readLine();
}
System.out.println(".");
System.out.println("SimpleMap RefsetMember loaded = " + simpleMapMembers.size());
} finally {
br.close();
}
}
public void loadLanguageRefsetFile(File languageRefsetFile) throws FileNotFoundException, IOException {
System.out.println("Starting Language Refset Members: " + languageRefsetFile.getName());
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(languageRefsetFile), "UTF8"));
try {
String line = br.readLine();
line = br.readLine(); // Skip header
int count = 0;
while (line != null) {
if (line.isEmpty()) {
continue;
}
String[] columns = line.split("\\t");
if (columns[2].equals("1")) {
LightLangMembership loopMember = new LightLangMembership();
loopMember.setUuid(UUID.fromString(columns[0]));
loopMember.setActive(columns[2].equals("1"));
loopMember.setEffectiveTime(columns[1]);
loopMember.setScTime(MAXEFFTIME);
loopMember.setModule(Long.parseLong(columns[3]));
Long sourceId = Long.parseLong(columns[5]);
loopMember.setDescriptionId(sourceId);
loopMember.setRefset(Long.parseLong(columns[4]));
loopMember.setAcceptability(Long.parseLong(columns[6]));
List<LightLangMembership> list = languageMembers.get(sourceId);
if (list == null) {
list = new ArrayList<LightLangMembership>();
}else{
for (LightLangMembership item:list){
if (item.getScTime().equals(MAXEFFTIME) && item.getRefset().equals(Long.parseLong(columns[4]))){
item.setScTime(columns[1]);
}
}
}
list.add(loopMember);
languageMembers.put(sourceId, list);
count++;
if (count % 100000 == 0) {
System.out.print(".");
}
}
line = br.readLine();
}
System.out.println(".");
System.out.println("LanguageMembers loaded = " + languageMembers.size());
} finally {
br.close();
}
}
public void createConceptsJsonFile(String fileName) throws FileNotFoundException, UnsupportedEncodingException, IOException {
System.out.println("Starting creation of " + fileName);
FileOutputStream fos = new FileOutputStream(fileName);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
BufferedWriter bw = new BufferedWriter(osw);
Gson gson = new Gson();
List<LightDescription> listLD = new ArrayList<LightDescription>();
List<Description> listD = new ArrayList<Description>();
List<LightLangMembership> listLLM = new ArrayList<LightLangMembership>();
List<LangMembership> listLM = new ArrayList<LangMembership>();
List<LightRelationship> listLR = new ArrayList<LightRelationship>();
List<Relationship> listR = new ArrayList<Relationship>();
List<LightRefsetMembership> listLRM = new ArrayList<LightRefsetMembership>();
List<RefsetMembership> listRM = new ArrayList<RefsetMembership>();
// int count = 0;
for (Long cptId : concepts.keySet()) {
// count++;
//if (count > 10) break;
Concept4F cpt = new Concept4F();
cpt.setConceptId(cptId);
List<ConceptDescriptor> cptdescs = concepts.get(cptId);
cpt.setVersions(cptdescs);
listLD = descriptions.get(cptId);
listD = new ArrayList<Description>();
if (listLD != null) {
Long descId;
for (LightDescription ldesc : listLD) {
Description d = new Description();
d.setActive(ldesc.getActive());
d.setConceptId(ldesc.getConceptId());
descId = ldesc.getDescriptionId();
d.setDescriptionId(descId);
d.setEffectiveTime(ldesc.getEffectiveTime());
d.setIcs(getCptVersion(concepts.get(ldesc.getIcs()),ldesc.getEffectiveTime()));
d.setTerm(ldesc.getTerm());
d.setLength(ldesc.getTerm().length());
d.setModule(ldesc.getModule());
d.setType(getCptVersion(concepts.get(ldesc.getType()),ldesc.getEffectiveTime()));
d.setLang(ldesc.getLang());
listLLM = languageMembers.get(descId);
listLM = new ArrayList<LangMembership>();
if (listLLM != null) {
for (LightLangMembership llm : listLLM) {
LangMembership lm = new LangMembership();
lm.setActive(llm.getActive());
lm.setDescriptionId(descId);
lm.setEffectiveTime(llm.getEffectiveTime());
lm.setModule(llm.getModule());
lm.setAcceptability(getCptVersion(concepts.get(llm.getAcceptability()),llm.getEffectiveTime()));
lm.setRefset(getCptVersion(concepts.get(llm.getRefset()),llm.getEffectiveTime()));
lm.setUuid(llm.getUuid());
listLM.add(lm);
}
if (listLM.isEmpty()) {
d.setLangMemberships(null);
} else {
d.setLangMemberships(listLM);
}
}
listLRM = attrMembers.get(descId);
listRM = new ArrayList<RefsetMembership>();
if (listLRM != null) {
for (LightRefsetMembership lrm : listLRM) {
RefsetMembership rm = new RefsetMembership();
rm.setEffectiveTime(lrm.getEffectiveTime());
rm.setActive(lrm.getActive());
rm.setModule(lrm.getModule());
rm.setUuid(lrm.getUuid());
rm.setReferencedComponentId(descId);
rm.setRefset(getCptVersion(concepts.get(lrm.getRefset()),lrm.getEffectiveTime()));
rm.setType(lrm.getType());
rm.setCidValue(getCptVersion(concepts.get(lrm.getCidValue()),lrm.getEffectiveTime()));
listRM.add(rm);
}
if (listRM.isEmpty()){
d.setRefsetMemberships(null);
}else{
d.setRefsetMemberships(listRM);
}
}else{
d.setRefsetMemberships(null);
}
listD.add(d);
}
}
listLD = tdefMembers.get(cptId);
if (listLD != null) {
Long descId;
for (LightDescription ldesc : listLD) {
Description d = new Description();
d.setActive(ldesc.getActive());
d.setConceptId(ldesc.getConceptId());
descId = ldesc.getDescriptionId();
d.setDescriptionId(descId);
d.setEffectiveTime(ldesc.getEffectiveTime());
d.setIcs(getCptVersion(concepts.get(ldesc.getIcs()),ldesc.getEffectiveTime()));
d.setTerm(ldesc.getTerm());
d.setLength(ldesc.getTerm().length());
d.setModule(ldesc.getModule());
d.setType(getCptVersion(concepts.get(ldesc.getType()),ldesc.getEffectiveTime()));
d.setLang(ldesc.getLang());
listLLM = languageMembers.get(descId);
listLM = new ArrayList<LangMembership>();
if (listLLM != null) {
for (LightLangMembership llm : listLLM) {
LangMembership lm = new LangMembership();
lm.setActive(llm.getActive());
lm.setDescriptionId(descId);
lm.setEffectiveTime(llm.getEffectiveTime());
lm.setModule(llm.getModule());
lm.setAcceptability(getCptVersion(concepts.get(llm.getAcceptability()),llm.getEffectiveTime()));
lm.setRefset(getCptVersion(concepts.get(llm.getRefset()),llm.getEffectiveTime()));
lm.setUuid(llm.getUuid());
listLM.add(lm);
}
if (listLM.isEmpty()) {
d.setLangMemberships(null);
} else {
d.setLangMemberships(listLM);
}
}
listD.add(d);
}
}
if (listD!=null && !listD.isEmpty()){
cpt.setDescriptions(listD);
} else {
cpt.setDescriptions(null);
}
listLR = relationships.get(cptId);
listR = new ArrayList<Relationship>();
if (listLR != null) {
for (LightRelationship lrel : listLR) {
if (lrel.getCharType().equals(900000000000010007L)) {
Relationship d = new Relationship();
d.setEffectiveTime(lrel.getEffectiveTime());
d.setActive(lrel.getActive());
d.setModule(lrel.getModule());
d.setGroupId(lrel.getGroupId());
d.setModifier(MODIFIER);
d.setSourceId(cptId);
d.setTarget(getCptVersion(concepts.get(lrel.getTarget()),lrel.getEffectiveTime()));
d.setType(getCptVersion(concepts.get(lrel.getType()),lrel.getEffectiveTime()));
d.setCharType(getCptVersion(concepts.get(lrel.getCharType()),lrel.getEffectiveTime()));
listR.add(d);
}
}
if (listR.isEmpty()) {
cpt.setStatedRelationships(null);
} else {
cpt.setStatedRelationships(listR);
}
} else {
cpt.setStatedRelationships(null);
}
listLR = relationships.get(cptId);
listR = new ArrayList<Relationship>();
if (listLR != null) {
for (LightRelationship lrel : listLR) {
if (lrel.getCharType().equals(900000000000011006L)) {
Relationship d = new Relationship();
d.setEffectiveTime(lrel.getEffectiveTime());
d.setActive(lrel.getActive());
d.setModule(lrel.getModule());
d.setGroupId(lrel.getGroupId());
d.setModifier(MODIFIER);
d.setSourceId(cptId);
d.setTarget(getCptVersion(concepts.get(lrel.getTarget()),lrel.getEffectiveTime()));
d.setType(getCptVersion(concepts.get(lrel.getType()),lrel.getEffectiveTime()));
d.setCharType(getCptVersion(concepts.get(lrel.getCharType()),lrel.getEffectiveTime()));
listR.add(d);
}
}
if (listR.isEmpty()) {
cpt.setRelationships(null);
} else {
cpt.setRelationships(listR);
}
} else {
cpt.setRelationships(null);
}
listLRM = simpleMembers.get(cptId);
listRM = new ArrayList<RefsetMembership>();
if (listLRM != null) {
for (LightRefsetMembership lrm : listLRM) {
RefsetMembership d = new RefsetMembership();
d.setEffectiveTime(lrm.getEffectiveTime());
d.setActive(lrm.getActive());
d.setModule(lrm.getModule());
d.setUuid(lrm.getUuid());
d.setReferencedComponentId(cptId);
d.setRefset(getCptVersion(concepts.get(lrm.getRefset()),lrm.getEffectiveTime()));
d.setType(lrm.getType());
listRM.add(d);
}
}
listLRM = simpleMapMembers.get(cptId);
if (listLRM != null) {
for (LightRefsetMembership lrm : listLRM) {
RefsetMembership d = new RefsetMembership();
d.setEffectiveTime(lrm.getEffectiveTime());
d.setActive(lrm.getActive());
d.setModule(lrm.getModule());
d.setUuid(lrm.getUuid());
d.setReferencedComponentId(cptId);
d.setRefset(getCptVersion(concepts.get(lrm.getRefset()),lrm.getEffectiveTime()));
d.setType(lrm.getType());
d.setOtherValue(lrm.getOtherValue());
listRM.add(d);
}
}
listLRM = assocMembers.get(cptId);
if (listLRM != null) {
for (LightRefsetMembership lrm : listLRM) {
RefsetMembership d = new RefsetMembership();
d.setEffectiveTime(lrm.getEffectiveTime());
d.setActive(lrm.getActive());
d.setModule(lrm.getModule());
d.setUuid(lrm.getUuid());
d.setReferencedComponentId(cptId);
d.setRefset(getCptVersion(concepts.get(lrm.getRefset()),lrm.getEffectiveTime()));
d.setType(lrm.getType());
d.setCidValue(getCptVersion(concepts.get(lrm.getCidValue()),lrm.getEffectiveTime()));
listRM.add(d);
}
}
listLRM = attrMembers.get(cptId);
if (listLRM != null) {
for (LightRefsetMembership lrm : listLRM) {
RefsetMembership d = new RefsetMembership();
d.setEffectiveTime(lrm.getEffectiveTime());
d.setActive(lrm.getActive());
d.setModule(lrm.getModule());
d.setUuid(lrm.getUuid());
d.setReferencedComponentId(cptId);
d.setRefset(getCptVersion(concepts.get(lrm.getRefset()),lrm.getEffectiveTime()));
d.setType(lrm.getType());
d.setCidValue(getCptVersion(concepts.get(lrm.getCidValue()),lrm.getEffectiveTime()));
listRM.add(d);
}
}
if (listRM.isEmpty()) {
cpt.setMemberships(null);
} else {
cpt.setMemberships(listRM);
}
bw.append(gson.toJson(cpt).toString());
bw.append(sep);
}
bw.close();
System.out.println(fileName + " Done");
}
private ConceptDescriptor getCptVersion(List<ConceptDescriptor> list,
String effectiveTime) {
for (ConceptDescriptor concDesc:list){
if (concDesc.getEffectiveTime().compareTo(effectiveTime)<=0 && concDesc.getScTime().compareTo(effectiveTime)>0){
return concDesc;
}
}
return null;
}
public String getDefaultLangCode() {
return defaultLangCode;
}
public void setDefaultLangCode(String defaultLangCode) {
this.defaultLangCode = defaultLangCode;
}
private void createTClosure(String fileName,Long charType) throws IOException {
System.out.println("Starting creation of " + fileName);
FileOutputStream fos = new FileOutputStream(fileName);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
BufferedWriter bw = new BufferedWriter(osw);
Gson gson = new Gson();
// int count = 0;
for (Long cptId : concepts.keySet()) {
listA = new ArrayList<Long>();
getAncestors(cptId,charType);
if (!listA.isEmpty()){
ConceptAncestor ca=new ConceptAncestor();
ca.setConceptId(cptId);
ca.setAncestor(listA);
bw.append(gson.toJson(ca).toString());
bw.append(sep);
}
}
bw.close();
System.out.println(fileName + " Done");
}
private void getAncestors(Long cptId,Long charType) {
List<LightRelationship> listLR = new ArrayList<LightRelationship>();
listLR = relationships.get(cptId);
if (listLR != null) {
for (LightRelationship lrel : listLR) {
if (lrel.getCharType().equals(charType) &&
lrel.getType().equals(isaSCTId) &&
lrel.getActive()) {
Long tgt=lrel.getTarget();
if (!listA.contains(tgt)){
listA.add(tgt);
getAncestors(tgt,charType);
}
}
}
}
return ;
}
public void createTextIndexFile(String fileName) throws FileNotFoundException, UnsupportedEncodingException, IOException {
System.out.println("Starting creation of " + fileName);
FileOutputStream fos = new FileOutputStream(fileName);
OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
BufferedWriter bw = new BufferedWriter(osw);
Gson gson = new Gson();
// int count = 0;
for (long conceptId : descriptions.keySet()) {
// count++;
//if (count > 10) break;
for (LightDescription ldesc : descriptions.get(conceptId)) {
TextIndexDescription d = new TextIndexDescription();
d.setActive(ldesc.getActive());
d.setTerm(ldesc.getTerm());
d.setLength(ldesc.getTerm().length());
d.setTypeId(ldesc.getType());
d.setConceptId(ldesc.getConceptId());
d.setDescriptionId(ldesc.getDescriptionId());
// using long lang names for Mongo 2.4.x text indexes
d.setLang(langCodes.get(ldesc.getLang()));
ConceptDescriptor concept = getCptVersion(concepts.get(ldesc.getConceptId()),ldesc.getEffectiveTime());
d.setConceptActive(concept.getActive());
d.setFsn(concept.getDefaultTerm());
if (d.getFsn() == null) {
System.out.println("FSN Issue..." + d.getConceptId());
d.setFsn(d.getTerm());
}
d.setSemanticTag("");
if (d.getFsn().contains("(")) {
d.setSemanticTag(d.getFsn().substring(d.getFsn().indexOf("(") + 1, d.getFsn().length() - 1));
}
String cleanTerm = d.getTerm().replace("(", "").replace(")", "").trim().toLowerCase();
String[] tokens = cleanTerm.split("\\s+");
d.setWords(Arrays.asList(tokens));
bw.append(gson.toJson(d).toString());
bw.append(sep);
}
}
bw.close();
System.out.println(fileName + " Done");
}
public String getDefaultTermType() {
return defaultTermType;
}
public void setDefaultTermType(String defaultTermType) {
this.defaultTermType = defaultTermType;
}
} |
package org.jbake.parser;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.io.IOUtils;
import org.jbake.app.ConfigUtil.Keys;
import org.jbake.app.Crawler;
import org.json.simple.JSONValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class MarkupEngine implements ParserEngine {
private static final Logger LOGGER = LoggerFactory.getLogger(MarkupEngine.class);
private static final String HEADER_SEPARATOR = "~~~~~~";
/**
* Tests if this markup engine can process the document.
* @param context the parser context
* @return true if this markup engine has enough context to process this document. false otherwise
*/
public boolean validate(ParserContext context) { return true; }
/**
* Processes the document header. Usually subclasses will parse the document body and look for
* specific header metadata and export it into {@link ParserContext#getContents() contents} map.
* @param context the parser context
*/
public void processHeader(final ParserContext context) {}
/**
* Processes the body of the document. Usually subclasses will parse the document body and render
* it, exporting the result using the {@link org.jbake.parser.ParserContext#setBody(String)} method.
* @param context the parser context
*/
public void processBody(final ParserContext context) {}
/**
* Parse given file to extract as much infos as possible
* @param file file to process
* @return a map containing all infos. Returning null indicates an error, even if an exception would be better.
*/
public Map<String, Object> parse(Configuration config, File file, String contentPath) {
Map<String,Object> content = new HashMap<String, Object>();
InputStream is = null;
List<String> fileContents = null;
try {
is = new FileInputStream(file);
fileContents = IOUtils.readLines(is, config.getString("render.encoding"));
} catch (IOException e) {
LOGGER.error("Error while opening file {}: {}", file, e);
return null;
} finally {
IOUtils.closeQuietly(is);
}
boolean hasHeader = hasHeader(fileContents);
ParserContext context = new ParserContext(
file,
fileContents,
config,
contentPath,
hasHeader,
content
);
if (hasHeader) {
// read header from file
processHeader(config, fileContents, content);
}
// then read engine specific headers
processHeader(context);
if (config.getString(Keys.DEFAULT_STATUS) != null) {
// default status has been set
if (content.get(Crawler.Attributes.STATUS) == null) {
// file hasn't got status so use default
content.put(Crawler.Attributes.STATUS, config.getString(Keys.DEFAULT_STATUS));
}
}
if (content.get(Crawler.Attributes.TYPE)==null||content.get(Crawler.Attributes.STATUS)==null) {
// output error
LOGGER.warn("Error parsing meta data from header (missing type or status value) for file {}!", file);
return null;
}
// generate default body
processBody(fileContents, content);
// eventually process body using specific engine
if (validate(context)) {
processBody(context);
} else {
LOGGER.error("Incomplete source file ({}) for markup engine:", file, getClass().getSimpleName());
return null;
}
if (content.get("tags") != null) {
String[] tags = (String[]) content.get("tags");
for( int i=0; i<tags.length; i++ ) {
tags[i]=tags[i].trim();
if (config.getBoolean(Keys.TAG_SANITIZE)) {
tags[i]=tags[i].replace(" ", "-");
}
}
content.put("tags", tags);
}
// TODO: post parsing plugins to hook in here?
return content;
}
/**
* Checks if the file has a meta-data header.
*
* @param contents Contents of file
* @return true if header exists, false if not
*/
private boolean hasHeader(List<String> contents) {
boolean headerValid = false;
boolean headerSeparatorFound = false;
boolean statusFound = false;
boolean typeFound = false;
List<String> header = new ArrayList<String>();
for (String line : contents) {
header.add(line);
if (line.contains("=")) {
if (line.startsWith("type=")) {
typeFound = true;
}
if (line.startsWith("status=")) {
statusFound = true;
}
}
if (line.equals(HEADER_SEPARATOR)) {
headerSeparatorFound = true;
header.remove(line);
break;
}
}
if (headerSeparatorFound) {
headerValid = true;
for (String headerLine : header) {
if (!headerLine.contains("=")) {
headerValid = false;
break;
}
}
}
if (!headerValid || !statusFound || !typeFound) {
return false;
}
return true;
}
/**
* Process the header of the file.
* @param config
*
* @param contents Contents of file
* @param content
*/
private void processHeader(Configuration config, List<String> contents, final Map<String, Object> content) {
for (String line : contents) {
if (line.equals(HEADER_SEPARATOR)) {
break;
} else {
String[] parts = line.split("=",2);
if (parts.length == 2) {
if (parts[0].equalsIgnoreCase("date")) {
DateFormat df = new SimpleDateFormat(config.getString(Keys.DATE_FORMAT));
Date date = null;
try {
date = df.parse(parts[1]);
content.put(parts[0], date);
} catch (ParseException e) {
e.printStackTrace();
}
} else if (parts[0].equalsIgnoreCase("tags")) {
String[] tags = parts[1].split(",");
for( int i=0; i<tags.length; i++ )
tags[i]=tags[i].trim();
content.put(parts[0], tags);
} else if (parts[1].startsWith("{") && parts[1].endsWith("}")) {
// Json type
content.put(parts[0], JSONValue.parse(parts[1]));
} else {
content.put(parts[0], parts[1]);
}
}
}
}
}
/**
* Process the body of the file.
*
* @param contents Contents of file
* @param content
*/
private void processBody(List<String> contents, final Map<String, Object> content) {
StringBuilder body = new StringBuilder();
boolean inBody = false;
for (String line : contents) {
if (inBody) {
body.append(line).append("\n");
}
if (line.equals(HEADER_SEPARATOR)) {
inBody = true;
}
}
if (body.length() == 0) {
for (String line : contents) {
body.append(line).append("\n");
}
}
content.put("body", body.toString());
}
} |
package org.jboss.util;
import java.util.HashMap;
import java.util.Map;
/**
* Implementation of a Least Recently Used cache policy.
*
* @author <a href="mailto:simone.bordet@compaq.com">Simone Bordet</a>
* @version $Revision$
*/
@SuppressWarnings("unchecked")
public class LRUCachePolicy
implements CachePolicy
{
/**
* The map holding the cached objects
*/
protected Map m_map;
/**
* The linked list used to implement the LRU algorithm
*/
protected LRUList m_list;
/**
* The maximum capacity of this cache
*/
protected int m_maxCapacity;
/**
* The minimum capacity of this cache
*/
protected int m_minCapacity;
/**
* Creates a LRU cache policy object with zero cache capacity.
*
* @see #create
*/
public LRUCachePolicy()
{
}
/**
* Creates a LRU cache policy object with the specified minimum
* and maximum capacity.
* @param min
* @param max
*
* @see #create
*/
public LRUCachePolicy(int min, int max)
{
if (min < 2 || min > max) {throw new IllegalArgumentException("Illegal cache capacities");}
m_minCapacity = min;
m_maxCapacity = max;
}
/**
* Create map holding entries.
*
* @return the map
*/
protected Map createMap()
{
return new HashMap();
}
/**
* Initializes the cache, creating all required objects and initializing their
* values.
* @see #start
* @see #destroy
*/
public void create()
{
m_map = createMap();
m_list = createList();
m_list.m_maxCapacity = m_maxCapacity;
m_list.m_minCapacity = m_minCapacity;
m_list.m_capacity = m_maxCapacity;
}
/**
* Starts this cache that is now ready to be used.
* @see #create
* @see #stop
*/
public void start()
{
}
/**
* Stops this cache thus {@link #flush}ing all cached objects. <br>
* After this method is called, a call to {@link #start} will restart the cache.
* @see #start
* @see #destroy
*/
public void stop()
{
if (m_list != null)
{
flush();
}
}
/**
* Destroys the cache that is now unusable. <br>
* To have it working again it must be re-{@link #create}ed and
* re-{@link #start}ed.
*
* @see #create
*/
public void destroy()
{
if( m_map != null )
m_map.clear();
if( m_list != null )
m_list.clear();
}
public Object get(Object key)
{
if (key == null)
{
throw new IllegalArgumentException("Requesting an object using a null key");
}
LRUCacheEntry value = (LRUCacheEntry)m_map.get(key);
if (value != null)
{
m_list.promote(value);
return value.m_object;
}
else
{
cacheMiss();
return null;
}
}
public Object peek(Object key)
{
if (key == null)
{
throw new IllegalArgumentException("Requesting an object using a null key");
}
LRUCacheEntry value = (LRUCacheEntry)m_map.get(key);
if (value == null)
{
return null;
}
else
{
return value.m_object;
}
}
public void insert(Object key, Object o)
{
if (o == null) {throw new IllegalArgumentException("Cannot insert a null object in the cache");}
if (key == null) {throw new IllegalArgumentException("Cannot insert an object in the cache with null key");}
if (m_map.containsKey(key))
{
throw new IllegalStateException("Attempt to put in the cache an object that is already there");
}
m_list.demote();
LRUCacheEntry entry = createCacheEntry(key, o);
m_map.put(key, entry);
m_list.promote(entry);
}
public void remove(Object key)
{
if (key == null) {throw new IllegalArgumentException("Removing an object using a null key");}
Object value = m_map.remove(key);
if (value != null)
{
m_list.remove((LRUCacheEntry)value);
}
//else Do nothing, the object isn't in the cache list
}
public void flush()
{
LRUCacheEntry entry = null;
while ((entry = m_list.m_tail) != null)
{
ageOut(entry);
}
}
public int size() {
return m_list.m_count;
}
/**
* Factory method for the linked list used by this cache implementation.
* @return the lru list
*/
protected LRUList createList() {return new LRUList();}
/**
* Callback method called when the cache algorithm ages out of the cache
* the given entry. <br>
* The implementation here is removing the given entry from the cache.
* @param entry
*/
protected void ageOut(LRUCacheEntry entry)
{
remove(entry.m_key);
}
/**
* Callback method called when a cache miss happens.
*/
protected void cacheMiss()
{
}
/**
* Factory method for cache entries
* @param key
* @param value
* @return the entry
*/
protected LRUCacheEntry createCacheEntry(Object key, Object value)
{
return new LRUCacheEntry(key, value);
}
/**
* Double queued list used to store cache entries.
*/
public class LRUList
{
/** The maximum capacity of the cache list */
@SuppressWarnings("hiding")
public int m_maxCapacity;
/** The minimum capacity of the cache list */
@SuppressWarnings("hiding")
public int m_minCapacity;
/** The current capacity of the cache list */
public int m_capacity;
/** The number of cached objects */
public int m_count;
/** The head of the double linked list */
public LRUCacheEntry m_head;
/** The tail of the double linked list */
public LRUCacheEntry m_tail;
/** The cache misses happened */
public int m_cacheMiss;
/**
* Creates a new double queued list.
*/
protected LRUList()
{
m_head = null;
m_tail = null;
m_count = 0;
}
protected void promote(LRUCacheEntry entry)
{
if (entry == null) {throw new IllegalArgumentException("Trying to promote a null object");}
if (m_capacity < 1) {throw new IllegalStateException("Can't work with capacity < 1");}
entryPromotion(entry);
entry.m_time = System.currentTimeMillis();
if (entry.m_prev == null)
{
if (entry.m_next == null)
{
// entry is new or there is only the head
if (m_count == 0) // cache is empty
{
m_head = entry;
m_tail = entry;
++m_count;
entryAdded(entry);
}
else if (m_count == 1 && m_head == entry) {} // there is only the head and I want to promote it, do nothing
else if (m_count < m_capacity)
{
entry.m_prev = null;
entry.m_next = m_head;
m_head.m_prev = entry;
m_head = entry;
++m_count;
entryAdded(entry);
}
else if (m_count < m_maxCapacity)
{
entry.m_prev = null;
entry.m_next = m_head;
m_head.m_prev = entry;
m_head = entry;
++m_count;
int oldCapacity = m_capacity;
++m_capacity;
entryAdded(entry);
capacityChanged(oldCapacity);
}
else {throw new IllegalStateException("Attempt to put a new cache entry on a full cache");}
}
else {} // entry is the head, do nothing
}
else
{
if (entry.m_next == null) // entry is the tail
{
LRUCacheEntry beforeLast = entry.m_prev;
beforeLast.m_next = null;
entry.m_prev = null;
entry.m_next = m_head;
m_head.m_prev = entry;
m_head = entry;
m_tail = beforeLast;
}
else // entry is in the middle of the list
{
LRUCacheEntry previous = entry.m_prev;
previous.m_next = entry.m_next;
entry.m_next.m_prev = previous;
entry.m_prev = null;
entry.m_next = m_head;
m_head.m_prev = entry;
m_head = entry;
}
}
}
/**
* Demotes from the cache the least used entry. <br>
* If the cache is not full, does nothing.
* @see #promote
*/
protected void demote()
{
if (m_capacity < 1) {throw new IllegalStateException("Can't work with capacity < 1");}
if (m_count > m_maxCapacity) {throw new IllegalStateException("Cache list entries number (" + m_count + ") > than the maximum allowed (" + m_maxCapacity + ")");}
if (m_count == m_maxCapacity)
{
LRUCacheEntry entry = m_tail;
// the entry will be removed by ageOut
ageOut(entry);
}
else {} // cache is not full, do nothing
}
/**
* Removes from the cache list the specified entry.
* @param entry
*/
protected void remove(LRUCacheEntry entry)
{
if (entry == null) {throw new IllegalArgumentException("Cannot remove a null entry from the cache");}
if (m_count < 1) {throw new IllegalStateException("Trying to remove an entry from an empty cache");}
entry.m_key = entry.m_object = null;
if (m_count == 1)
{
m_head = m_tail = null;
}
else
{
if (entry.m_prev == null) // the head
{
m_head = entry.m_next;
m_head.m_prev = null;
entry.m_next = null;
}
else if (entry.m_next == null) // the tail
{
m_tail = entry.m_prev;
m_tail.m_next = null;
entry.m_prev = null;
}
else // in the middle
{
entry.m_next.m_prev = entry.m_prev;
entry.m_prev.m_next = entry.m_next;
entry.m_prev = null;
entry.m_next = null;
}
}
--m_count;
entryRemoved(entry);
}
/**
* Callback that signals that the given entry is just about to be added.
* @param entry
*/
protected void entryPromotion(LRUCacheEntry entry) {}
/**
* Callback that signals that the given entry has been added to the cache.
* @param entry
*/
protected void entryAdded(LRUCacheEntry entry) {}
/**
* Callback that signals that the given entry has been removed from the cache.
* @param entry
*/
protected void entryRemoved(LRUCacheEntry entry) {}
/**
* Callback that signals that the capacity of the cache is changed.
* @param oldCapacity the capacity before the change happened
*/
protected void capacityChanged(int oldCapacity) {}
protected void clear()
{
LRUCacheEntry entry = m_head;
m_head = null;
m_tail = null;
m_count = 0;
for (; entry != null; entry = entry.m_next)
entryRemoved(entry);
}
public String toString()
{
String s = Integer.toHexString(super.hashCode());
s += " size: " + m_count;
for (LRUCacheEntry entry = m_head; entry != null; entry = entry.m_next)
{
s += "\n" + entry;
}
return s;
}
}
/**
* Double linked cell used as entry in the cache list.
*/
public class LRUCacheEntry
{
/** Reference to the next cell in the list */
public LRUCacheEntry m_next;
/** Reference to the previous cell in the list */
public LRUCacheEntry m_prev;
/** The key used to retrieve the cached object */
public Object m_key;
/** The cached object */
public Object m_object;
/** The timestamp of the creation */
public long m_time;
/**
* Creates a new double linked cell, storing the object we
* want to cache and the key that is used to retrieve it.
* @param key
* @param object
*/
protected LRUCacheEntry(Object key, Object object)
{
m_key = key;
m_object = object;
m_next = null;
m_prev = null;
m_time = 0; // Set when inserted in the list.
}
public String toString()
{
return "key: " + m_key + ", object: " + ( m_object==null ? "null" : Integer.toHexString(m_object.hashCode())) + ", entry: " + Integer.toHexString(super.hashCode());
}
}
} |
package org.springframework.load;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import org.springframework.util.ResponseTimeMonitor;
import org.springframework.util.ResponseTimeMonitorImpl;
import org.springframework.util.StopWatch;
/**
* Convenient superclass that makes it very easy to implement Tests.
*
* Uses the Template Method design pattern. Concrete subclasses have
* only to implement the abstract runPass(i) method to execute each test.
*
* This class exposes bean properties controlling test execution.
*
* @author Rod Johnson
* @since February 9, 2001
*/
public abstract class AbstractTest implements Test {
// Instance variables
/** Used to calculate random delays if a subclass wants this behavior */
private static Random rand = new Random();
private long maxPause = -1L;
private int nbPasses;
private StopWatch runningTimer;
private StopWatch pauseTimer;
private StopWatch elapsedTimer;
/**
* List of failures encountered by this test so far
*/
private List testFailedExceptions;
/**
* Whether toString should generate a verbose format.
* This property is inherited from the managing TestSuite unless
* it's overridden as a bean property.
*/
private boolean longReports;
/** Number of tests completed so far */
private int completedTests;
/** Number of instances of this test. Use for weighting */
private int instances = 1;
/** Descriptive name of this test */
private String name;
/**
* Helper object used to capture performance information
*/
private ResponseTimeMonitorImpl responseTimeMonitorImpl = new ResponseTimeMonitorImpl();
/** Suite that manages this test */
private AbstractTestSuite suite;
// Constructor
/**
* Construct a new AbstractTest. The object must be further configured
* by its JavaBean properties and/or by inheritance of properties
* from the TestSuite it runs it. The setTestSuite() method must
* be invoked by the managing AbstractTestSuite.
*/
protected AbstractTest() {
testFailedExceptions = new LinkedList();
runningTimer = new StopWatch();
runningTimer.setKeepTaskList(false);
pauseTimer = new StopWatch();
pauseTimer.setKeepTaskList(false);
elapsedTimer = new StopWatch();
elapsedTimer.setKeepTaskList(false);
}
// Implementation of Test
/**
* Subclasses can override this to save a test
* fixture to run application-specific tests against.
* This implementation doesn't know anything about fixtures, so
* it always throws an exception.
* @param context application-specific object to test
*/
public void setFixture(Object context) {
throw new UnsupportedOperationException("AbstractTest.setFixture");
}
/**
* @return the test fixture used by this object.
* Subclasses that require test fixtures must override this method,
* which always throws UnsupportedOperationException
*/
public Object getFixture() {
throw new UnsupportedOperationException("AbstractTest.getFixture");
}
/**
* Set the number of instances of this Test. This enables weighting
* of tests.
*/
public void setInstances(int instances) {
this.instances = instances;
}
public int getInstances() {
return instances;
}
/**
* The TestSuite object that manages this test thread invokes this
* method. It is used to enable properties to be inherited from the
* test suite unless overriden by bean properties on this class.
*/
public void setTestSuite(AbstractTestSuite suite) {
this.suite = suite;
// Set defaults if not set via this class's bean properties
if (getPasses() == 0)
this.setPasses(suite.getPasses());
if (getMaxPause() < 0L)
this.setMaxPause(suite.getMaxPause());
this.setLongReports(suite.getLongReports());
}
public final void setName(String name) {
this.name = name;
}
public final void setLongReports(boolean longReports) {
this.longReports = longReports;
}
public final void setPasses(int nbPasses) {
this.nbPasses = nbPasses;
}
public final void setMaxPause(long maxPause) {
this.maxPause = maxPause;
}
public final long getMaxPause() {
return this.maxPause;
}
public final int getPasses() {
return nbPasses;
}
public final int getErrorCount() {
return testFailedExceptions.size();
}
public final String getName() {
return name;
}
public final int getTestsCompletedCount() {
return completedTests;
}
public final boolean isComplete() {
return getPasses() == getTestsCompletedCount();
}
/**
* @see org.springframework.load.TestStatus#getAverageResponseTime()
*/
public int getAverageResponseTime() {
return this.responseTimeMonitorImpl.getAverageResponseTimeMillis();
}
/**
* @see org.springframework.load.TestStatus#getTestsPerSecondCount()
*/
public final double getTestsPerSecondCount() {
double res = 0.0;
double totalTime = runningTimer.getTotalTime();
double testCompleted = (double) getTestsCompletedCount();
if (testCompleted == 0.0)
return 0.0;
if (totalTime != 0.0)
res = 1000.0 / (totalTime / testCompleted);
else {
// No time!!!!
//return testCompleted;
return Double.POSITIVE_INFINITY;
}
return res;
}
/**
* @see org.springframework.load.TestStatus#getTotalWorkingTime()
*/
public final long getTotalWorkingTime() {
return runningTimer.getTotalTime();
}
/**
* @see org.springframework.load.TestStatus#getElapsedTime()
*/
public final long getElapsedTime() {
return elapsedTimer.getTotalTime();
}
/**
* @see org.springframework.load.TestStatus#getTotalPauseTime()
*/
public final long getTotalPauseTime() {
return pauseTimer.getTotalTime();
}
public final TestFailedException[] getFailureExceptions() {
TestFailedException[] fails = new TestFailedException[testFailedExceptions.size()];
for (int i = 0; i < fails.length; i++)
fails[i] = (TestFailedException) testFailedExceptions.get(i);
return fails;
}
/**
* @see org.springframework.load.Test#reset()
*/
public void reset() {
elapsedTimer = new StopWatch("elapsed timer");
completedTests = 0;
runningTimer = new StopWatch("running timer");
pauseTimer = new StopWatch("pause timer");
testFailedExceptions.clear();
}
/**
* @return additional stats information.
*/
public ResponseTimeMonitor getTargetResponse() {
return responseTimeMonitorImpl;
}
/**
* Run all the tests in this thread
* @see java.lang.Runnable#run()
*/
public final void run() {
elapsedTimer.start(null);//"run");
for (int i = 0; i < getPasses(); i++) {
try {
pause();
runningTimer.start(null);//"run");
runPass(i);
}
catch (AbortTestException ex) {
// Terminate the for loop to end the work of this test thread
System.err.println("Abortion!: " + ex);
break;
}
catch (TestFailedException ex) {
// We don't need to wrap this
testFailedExceptions.add(ex);
onTestPassFailed(ex);
}
catch (Exception ex) {
// Wrap the uncaught exception in a new TestFailedException
TestFailedException tfe = new TestFailedException("Uncaught exception: " + ex.getMessage(), ex);
testFailedExceptions.add(tfe);
onTestPassFailed(ex);
}
finally {
++completedTests;
runningTimer.stop();
responseTimeMonitorImpl.recordResponseTime(runningTimer.getLastInterval());
}
} // for each test
elapsedTimer.stop();
} // run
/**
* @return diagnostic information about this Test.
* The verbosity of the format will depend on the value of the
* longReports bean property.
*/
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(getName() + "\t");
sb.append(getTestsCompletedCount() + "/" + getPasses());
sb.append("\terrs=" + getErrorCount());
sb.append("\t" + suite.getDecimalFormat().format(getTestsPerSecondCount()) + "hps");
sb.append("\tavg=" + responseTimeMonitorImpl.getAverageResponseTimeMillis() + "ms");
if (longReports) {
sb.append("\tworkt=" + getTotalWorkingTime());
sb.append("\telt=" + getElapsedTime());
sb.append("\best=" + responseTimeMonitorImpl.getBestResponseTimeMillis() + "ms");
sb.append("\tworst=" + responseTimeMonitorImpl.getWorstResponseTimeMillis() + "ms");
sb.append("\tpause=" + getTotalPauseTime());
}
if (isComplete() && this.longReports) {
sb.append("\tCOMPLETED\n");
sb.append(getErrorReport());
}
return sb.toString();
} // toString
/**
* @return an error report string
*/
public final String getErrorReport() {
String s = "";
TestFailedException[] fails = getFailureExceptions();
if (fails == null || fails.length == 0)
return "No errors\n";
else {
for (int i = 0; i < fails.length; i++) {
s += fails[i] + "\n";
}
}
return s;
}
/**
* Subclasses must implement this method
* @throws TestFailedException if the test failed
* @throws AbortTestException if the test run should abort
* @throws Exception if there's any other unspecified error.
* This will not cause the test run to abort.
* @param i index of test pass, indexed from 0
*/
protected abstract void runPass(int i) throws TestFailedException, AbortTestException, Exception;
/**
* For handling any exceptions thrown by a Test pass. Override as desired.
* This implementation does nothing.
* This method is invoked on test failures, whether caused by an uncaught exception
* or a TestAssertionFailure
*/
protected void onTestPassFailed(Exception ex) {
ex.printStackTrace();
}
// Implementation methods and convenience methods for subclasses
/**
* Pause for up to maxPause milliseconds
*/
private void pause() {
if (this.maxPause > 0L) {
try {
pauseTimer.start(null);//"pause");
long p = Math.abs(rand.nextLong() % this.maxPause);
Thread.sleep(p);
}
catch (InterruptedException ex) {
ex.printStackTrace();
}
finally {
pauseTimer.stop();
}
}
} // pause
/**
* Convenience method to simulate delay for between min and max ms
* @param min minimum number of milliseconds to delay
* @param max maximum number of milliseconds to delay
*/
public static void simulateDelay(long min, long max) {
if (max - min > 0L) {
try {
long p = Math.abs(min + rand.nextLong() % (max - min));
//System.out.println("delay for " + p + "ms");
Thread.sleep(p);
}
catch (InterruptedException ex) {
// Ignore it
}
}
} // simulateDelay
/**
* Convenience method for subclasses
* @param sz size of array to index
* @return a random array of list index from 0 up to sz-1
*/
public static int randomIndex(int sz) {
return Math.abs(rand.nextInt(sz));
}
} // class AbstractTest |
package org.lightmare.rest;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.model.Resource;
import org.lightmare.cache.MetaContainer;
import org.lightmare.rest.providers.JacksonFXmlFeature;
import org.lightmare.rest.providers.ObjectMapperProvider;
import org.lightmare.rest.providers.RestReloader;
import org.lightmare.rest.utils.RestUtils;
import org.lightmare.utils.ObjectUtils;
/**
* Dynamically manage REST resources, implementation of {@link ResourceConfig}
* class to add and remove {@link Resource}'s and reload at runtime
*
* @author levan
*
*/
public class RestConfig extends ResourceConfig {
private static RestConfig config;
// Collection of resources before registration
private Set<Resource> preResources;
// Reloader instance (implementation of ContainerLifecycleListener class)
private RestReloader reloader = RestReloader.get();
public RestConfig() {
super();
register(ObjectMapperProvider.class);
register(JacksonFXmlFeature.class);
synchronized (RestConfig.class) {
if (reloader == null) {
reloader = new RestReloader();
}
this.registerInstances(reloader);
if (ObjectUtils.notNull(config)) {
// Adds resources to pre-resources from existing cached
// configuration
this.addPreResources(config);
Map<String, Object> properties = config.getProperties();
if (ObjectUtils.available(properties)) {
addProperties(properties);
}
}
config = this;
}
}
public static RestConfig get() {
synchronized (RestConfig.class) {
return config;
}
}
private void clearResources() {
Set<Resource> resources = getResources();
if (ObjectUtils.available(resources)) {
getResources().clear();
}
}
/**
* Registers {@link Resource}s from passed {@link RestConfig} as
* {@link RestConfig#preResources} cache
*
* @param oldConfig
*/
public void registerAll(RestConfig oldConfig) {
clearResources();
Set<Resource> newResources;
newResources = new HashSet<Resource>();
if (ObjectUtils.notNull(oldConfig)) {
Set<Resource> olds = oldConfig.getResources();
if (ObjectUtils.available(olds)) {
newResources.addAll(olds);
}
}
registerResources(newResources);
}
/**
* Caches {@link Resource} created from passed {@link Class} for further
* registration
*
* @param resourceClass
* @param oldConfig
* @throws IOException
*/
public void registerClass(Class<?> resourceClass, RestConfig oldConfig)
throws IOException {
Resource.Builder builder = Resource.builder(resourceClass);
Resource preResource = builder.build();
Resource resource = RestUtils.defineHandler(preResource);
addPreResource(resource);
MetaContainer.putResource(resourceClass, resource);
}
public void unregister(Class<?> resourceClass, RestConfig oldConfig) {
Resource resource = MetaContainer.getResource(resourceClass);
removePreResource(resource);
MetaContainer.removeResource(resourceClass);
}
public void addPreResource(Resource resource) {
if (this.preResources == null || this.preResources.isEmpty()) {
this.preResources = new HashSet<Resource>();
}
this.preResources.add(resource);
}
public void removePreResource(Resource resource) {
if (ObjectUtils.available(this.preResources)) {
this.preResources.remove(resource);
}
}
public void addPreResources(Collection<Resource> preResources) {
if (ObjectUtils.available(preResources)) {
if (this.preResources == null || this.preResources.isEmpty()) {
this.preResources = new HashSet<Resource>();
}
this.preResources.addAll(preResources);
}
}
public void addPreResources(RestConfig oldConfig) {
if (ObjectUtils.notNull(oldConfig)) {
addPreResources(oldConfig.getResources());
addPreResources(oldConfig.preResources);
}
}
public void registerPreResources() {
if (ObjectUtils.available(this.preResources)) {
registerResources(preResources);
}
}
} |
package org.myrobotlab.service;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.commons.io.FilenameUtils;
import org.myrobotlab.document.Classification;
import org.myrobotlab.framework.Platform;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.Status;
import org.myrobotlab.framework.interfaces.Attachable;
import org.myrobotlab.framework.interfaces.ServiceInterface;
import org.myrobotlab.inmoov.LanguagePack;
import org.myrobotlab.inmoov.Utils;
import org.myrobotlab.inmoov.Vision;
import org.myrobotlab.jme3.InMoov3DApp;
import org.myrobotlab.kinematics.DHLinkType;
import org.myrobotlab.kinematics.GravityCenter;
import org.myrobotlab.kinematics.Point;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.openni.OpenNiData;
import org.myrobotlab.openni.Skeleton;
import org.myrobotlab.service.data.AudioData;
import org.myrobotlab.service.data.JoystickData;
import org.myrobotlab.service.data.Pin;
import org.myrobotlab.service.interfaces.IKJointAngleListener;
import org.myrobotlab.service.interfaces.JoystickListener;
import org.myrobotlab.service.interfaces.PinArrayControl;
import org.myrobotlab.service.interfaces.ServoControl;
import org.myrobotlab.service.interfaces.ServoController;
import org.myrobotlab.service.interfaces.ServoData;
import org.myrobotlab.service.interfaces.SpeechRecognizer;
import org.myrobotlab.service.interfaces.SpeechSynthesis;
import org.slf4j.Logger;
// FIXME - EVERYTHING .. ya EVERYTHING a local top level reference !
// TODO ALL PEERS NEED TO BE PRIVATE - ACCESS THROUGH GETTERS
// TODO ATTACH THINGS ...
// TODO implement generic bodypart to remove lot of things from here
public class InMoov extends Service implements IKJointAngleListener, JoystickListener {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(InMoov.class);
public InMoov(String n) {
super(n);
}
// start variables declaration
// TODO: inventory all of those vars..
private final String GESTURES_DIRECTORY = "gestures";
public String CALIBRATION_FILE = "calibration.py";
transient HashMap<String, ServoController> arduinos = new HashMap<String, ServoController>();
transient private HashMap<String, InMoovArm> arms = new HashMap<String, InMoovArm>();
transient private HashMap<String, InMoovHand> hands = new HashMap<String, InMoovHand>();
transient public final static String LEFT = "left";
transient public final static String RIGHT = "right";
boolean copyGesture = false;
public double openNiShouldersOffset = -50.0;
public boolean openNiLeftShoulderInverted = true;
public boolean openNiRightShoulderInverted = true;
boolean firstSkeleton = true;
boolean saveSkeletonFrame = false;
boolean speakErrors = false;
String lastInMoovError = "";
int maxInactivityTimeSeconds = 120;
public static int attachPauseMs = 100;
public Set<String> gesturesList = new TreeSet<String>();
private String lastGestureExecuted = "";
public static boolean RobotCanMoveHeadRandom = true;
public static boolean RobotCanMoveEyesRandom = true;
public static boolean RobotCanMoveBodyRandom = true;
public static boolean RobotCanMoveRandom = true;
public static boolean RobotIsSleeping = false;
public static boolean RobotIsStarted = false;
public Integer pirPin = null;
Long startSleep = null;
Long lastPIRActivityTime = null;
boolean useHeadForTracking = true;
boolean useEyesForTracking = false;
transient InMoov3DApp vinMoovApp;
transient LanguagePack languagePack = new LanguagePack();
private PinArrayControl pirArduino;
public static LinkedHashMap<String, String> languages = new LinkedHashMap<String, String>();
public static List<String> languagesIndex = new ArrayList<String>();
String language;
boolean mute;
static String speechService = "MarySpeech";
static String speechRecognizer = "WebkitSpeechRecognition";
// end variables
// services reservations & related extra class for custom methods & configs
transient public OpenCV opencv;
public Vision vision;
transient public SpeechRecognizer ear;
transient public SpeechSynthesis mouth;
transient public Tracking eyesTracking;
transient public Tracking headTracking;
transient public OpenNi openni;
transient public MouthControl mouthControl;
transient public Python python;
transient public InMoovHead head;
transient public InMoovTorso torso;
transient public InMoovArm leftArm;
transient public InMoovHand leftHand;
transient public InMoovArm rightArm;
transient public InMoovHand rightHand;
transient public InMoovEyelids eyelids;
transient public Pid pid;
transient public Relay LeftRelay1;
transient public Relay RightRelay1;
transient public NeoPixel neopixel;
transient public Arduino neopixelArduino;
transient public UltrasonicSensor ultrasonicSensor;
transient public ProgramAB chatBot;
transient private IntegratedMovement integratedMovement;
transient private InverseKinematics3D ik3d;
transient private JMonkeyEngine jme; // TODO - should probably be a Simulator
// interface
transient private Joystick joystick;
// end services reservations
// attach engine, more here !! later ..
public void attach(Attachable attachable) {
// opencv
if (attachable instanceof OpenCV) {
opencv = (OpenCV) attachable;
subscribe(opencv.getName(), "publishClassification");
} else if (attachable instanceof SpeechSynthesis) {
mouth = (SpeechSynthesis) attachable;
if (ear != null) {
ear.addMouth(mouth);
}
} else if (attachable instanceof SpeechRecognizer) {
ear = (SpeechRecognizer) attachable;
if (mouth != null) {
ear.addMouth(mouth);
}
} else if (attachable instanceof ProgramAB) {
chatBot = (ProgramAB) attachable;
}
}
// end attach
// VISION public methods
public void cameraOff() {
if (opencv != null) {
opencv.stopCapture();
opencv.disableAll();
}
// temporary fix overexpand windows
SwingGui gui = (SwingGui) Runtime.getService("gui");
if (gui != null) {
gui.maximize();
}
}
public void cameraOn() {
if (opencv == null) {
startOpenCV();
}
opencv.capture();
vision.enablePreFilters();
}
public boolean isCameraOn() {
if (opencv != null) {
if (opencv.isCapturing()) {
return true;
}
}
return false;
}
public void stopTracking() {
if (eyesTracking != null) {
eyesTracking.stopTracking();
}
if (headTracking != null) {
headTracking.stopTracking();
}
}
public void clearTrackingPoints() {
if (headTracking == null) {
error("attach head before tracking");
} else {
headTracking.clearTrackingPoints();
}
}
@Deprecated
public void startHeadTracking(String port, Integer rothead, Integer neck) {
log.warn("Please use ServoControl : startHeadTracking(YourServoRothead,YourServoNeck), I will try to do it for you...");
startHeadTracking();
}
public void startHeadTracking() {
startHeadTracking(head.rothead, head.neck);
}
public void startHeadTracking(ServoControl rothead, ServoControl neck) {
if (opencv == null) {
log.warn("Tracking needs Opencv activated, I will try to lauch it. It is better if you DIY");
startOpenCV();
}
if (headTracking == null) {
speakBlocking(languagePack.get("TRACKINGSTARTED"));
headTracking = (Tracking) this.startPeer("headTracking");
headTracking.connect(this.opencv, rothead, neck);
}
}
@Deprecated
public void startEyesTracking(String port, Integer eyeX, Integer eyeY) {
log.warn("Please use ServoControl : startEyesTracking(ServoX,ServoY), I will try to do it for you...");
startEyesTracking();
}
public void startEyesTracking() {
startEyesTracking(head.eyeX, head.eyeY);
}
public void startEyesTracking(ServoControl eyeX, ServoControl eyeY) {
if (opencv == null) {
log.warn("Tracking needs Opencv activated, I will try to lauch it. It is better if you DIY");
startOpenCV();
}
speakBlocking(languagePack.get("TRACKINGSTARTED"));
eyesTracking = (Tracking) this.startPeer("eyesTracking");
eyesTracking.connect(this.opencv, head.eyeX, head.eyeY);
}
public void trackHumans() {
// FIXME can't have 2 PID for tracking
// if (eyesTracking != null) {
// eyesTracking.faceDetect();
vision.enablePreFilters();
startHeadTracking();
if (headTracking != null) {
headTracking.faceDetect();
}
}
// FIXME check / test lk tracking..
public void trackPoint() {
vision.enablePreFilters();
startHeadTracking();
if (headTracking != null) {
headTracking.startLKTracking();
headTracking.trackPoint();
}
}
public void onClassification(TreeMap<String, List<Classification>> classifications) {
vision.yoloInventory(classifications);
}
// END VISION methods
// OPENNI methods
@Deprecated
public boolean RobotIsOpenCvCapturing() {
if (opencv != null)
return opencv.isCapturing();
return false;
}
// TODO:change -> isOpenNiCapturing
@Deprecated
public boolean RobotIsOpenNiCapturing() {
if (openni != null) {
if (openni.capturing) {
return true;
}
}
return false;
}
public void onOpenNIData(OpenNiData data) {
if (data != null) {
Skeleton skeleton = data.skeleton;
if (firstSkeleton) {
speakBlocking("i see you");
firstSkeleton = false;
}
if (copyGesture) {
if (leftArm != null) {
if (!Double.isNaN(skeleton.leftElbow.getAngleXY())) {
if (skeleton.leftElbow.getAngleXY() >= 0) {
leftArm.bicep.moveTo((double)skeleton.leftElbow.getAngleXY());
}
}
if (!Double.isNaN(skeleton.leftShoulder.getAngleXY())) {
if (skeleton.leftShoulder.getAngleXY() >= 0) {
leftArm.omoplate.moveTo((double)skeleton.leftShoulder.getAngleXY());
}
}
if (!Double.isNaN(skeleton.leftShoulder.getAngleYZ())) {
if (skeleton.leftShoulder.getAngleYZ() + openNiShouldersOffset >= 0) {
leftArm.shoulder.moveTo((double)skeleton.leftShoulder.getAngleYZ() - 50);
}
}
}
if (rightArm != null) {
if (!Double.isNaN(skeleton.rightElbow.getAngleXY())) {
if (skeleton.rightElbow.getAngleXY() >= 0) {
rightArm.bicep.moveTo((double)skeleton.rightElbow.getAngleXY());
}
}
if (!Double.isNaN(skeleton.rightShoulder.getAngleXY())) {
if (skeleton.rightShoulder.getAngleXY() >= 0) {
rightArm.omoplate.moveTo((double)skeleton.rightShoulder.getAngleXY());
}
}
if (!Double.isNaN(skeleton.rightShoulder.getAngleYZ())) {
if (skeleton.rightShoulder.getAngleYZ() + openNiShouldersOffset >= 0) {
rightArm.shoulder.moveTo((double)skeleton.rightShoulder.getAngleYZ() - 50);
}
}
}
}
}
// TODO - route data appropriately
// rgb & depth image to OpenCV
// servos & depth image to gui (entire InMoov + references to servos)
}
// END OPENNI methods
// START GESTURES related methods
public void loadGestures() {
loadGestures(GESTURES_DIRECTORY);
}
/**
* This method will try to launch a python command with error handling
*/
public String execGesture(String gesture) {
lastGestureExecuted = gesture;
if (python == null) {
log.warn("execGesture : No jython engine...");
return null;
}
subscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus");
startedGesture(lastGestureExecuted);
return python.evalAndWait(gesture);
}
public void onGestureStatus(Status status) {
if (!status.equals(Status.success()) && !status.equals(Status.warn("Python process killed !"))) {
error("I cannot execute %s, please check logs", lastGestureExecuted);
}
finishedGesture(lastGestureExecuted);
unsubscribe(python.getName(), "publishStatus", this.getName(), "onGestureStatus");
}
/**
* This blocking method will look at all of the .py files in a directory. One
* by one it will load the files into the python interpreter. A gesture python
* file should contain 1 method definition that is the same as the filename.
*
* @param directory
* - the directory that contains the gesture python files.
*/
public boolean loadGestures(String directory) {
// iterate over each of the python files in the directory
// and load them into the python interpreter.
String extension = "py";
Integer totalLoaded = 0;
Integer totalError = 0;
File dir = Utils.makeDirectory(directory);
if (dir.exists()) {
for (File f : dir.listFiles()) {
if (FilenameUtils.getExtension(f.getAbsolutePath()).equalsIgnoreCase(extension)) {
if (Utils.loadFile(f.getAbsolutePath()) == true) {
totalLoaded += 1;
gesturesList.add(f.getName());
} else {
totalError += 1;
}
} else {
log.warn("{} is not a {} file", f.getAbsolutePath(), extension);
}
}
}
info("%s Gestures loaded, %s Gestures with error", totalLoaded, totalError);
if (totalError > 0) {
speakAlert(languagePack.get("GESTURE_ERROR"));
return false;
}
return true;
}
public void stopGesture() {
Python p = (Python) Runtime.getService("python");
p.stop();
}
public String captureGesture() {
return captureGesture(null);
}
public String captureGesture(String gestureName) {
StringBuffer script = new StringBuffer();
Date date = new Date();
String indentSpace = "";
script.append("# - " + date + " - Captured gesture :\n");
if (gestureName != null) {
indentSpace = " ";
script.append(String.format("def %s():\n", gestureName));
}
if (head != null) {
script.append(indentSpace);
script.append(head.getScript(getName()));
}
if (leftArm != null) {
script.append(indentSpace);
script.append(leftArm.getScript(getName()));
}
if (rightArm != null) {
script.append(indentSpace);
script.append(rightArm.getScript(getName()));
}
if (leftHand != null) {
script.append(indentSpace);
script.append(leftHand.getScript(getName()));
}
if (rightHand != null) {
script.append(indentSpace);
script.append(rightHand.getScript(getName()));
}
if (torso != null) {
script.append(indentSpace);
script.append(torso.getScript(getName()));
}
if (eyelids != null) {
script.append(indentSpace);
script.append(eyelids.getScript(getName()));
}
send("python", "appendScript", script.toString());
return script.toString();
}
public boolean copyGesture(boolean b) throws Exception {
log.info("copyGesture {}", b);
if (b) {
if (openni == null) {
openni = startOpenNI();
}
speakBlocking("copying gestures");
openni.startUserTracking();
} else {
speakBlocking("stop copying gestures");
if (openni != null) {
openni.stopCapture();
firstSkeleton = true;
}
}
copyGesture = b;
return b;
}
public void savePose(String poseName) {
// TODO: consider a prefix for the pose name?
captureGesture(poseName);
}
public void saveGesture(String gestureName, String directory) {
// TODO: consider the gestures directory as a property on the inmoov
String gestureMethod = mapGestureNameToPythonMethod(gestureName);
String gestureFilename = directory + File.separator + gestureMethod + ".py";
File gestureFile = new File(gestureFilename);
if (gestureFile.exists()) {
log.warn("Gesture file {} already exists.. not overwiting it.", gestureFilename);
return;
}
FileWriter gestureWriter = null;
try {
gestureWriter = new FileWriter(gestureFile);
// print the first line of the python file
gestureWriter.write("def " + gestureMethod + "():\n");
// now for each servo, we should write out the approperiate moveTo
// statement
// TODO: consider doing this only for the inmoov services.. but for now..
// i think
// we want all servos that are currently in the system?
for (ServiceInterface service : Runtime.getServices()) {
if (ServoControl.class.isAssignableFrom(service.getClass())) {
double pos = ((ServoControl) service).getPos();
gestureWriter.write(" " + service.getName() + ".moveTo(" + pos + ")\n");
}
}
gestureWriter.write("\n");
gestureWriter.close();
} catch (IOException e) {
log.warn("Error writing gestures file {}", gestureFilename);
e.printStackTrace();
return;
}
// TODO: consider writing out cooresponding AIML?
}
private String mapGestureNameToPythonMethod(String gestureName) {
// TODO: some fancier mapping?
String methodName = gestureName.replaceAll(" ", "");
return methodName;
}
public void saveGesture(String gestureName) {
// TODO: allow a user to save a gesture to the gestures directory
saveGesture(gestureName, GESTURES_DIRECTORY);
}
// waiting controable threaded gestures we warn user
boolean gestureAlreadyStarted = false;
public void startedGesture() {
startedGesture("unknown");
}
public void startedGesture(String nameOfGesture) {
if (gestureAlreadyStarted) {
warn("Warning 1 gesture already running, this can break spacetime and lot of things");
} else {
log.info("Starting gesture : {}", nameOfGesture);
gestureAlreadyStarted = true;
RobotCanMoveRandom = false;
}
}
public void finishedGesture() {
finishedGesture("unknown");
}
public void finishedGesture(String nameOfGesture) {
if (gestureAlreadyStarted) {
waitTargetPos();
RobotCanMoveRandom = true;
gestureAlreadyStarted = false;
log.info("gesture : {} finished...", nameOfGesture);
}
}
// END GESTURES
// SKELETON RELATED METHODS
public void enable() {
if (head != null) {
head.enable();
}
if (rightHand != null) {
rightHand.enable();
}
if (leftHand != null) {
leftHand.enable();
}
if (rightArm != null) {
rightArm.enable();
}
if (leftArm != null) {
leftArm.enable();
}
if (torso != null) {
torso.enable();
}
if (eyelids != null) {
eyelids.enable();
}
}
public void disable() {
if (head != null) {
head.disable();
}
if (rightHand != null) {
rightHand.disable();
}
if (leftHand != null) {
leftHand.disable();
}
if (rightArm != null) {
rightArm.disable();
}
if (leftArm != null) {
leftArm.disable();
}
if (torso != null) {
torso.disable();
}
if (eyelids != null) {
eyelids.disable();
}
}
public void fullSpeed() {
if (head != null) {
head.setVelocity(-1.0, -1.0, -1.0, -1.0, -1.0, -1.0);
}
if (rightHand != null) {
rightHand.setVelocity(-1.0, -1.0, -1.0, -1.0, -1.0, -1.0);
}
if (leftHand != null) {
leftHand.setVelocity(-1.0, -1.0, -1.0, -1.0, -1.0, -1.0);
}
if (rightArm != null) {
rightArm.setVelocity(-1.0, -1.0, -1.0, -1.0);
}
if (leftArm != null) {
leftArm.setVelocity(-1.0, -1.0, -1.0, -1.0);
}
if (torso != null) {
torso.setVelocity(-1.0, -1.0, -1.0);
}
if (eyelids != null) {
eyelids.setVelocity(-1.0, -1.0);
}
}
public void halfSpeed() {
if (head != null) {
head.setVelocity(25.0, 25.0, 25.0, 25.0, -1.0, 25.0);
}
if (rightHand != null) {
rightHand.setVelocity(30.0, 30.0, 30.0, 30.0, 30.0, 30.0);
}
if (leftHand != null) {
leftHand.setVelocity(30.0, 30.0, 30.0, 30.0, 30.0, 30.0);
}
if (rightArm != null) {
rightArm.setVelocity(25.0, 25.0, 25.0, 25.0);
}
if (leftArm != null) {
leftArm.setVelocity(25.0, 25.0, 25.0, 25.0);
}
if (torso != null) {
torso.setVelocity(20.0, 20.0, 20.0);
}
if (eyelids != null) {
eyelids.setVelocity(30.0, 30.0);
}
}
public boolean isAttached() {
boolean attached = false;
if (leftHand != null) {
attached |= leftHand.isAttached();
}
if (leftArm != null) {
attached |= leftArm.isAttached();
}
if (rightHand != null) {
attached |= rightHand.isAttached();
}
if (rightArm != null) {
attached |= rightArm.isAttached();
}
if (head != null) {
attached |= head.isAttached();
}
if (torso != null) {
attached |= torso.isAttached();
}
if (eyelids != null) {
attached |= eyelids.isAttached();
}
return attached;
}
public void moveArm(String which, double bicep, double rotate, double shoulder, double omoplate) {
if (!arms.containsKey(which)) {
error("setArmSpeed %s does not exist", which);
} else {
arms.get(which).moveTo(bicep, rotate, shoulder, omoplate);
}
}
public void moveEyes(double eyeX, double eyeY) {
if (head != null) {
head.moveTo(null, null, eyeX, eyeY, null, null);
} else {
log.error("moveEyes - I have a null head");
}
}
public void moveHand(String which, double thumb, double index, double majeure, double ringFinger, double pinky) {
moveHand(which, thumb, index, majeure, ringFinger, pinky, null);
}
public void moveHand(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
if (!hands.containsKey(which)) {
error("moveHand %s does not exist", which);
} else {
hands.get(which).moveTo(thumb, index, majeure, ringFinger, pinky, wrist);
}
}
public void moveHead(double neck, double rothead) {
moveHead(neck, rothead, null);
}
public void moveHead(Double neck, Double rothead, Double rollNeck) {
moveHead(neck, rothead, null, null, null, rollNeck);
}
public void moveHead(double neck, double rothead, double eyeX, double eyeY, double jaw) {
moveHead(neck, rothead, eyeX, eyeY, jaw, null);
}
public void moveHead(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) {
if (head != null) {
head.moveTo(neck, rothead, eyeX, eyeY, jaw, rollNeck);
} else {
log.error("I have a null head");
}
}
public void moveTorso(double topStom, double midStom, double lowStom) {
if (torso != null) {
torso.moveTo(topStom, midStom, lowStom);
} else {
log.error("moveTorso - I have a null torso");
}
}
public void moveTorsoBlocking(double topStom, double midStom, double lowStom) {
if (torso != null) {
torso.moveToBlocking(topStom, midStom, lowStom);
} else {
log.error("moveTorsoBlocking - I have a null torso");
}
}
public void moveEyelids(double eyelidleft, double eyelidright) {
if (eyelids != null) {
eyelids.moveTo(eyelidleft, eyelidright);
} else {
log.error("moveEyelids - I have a null Eyelids");
}
}
public void moveHeadBlocking(double neck, double rothead) {
moveHeadBlocking(neck, rothead, null);
}
public void moveHeadBlocking(double neck, double rothead, Double rollNeck) {
moveHeadBlocking(neck, rothead, null, null, null, rollNeck);
}
public void moveHeadBlocking(double neck, double rothead, Double eyeX, Double eyeY, Double jaw) {
moveHeadBlocking(neck, rothead, eyeX, eyeY, jaw, null);
}
public void moveHeadBlocking(Double neck, Double rothead, Double eyeX, Double eyeY, Double jaw, Double rollNeck) {
if (head != null) {
head.moveToBlocking(neck, rothead, eyeX, eyeY, jaw, rollNeck);
} else {
log.error("I have a null head");
}
}
public void waitTargetPos() {
if (head != null)
head.waitTargetPos();
if (eyelids != null)
eyelids.waitTargetPos();
if (leftArm != null)
leftArm.waitTargetPos();
if (rightArm != null)
rightArm.waitTargetPos();
if (leftHand != null)
leftHand.waitTargetPos();
if (rightHand != null)
rightHand.waitTargetPos();
if (torso != null)
torso.waitTargetPos();
}
public void rest() {
log.info("InMoov Native Rest Gesture Called");
if (head != null) {
head.rest();
}
if (rightHand != null) {
rightHand.rest();
}
if (leftHand != null) {
leftHand.rest();
}
if (rightArm != null) {
rightArm.rest();
}
if (leftArm != null) {
leftArm.rest();
}
if (torso != null) {
torso.rest();
}
if (eyelids != null) {
eyelids.rest();
}
}
@Deprecated
public void setArmSpeed(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) {
if (!arms.containsKey(which)) {
error("setArmSpeed %s does not exist", which);
} else {
arms.get(which).setSpeed(bicep, rotate, shoulder, omoplate);
}
}
public void setArmVelocity(String which, Double bicep, Double rotate, Double shoulder, Double omoplate) {
if (!arms.containsKey(which)) {
error("setArmVelocity %s does not exist", which);
} else {
arms.get(which).setVelocity(bicep, rotate, shoulder, omoplate);
}
}
@Deprecated
public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) {
setHandSpeed(which, thumb, index, majeure, ringFinger, pinky, null);
}
public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky) {
setHandVelocity(which, thumb, index, majeure, ringFinger, pinky, null);
}
@Deprecated
public void setHandSpeed(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
if (!hands.containsKey(which)) {
error("setHandSpeed %s does not exist", which);
} else {
hands.get(which).setSpeed(thumb, index, majeure, ringFinger, pinky, wrist);
}
}
public void setHandVelocity(String which, Double thumb, Double index, Double majeure, Double ringFinger, Double pinky, Double wrist) {
if (!hands.containsKey(which)) {
error("setHandSpeed %s does not exist", which);
} else {
hands.get(which).setVelocity(thumb, index, majeure, ringFinger, pinky, wrist);
}
}
@Deprecated
public void setHeadSpeed(Double rothead, Double neck) {
setHeadSpeed(rothead, neck, null, null, null);
}
public void setHeadVelocity(Double rothead, Double neck) {
setHeadVelocity(rothead, neck, null, null, null, null);
}
public void setHeadVelocity(Double rothead, Double neck, Double rollNeck) {
setHeadVelocity(rothead, neck, null, null, null, rollNeck);
}
public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) {
setHeadVelocity(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, null);
}
@Deprecated
public void setHeadSpeed(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed) {
if (head != null) {
head.setSpeed(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed);
} else {
log.warn("setHeadSpeed - I have no head");
}
}
@Deprecated
public void setHeadVelocity(Double rothead, Double neck, Double eyeXSpeed, Double eyeYSpeed, Double jawSpeed, Double rollNeckSpeed) {
if (head != null) {
head.setVelocity(rothead, neck, eyeXSpeed, eyeYSpeed, jawSpeed, rollNeckSpeed);
} else {
log.warn("setHeadVelocity - I have no head");
}
}
@Deprecated
public void setTorsoSpeed(Double topStom, Double midStom, Double lowStom) {
if (torso != null) {
torso.setSpeed(topStom, midStom, lowStom);
} else {
log.warn("setTorsoSpeed - I have no torso");
}
}
public void setTorsoVelocity(Double topStom, Double midStom, Double lowStom) {
if (torso != null) {
torso.setVelocity(topStom, midStom, lowStom);
} else {
log.warn("setTorsoVelocity - I have no torso");
}
}
public void setEyelidsVelocity(Double eyelidleft, Double eyelidright) {
if (eyelids != null) {
eyelids.setVelocity(eyelidleft, eyelidright);
} else {
log.warn("setEyelidsVelocity - I have no eyelids");
}
}
public InMoovArm startArm(String side, String port, String type) throws Exception {
// TODO rework this...
if (type == "left") {
speakBlocking(languagePack.get("STARTINGLEFTARM") + " " + port);
} else {
speakBlocking(languagePack.get("STARTINGRIGHTARM") + " " + port);
}
InMoovArm arm = (InMoovArm) startPeer(String.format("%sArm", side));
arms.put(side, arm);
arm.setSide(side);// FIXME WHO USES SIDE - THIS SHOULD BE NAME !!!
if (type == null) {
type = Arduino.BOARD_TYPE_MEGA;
}
// arm.arduino.setBoard(type); FIXME - this is wrong setting to Mega ...
// what if its a USB or I2C ???
arm.connect(port); // FIXME are all ServoControllers "connectable" ?
arduinos.put(port, arm.controller);
return arm;
}
public InMoovHand startHand(String side, String port, String type) throws Exception {
// TODO rework this...
if (type == "left") {
speakBlocking(languagePack.get("STARTINGLEFTHAND") + " " + port);
} else {
speakBlocking(languagePack.get("STARTINGRIGHTHAND") + " " + port);
}
InMoovHand hand = (InMoovHand) startPeer(String.format("%sHand", side));
hand.setSide(side);
hands.put(side, hand);
// FIXME - this is wrong ! its configuratin of an Arduino, (we may not have
// an Arduino !!!)
if (type == null) {
type = Arduino.BOARD_TYPE_MEGA;
}
// hand.arduino.setBoard(type);
hand.connect(port);
arduinos.put(port, hand.controller);
return hand;
}
public InMoovHead startHead(String port) throws Exception {
return startHead(port, null, 12, 13, 22, 24, 26, 30);
}
public InMoovHead startHead(String port, String type) throws Exception {
return startHead(port, type, 12, 13, 22, 24, 26, 30);
}
public InMoovHead startHead(String port, Integer headYPin, Integer headXPin, Integer eyeXPin, Integer eyeYPin, Integer jawPin, Integer rollNeckPin) throws Exception {
return startHead(port, null, headYPin, headXPin, eyeXPin, eyeYPin, jawPin, rollNeckPin);
}
public InMoovHead startHead(String port, String type, Integer headYPin, Integer headXPin, Integer eyeXPin, Integer eyeYPin, Integer jawPin, Integer rollNeckPin)
throws Exception {
// log.warn(InMoov.buildDNA(myKey, serviceClass))
speakBlocking(languagePack.get("STARTINGHEAD") + " " + port);
head = (InMoovHead) startPeer("head");
if (type == null) {
type = Arduino.BOARD_TYPE_MEGA;
}
// FIXME - !!! => cannot do this "here" ??? head.arduino.setBoard(type);
head.connect(port, headYPin, headXPin, eyeXPin, eyeYPin, jawPin, rollNeckPin);
arduinos.put(port, head.controller);
return head;
}
public void setAutoDisable(Boolean param) {
if (head != null) {
head.setAutoDisable(param);
}
if (rightArm != null) {
rightArm.setAutoDisable(param);
}
if (leftArm != null) {
leftArm.setAutoDisable(param);
}
if (leftHand != null) {
leftHand.setAutoDisable(param);
}
if (rightHand != null) {
leftHand.setAutoDisable(param);
}
if (torso != null) {
torso.setAutoDisable(param);
}
if (eyelids != null) {
eyelids.setAutoDisable(param);
}
}
public InMoovArm startLeftArm(String port) throws Exception {
return startLeftArm(port, null);
}
public InMoovArm startLeftArm(String port, String type) throws Exception {
leftArm = startArm(LEFT, port, type);
return leftArm;
}
public InMoovHand startLeftHand(String port) throws Exception {
return startLeftHand(port, null);
}
public InMoovHand startLeftHand(String port, String type) throws Exception {
leftHand = startHand(LEFT, port, type);
return leftHand;
}
public InMoovArm startRightArm(String port) throws Exception {
return startRightArm(port, null);
}
public InMoovArm startRightArm(String port, String type) throws Exception {
if (rightArm != null) {
info("right arm already started");
return rightArm;
}
rightArm = startArm(RIGHT, port, type);
return rightArm;
}
public InMoovHand startRightHand(String port) throws Exception {
return startRightHand(port, null);
}
public InMoovHand startRightHand(String port, String type) throws Exception {
rightHand = startHand(RIGHT, port, type);
return rightHand;
}
/*
* New startEyelids attach method ( for testing );
*/
public InMoovEyelids startEyelids(ServoController controller, Integer eyeLidLeftPin, Integer eyeLidRightPin) throws Exception {
eyelids = (InMoovEyelids) startPeer("eyelids");
eyelids.attach(controller, eyeLidLeftPin, eyeLidRightPin);
return eyelids;
}
// END SKELETON RELATED METHODS
// GENERAL METHODS / TO SORT
public void beginCheckingOnInactivity() {
beginCheckingOnInactivity(maxInactivityTimeSeconds);
}
public void beginCheckingOnInactivity(int maxInactivityTimeSeconds) {
this.maxInactivityTimeSeconds = maxInactivityTimeSeconds;
// speakBlocking("power down after %s seconds inactivity is on",
// this.maxInactivityTimeSeconds);
log.info("power down after %s seconds inactivity is on", this.maxInactivityTimeSeconds);
addTask("checkInactivity", 5 * 1000, 0, "checkInactivity");
}
public long checkInactivity() {
// speakBlocking("checking");
long lastActivityTime = getLastActivityTime();
long now = System.currentTimeMillis();
long inactivitySeconds = (now - lastActivityTime) / 1000;
if (inactivitySeconds > maxInactivityTimeSeconds && isAttached()) {
// speakBlocking("%d seconds have passed without activity",
// inactivitySeconds);
powerDown();
} else {
// speakBlocking("%d seconds have passed without activity",
// inactivitySeconds);
info("checking checkInactivity - %d seconds have passed without activity", inactivitySeconds);
}
return lastActivityTime;
}
String getBoardType(String side, String type) {
if (type != null) {
return type;
}
if (RIGHT.equals(side)) {
return Arduino.BOARD_TYPE_MEGA;
}
return Arduino.BOARD_TYPE_MEGA;
}
/**
* finds most recent activity
*
* @return the timestamp of the last activity time.
*/
public long getLastActivityTime() {
long lastActivityTime = 0;
if (leftHand != null) {
lastActivityTime = Math.max(lastActivityTime, leftHand.getLastActivityTime());
}
if (leftArm != null) {
lastActivityTime = Math.max(lastActivityTime, leftArm.getLastActivityTime());
}
if (rightHand != null) {
lastActivityTime = Math.max(lastActivityTime, rightHand.getLastActivityTime());
}
if (rightArm != null) {
lastActivityTime = Math.max(lastActivityTime, rightArm.getLastActivityTime());
}
if (head != null) {
lastActivityTime = Math.max(lastActivityTime, head.getLastActivityTime());
}
if (torso != null) {
lastActivityTime = Math.max(lastActivityTime, torso.getLastActivityTime());
}
if (eyelids != null) {
lastActivityTime = Math.max(lastActivityTime, eyelids.getLastActivityTime());
}
if (lastPIRActivityTime != null) {
lastActivityTime = Math.max(lastActivityTime, lastPIRActivityTime);
}
if (lastActivityTime == 0) {
error("invalid activity time - anything connected?");
lastActivityTime = System.currentTimeMillis();
}
return lastActivityTime;
}
public Python getPython() {
try {
if (python == null) {
python = (Python) startPeer("python");
}
} catch (Exception e) {
error(e);
}
return python;
}
public boolean isMute() {
return mute;
}
// TODO FIX/CHECK this, migrate from python land
public void powerDown() {
rest();
purgeTasks();
disable();
if (ear != null) {
ear.lockOutAllGrammarExcept("power up");
}
startSleep = System.currentTimeMillis();
python.execMethod("power_down");
}
// TODO FIX/CHECK this, migrate from python land
public void powerUp() {
startSleep = null;
enable();
rest();
if (ear != null) {
ear.clearLock();
}
beginCheckingOnInactivity();
python.execMethod("power_up");
}
// TODO FIX/CHECK this, migrate from python land
public void publishPin(Pin pin) {
log.info("{} - {}", pin.pin, pin.value);
if (pin.value == 1) {
lastPIRActivityTime = System.currentTimeMillis();
}
// if its PIR & PIR is active & was sleeping - then wake up !
if (pirPin == pin.pin && startSleep != null && pin.value == 1) {
// attach(); // good morning / evening / night... asleep for % hours
powerUp();
// Calendar now = Calendar.getInstance();
/*
* FIXME - make a getSalutation String salutation = "hello "; if
* (now.get(Calendar.HOUR_OF_DAY) < 12) { salutation = "good morning "; }
* else if (now.get(Calendar.HOUR_OF_DAY) < 16) { salutation =
* "good afternoon "; } else { salutation = "good evening "; }
*
*
* speakBlocking(String.format("%s. i was sleeping but now i am awake" ,
* salutation));
*/
}
}
@Override
public void purgeTasks() {
speakBlocking("purging all tasks");
super.purgeTasks();
}
@Override
public boolean save() {
super.save();
if (leftHand != null) {
leftHand.save();
}
if (rightHand != null) {
rightHand.save();
}
if (rightArm != null) {
rightArm.save();
}
if (leftArm != null) {
leftArm.save();
}
if (head != null) {
head.save();
}
if (openni != null) {
openni.save();
}
return true;
}
public void setMute(boolean mute) {
info("Set mute to %s", mute);
this.mute = mute;
}
public List<AudioData> speakBlocking(String toSpeak) {
if (mouth == null) {
mouth = (SpeechSynthesis)startPeer("mouth");
}
if (mouth == null) {
log.error("speakBlocking is called, but my mouth is NULL...");
return null;
}
if (!mute) {
try {
return mouth.speakBlocking(toSpeak);
} catch (Exception e) {
log.error("speakBlocking threw", e);
}
}
return null;
}
public List<AudioData> speakAlert(String toSpeak) {
speakBlocking(languagePack.get("ALERT"));
return speakBlocking(toSpeak);
}
public List<AudioData> speak(String toSpeak) {
if (mouth == null) {
log.error("Speak is called, but my mouth is NULL...");
return null;
}
if (!mute) {
try {
return mouth.speak(toSpeak);
} catch (Exception e) {
Logging.logError(e);
}
}
return null;
}
public boolean speakErrors(boolean b) {
speakErrors = b;
return b;
}
// FIXME , later ... attach things !
public void startAll(String leftPort, String rightPort) throws Exception {
startMouth();
startHead(leftPort);
startOpenCV();
startEar();
startMouthControl(head.jaw, mouth);
startLeftHand(leftPort);
startRightHand(rightPort);
// startEyelids(rightPort);
startLeftArm(leftPort);
startRightArm(rightPort);
startTorso(leftPort);
startHeadTracking();
startEyesTracking();
// TODO LP
speakBlocking("startup sequence completed");
}
/**
* Start InMoov brain engine And extra stuffs, like "what is you name" ( TODO
* finish migration )
*
* @return started ProgramAB service
*/
public ProgramAB startBrain() {
if (chatBot == null) {
chatBot = (ProgramAB) Runtime.start(this.getIntanceName() + ".brain", "ProgramAB");
}
this.attach(chatBot);
speakBlocking(languagePack.get("CHATBOTACTIVATED"));
chatBot.repetitionCount(10);
chatBot.setPath("InMoov/chatBot");
chatBot.startSession("default", getLanguage());
// reset some parameters to default...
chatBot.setPredicate("topic", "default");
chatBot.setPredicate("questionfirstinit", "");
chatBot.setPredicate("tmpname", "");
chatBot.setPredicate("null", "");
// load last user session
if (!chatBot.getPredicate("name").isEmpty()) {
if (chatBot.getPredicate("lastUsername").isEmpty() || chatBot.getPredicate("lastUsername").equals("unknown")) {
chatBot.setPredicate("lastUsername", chatBot.getPredicate("name"));
}
}
chatBot.setPredicate("parameterHowDoYouDo", "");
try {
chatBot.savePredicates();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// start session based on last recognized person
if (!chatBot.getPredicate("default", "lastUsername").isEmpty() && !chatBot.getPredicate("default", "lastUsername").equals("unknown")) {
chatBot.startSession(chatBot.getPredicate("lastUsername"));
}
return chatBot;
}
// TODO TODO TODO - context & status report -
// "current context is right hand"
// FIXME - voice control for all levels (ie just a hand or head !!!!)
public SpeechRecognizer startEar() {
if (ear == null) {
ear = (SpeechRecognizer) startPeer("ear");
}
this.attach((Attachable) ear);
speakBlocking(languagePack.get("STARTINGEAR"));
return ear;
}
public SpeechSynthesis startMouth() {
if (mouth == null) {
mouth = (SpeechSynthesis) startPeer("mouth");
}
this.attach((Attachable) mouth);
speakBlocking(languagePack.get("STARTINGMOUTH"));
speakBlocking(languagePack.get("WHATISTHISLANGUAGE"));
return mouth;
}
@Deprecated
public MouthControl startMouthControl(String port) {
log.warn("Please use ServoControl : startMouthControl(YourServoJaw,mouthService), I will try to do it for you...");
return startMouthControl();
}
public MouthControl startMouthControl() {
return startMouthControl(head.jaw, mouth);
}
public MouthControl startMouthControl(ServoControl jaw, SpeechSynthesis mouth) {
speakBlocking(languagePack.get("STARTINGMOUTHCONTROL"));
if (mouthControl == null) {
mouthControl = (MouthControl) startPeer("mouthControl");
mouthControl.attach(jaw);
mouthControl.attach((Attachable) mouth);
mouthControl.setmouth(10, 50);
}
return mouthControl;
}
public boolean startOpenCV() {
speakBlocking(languagePack.get("STARTINGOPENCV"));
if (opencv == null) {
opencv = (OpenCV) Runtime.loadAndStart(this.getIntanceName() + ".opencv", "OpenCV");
}
this.attach(opencv);
if (vision.openCVenabled) {
// test for a worky opencv with hardware
// TODO: revisit this test method. , maybe it should go away or be done differently?
// It forces capture
if (vision.test()) {
broadcastState();
return true;
} else {
speakAlert(languagePack.get("OPENCVNOWORKY"));
return false;
}
}
return false;
}
public OpenNi startOpenNI() throws Exception {
if (openni == null) {
speakBlocking(languagePack.get("STARTINGOPENNI"));
openni = (OpenNi) startPeer("openni");
pid = (Pid) startPeer("pid");
pid.setPID("kinect", 10.0, 0.0, 1.0);
pid.setMode("kinect", Pid.MODE_AUTOMATIC);
pid.setOutputRange("kinect", -1, 1);
pid.setControllerDirection("kinect", 0);
// re-mapping of skeleton !
openni.skeleton.leftElbow.mapXY(0, 180, 180, 0);
openni.skeleton.rightElbow.mapXY(0, 180, 180, 0);
if (openNiLeftShoulderInverted) {
openni.skeleton.leftShoulder.mapYZ(0, 180, 180, 0);
}
if (openNiRightShoulderInverted) {
openni.skeleton.rightShoulder.mapYZ(0, 180, 180, 0);
}
// openni.skeleton.leftShoulder
// openni.addListener("publishOpenNIData", this.getName(),
// "getSkeleton");
// openni.addOpenNIData(this);
subscribe(openni.getName(), "publishOpenNIData");
}
return openni;
}
public void startPIR(String port, int pin) throws IOException {
speakBlocking(String.format("starting pee. eye. are. sensor on port %s pin %d", port, pin));
if (arduinos.containsKey(port)) {
ServoController sc = arduinos.get(port);
if (sc instanceof Arduino) {
Arduino arduino = (Arduino) sc;
// arduino.connect(port);
// arduino.setSampleRate(8000);
arduino.enablePin(pin, 10);
pirArduino = arduino;
pirPin = pin;
arduino.addListener("publishPin", this.getName(), "publishPin");
}
} else {
// FIXME - SHOULD ALLOW STARTUP AND LATER ACCESS VIA PORT ONCE OTHER
// STARTS CHECK MAP FIRST
log.error("{} arduino not found - start some other system first (head, arm, hand)", port);
}
}
@Override
public void preShutdown() {
RobotCanMoveRandom = false;
stopTracking();
speakBlocking(languagePack.get("SHUTDOWN"));
halfSpeed();
rest();
waitTargetPos();
// if relay used, we switch on power
if (LeftRelay1 != null) {
LeftRelay1.on();
}
if (RightRelay1 != null) {
RightRelay1.on();
}
if (eyelids != null) {
eyelids.autoBlink(false);
eyelids.moveToBlocking(180, 180);
}
stopVinMoov();
if (neopixel != null && neopixelArduino != null) {
neopixel.animationStop();
sleep(500);
neopixel.detach(neopixelArduino);
sleep(100);
neopixelArduino.serial.disconnect();
neopixelArduino.serial.stopRecording();
neopixelArduino.disconnect();
}
disable();
if (LeftRelay1 != null) {
LeftRelay1.off();
}
if (RightRelay1 != null) {
RightRelay1.off();
}
}
@Override
public void startService() {
super.startService();
if (vision == null) {
vision = new Vision();
vision.init();
}
vision.instance = this;
// TODO : use locale it-IT,fi-FI
languages.put("en-US", "English - United States");
languages.put("fr-FR", "French - France");
languages.put("es-ES", "Spanish - Spain");
languages.put("de-DE", "German - Germany");
languages.put("nl-NL", "Dutch - Netherlands");
languages.put("ru-RU", "Russian");
languages.put("hi-IN", "Hindi - India");
languages.put("it-IT", "Italian - Italia");
languages.put("fi-FI", "Finnish - Finland");
languages.put("pt-PT", "Portuguese - Portugal");
languagesIndex = new ArrayList<String>(languages.keySet());
this.language = getLanguage();
python = getPython();
languagePack.load(language);
// get events of new services and shutdown
Runtime r = Runtime.getInstance();
subscribe(r.getName(), "shutdown");
}
public InMoovTorso startTorso(String port) throws Exception {
return startTorso(port, null);
}
public InMoovTorso startTorso(String port, String type) throws Exception {
// log.warn(InMoov.buildDNA(myKey, serviceClass))
speakBlocking(languagePack.get("STARTINGTORSO") + " " + port);
torso = (InMoovTorso) startPeer("torso");
if (type == null) {
type = Arduino.BOARD_TYPE_MEGA;
}
// FIXME - needs to be a ServoController
// torso.arduino.setBoard(type);
torso.connect(port);
arduinos.put(port, torso.controller);
return torso;
}
public void stopPIR() {
if (pirArduino != null && pirPin != null) {
pirArduino.disablePin(pirPin);
pirPin = null;
pirArduino = null;
}
/*
* if (arduinos.containsKey(port)) { Arduino arduino = arduinos.get(port);
* arduino.connect(port); arduino.setSampleRate(8000);
* arduino.digitalReadPollStart(pin); pirPin = pin;
* arduino.addListener("publishPin", this.getName(), "publishPin"); }
*/
}
// This is an in-flight check vs power up or power down
public void systemCheck() {
speakBlocking("starting system check");
speakBlocking("testing");
rest();
sleep(500);
if (rightHand != null) {
speakBlocking("testing right hand");
rightHand.test();
}
if (rightArm != null) {
speakBlocking("testing right arm");
rightArm.test();
}
if (leftHand != null) {
speakBlocking("testing left hand");
leftHand.test();
}
if (leftArm != null) {
speakBlocking("testing left arm");
leftArm.test();
}
if (head != null) {
speakBlocking("testing head");
head.test();
}
if (torso != null) {
speakBlocking("testing torso");
torso.test();
}
if (eyelids != null) {
speakBlocking("testing eyelids");
eyelids.test();
}
sleep(500);
rest();
broadcastState();
speakBlocking("system check completed");
}
public void loadCalibration() {
loadCalibration(CALIBRATION_FILE);
}
public void loadCalibration(String calibrationFilename) {
File calibF = new File(calibrationFilename);
if (calibF.exists()) {
log.info("Loading Calibration Python file {}", calibF.getAbsolutePath());
Python p = (Python) Runtime.getService("python");
try {
p.execFile(calibF.getAbsolutePath());
} catch (IOException e) {
// TODO Auto-generated catch block
log.warn("Error loading calibratoin file {}", calibF.getAbsolutePath());
e.printStackTrace();
}
}
}
public void saveCalibration() {
saveCalibration(CALIBRATION_FILE);
}
public void saveCalibration(String calibrationFilename) {
File calibFile = new File(calibrationFilename);
FileWriter calibrationWriter = null;
try {
calibrationWriter = new FileWriter(calibFile);
calibrationWriter.write("
calibrationWriter.write("# InMoov auto generated calibration \n");
calibrationWriter.write("# " + new Date() + "\n");
calibrationWriter.write("
// String inMoovName = this.getName();
// iterate all the services that are running.
// we want all servos that are currently in the system?
for (ServiceInterface service : Runtime.getServices()) {
if (service instanceof ServoControl) {
ServoControl s = (Servo) service;
if (!s.getName().startsWith(this.getName())) {
continue;
}
calibrationWriter.write("\n");
// first detach the servo.
calibrationWriter.write("# Servo Config : " + s.getName() + "\n");
calibrationWriter.write(s.getName() + ".detach()\n");
calibrationWriter.write(s.getName() + ".setMinMax(" + s.getMin() + "," + s.getMax() + ")\n");
calibrationWriter.write(s.getName() + ".setVelocity(" + s.getSpeed() + ")\n");
calibrationWriter.write(s.getName() + ".setRest(" + s.getRest() + ")\n");
if (s.getPin() != null) {
calibrationWriter.write(s.getName() + ".setPin(" + s.getPin() + ")\n");
} else {
calibrationWriter.write("# " + s.getName() + ".setPin(" + s.getPin() + ")\n");
}
s.map(s.getMin(), s.getMax(), s.getMinOutput(), s.getMaxOutput());
// save the servo map
calibrationWriter.write(s.getName() + ".map(" + s.getMin() + "," + s.getMax() + "," + s.getMinOutput() + "," + s.getMaxOutput() + ")\n");
// if there's a controller reattach it at rest
if (s.getControllerName() != null) {
String controller = s.getControllerName();
calibrationWriter.write(s.getName() + ".attach(\"" + controller + "\"," + s.getPin() + "," + s.getRest() + ")\n");
}
if (s.getAutoDisable()) {
calibrationWriter.write(s.getName() + ".setAutoDisable(True)\n");
}
}
}
calibrationWriter.write("\n");
calibrationWriter.close();
} catch (IOException e) {
log.warn("Error writing calibration file {}", calibrationFilename);
e.printStackTrace();
return;
}
}
// vinmoov cosmetics and optional vinmoov monitor idea ( poc i know nothing
// about jme...)
// just want to use jme as main screen and show some informations
// like batterie / errors / onreconized text etc ...
// i01.VinmoovMonitorActivated=1 before to start vinmoov
public Boolean VinmoovMonitorActivated = false;
public void onListeningEvent() {
if (vinMoovApp != null && VinmoovMonitorActivated && RobotIsStarted) {
vinMoovApp.setMicro(true);
}
}
public void onPauseListening() {
if (vinMoovApp != null && VinmoovMonitorActivated && RobotIsStarted) {
vinMoovApp.setMicro(false);
}
}
public void setBatteryLevel(Integer level) {
if (vinMoovApp != null && VinmoovMonitorActivated && RobotIsStarted) {
vinMoovApp.setBatteryLevel(level);
}
}
public Boolean VinmoovFullScreen = false;
public String VinmoovBackGroundColor = "Grey";
public int VinmoovWidth = 800;
public int VinmoovHeight = 600;
private Boolean debugVinmoov = true;
// show some infos to jme screen
public void setLeftArduinoConnected(boolean param) {
vinMoovApp.setLeftArduinoConnected(param);
}
public void setRightArduinoConnected(boolean param) {
vinMoovApp.setRightArduinoConnected(param);
}
// end vinmoov cosmetics and optional vinmoov monitor
/* use the most recent virtual inmoov */
public void onIKServoEvent(ServoData data) {
if (vinMoovApp != null) {
vinMoovApp.updatePosition(data);
}
}
public void stopVinMoov() {
try {
vinMoovApp.stop();
} catch (NullPointerException e) {
}
vinMoovApp = null;
}
public void startIntegratedMovement() {
integratedMovement = (IntegratedMovement) startPeer("integratedMovement");
IntegratedMovement im = integratedMovement;
// set the DH Links or each arms
im.setNewDHRobotArm("leftArm");
im.setNewDHRobotArm("rightArm");
im.setNewDHRobotArm("kinect");
if (torso != null) {
im.setDHLink("leftArm", torso.midStom, 113, 90, 0, -90);
im.setDHLink("rightArm", torso.midStom, 113, 90, 0, -90);
im.setDHLink("kinect", torso.midStom, 113, 90, 0, -90);
im.setDHLink("leftArm", torso.topStom, 0, 180, 292, 90);
im.setDHLink("rightArm", torso.topStom, 0, 180, 292, 90);
im.setDHLink("kinect", torso.topStom, 0, 180, 110, -90);
} else {
im.setDHLink("leftArm", "i01.torso.midStom", 113, 90, 0, -90);
im.setDHLink("rightArm", "i01.torso.midStom", 113, 90, 0, -90);
im.setDHLink("kinect", "i01.torso.midStom", 113, 90, 0, -90);
im.setDHLink("leftArm", "i01.torso.topStom", 0, 180, 292, 90);
im.setDHLink("rightArm", "i01.torso.topStom", 0, 180, 292, 90);
im.setDHLink("kinect", "i01.torso.topStom", 0, 180, 110, -90);
}
im.setDHLink("leftArm", "leftS", 143, 180, 0, 90);
im.setDHLink("rightArm", "rightS", -143, 180, 0, -90);
if (arms.containsKey(LEFT)) {
InMoovArm arm = arms.get(LEFT);
im.setDHLink("leftArm", arm.omoplate, 0, -5.6, 45, -90);
im.setDHLink("leftArm", arm.shoulder, 77, -30 + 90, 0, 90);
im.setDHLink("leftArm", arm.rotate, 284, 90, 40, 90);
im.setDHLink("leftArm", arm.bicep, 0, -7 + 24.4 + 90, 300, 90);
} else {
im.setDHLink("leftArm", "i01.leftArm.omoplate", 0, -5.6, 45, -90);
im.setDHLink("leftArm", "i01.leftArm.shoulder", 77, -30 + 90, 0, 90);
im.setDHLink("leftArm", "i01.leftArm.rotate", 284, 90, 40, 90);
im.setDHLink("leftArm", "i01.leftArm.bicep", 0, -7 + 24.4 + 90, 300, 90);
}
if (arms.containsKey(RIGHT)) {
InMoovArm arm = arms.get(RIGHT);
im.setDHLink("rightArm", arm.omoplate, 0, -5.6, 45, 90);
im.setDHLink("rightArm", arm.shoulder, -77, -30 + 90, 0, -90);
im.setDHLink("rightArm", arm.rotate, -284, 90, 40, -90);
im.setDHLink("rightArm", arm.bicep, 0, -7 + 24.4 + 90, 300, 0);
} else {
im.setDHLink("rightArm", "i01.rightArm.omoplate", 0, -5.6, 45, 90);
im.setDHLink("rightArm", "i01.rightArm.shoulder", -77, -30 + 90, 0, -90);
im.setDHLink("rightArm", "i01.rightArm.rotate", -284, 90, 40, -90);
im.setDHLink("rightArm", "i01.rightArm.bicep", 0, -7 + 24.4 + 90, 300, 0);
}
if (hands.containsKey(LEFT)) {
InMoovHand hand = hands.get(LEFT);
im.setDHLink("leftArm", hand.wrist, 00, -90, 0, 0);
im.setDHLinkType("i01.leftHand.wrist", DHLinkType.REVOLUTE_ALPHA);
} else {
im.setDHLink("leftArm", "i01.leftHand.wrist", 00, -90, 0, 0);
}
if (hands.containsKey(RIGHT)) {
InMoovHand hand = hands.get(RIGHT);
im.setDHLink("rightArm", hand.wrist, 00, -90, 0, 0);
im.setDHLinkType("i01.rigtHand.wrist", DHLinkType.REVOLUTE_ALPHA);
} else {
im.setDHLink("rightArm", "i01.rightHand.wrist", 00, -90, 0, 0);
}
im.setDHLink("leftArm", "wristup", 0, -5, 90, 0);
im.setDHLink("leftArm", "wristdown", 0, 0, 125, 45);
im.setDHLink("leftArm", "finger", 5, -90, 5, 0);
im.setDHLink("rightArm", "Rwristup", 0, 5, 90, 0);
im.setDHLink("rightArm", "Rwristdown", 0, 0, 125, -45);
im.setDHLink("rightArm", "Rfinger", 5, 90, 5, 0);
im.setDHLink("kinect", "camera", 0, 90, 10, 90);
// log.info("{}",im.createJointPositionMap("leftArm").toString());
// start the kinematics engines
// define object, each dh link are set as an object, but the
// start point and end point will be update by the ik service, but still
// need
// a name and a radius
im.clearObject();
im.addObject(0.0, 0.0, 0.0, 0.0, 0.0, -150.0, "base", 150.0, false);
im.addObject("i01.torso.midStom", 150.0);
im.addObject("i01.torso.topStom", 10.0);
im.addObject("i01.leftArm.omoplate", 10.0);
im.addObject("i01.rightArm.omoplate", 10.0);
im.addObject("i01.leftArm.shoulder", 50.0);
im.addObject("i01.rightArm.shoulder", 50.0);
im.addObject("i01.leftArm.rotate", 50.0);
im.addObject("i01.rightArm.rotate", 50.0);
im.addObject("i01.leftArm.bicep", 60.0);
im.addObject("i01.rightArm.bicep", 60.0);
im.addObject("i01.leftHand.wrist", 70.0);
im.addObject("i01.rightHand.wrist", 70.0);
im.objectAddIgnore("i01.rightArm.omoplate", "i01.leftArm.rotate");
im.objectAddIgnore("i01.rightArm.omoplate", "i01.rightArm.rotate");
im.addObject("leftS", 10);
im.addObject("rightS", 10);
im.objectAddIgnore("leftS", "rightS");
im.objectAddIgnore("rightS", "i01.leftArm.shoulder");
im.objectAddIgnore("leftS", "i01.rightArm.shoulder");
im.addObject("wristup", 70);
im.addObject("wristdown", 70);
im.objectAddIgnore("i01.leftArm.bicep", "wristup");
im.addObject("Rwristup", 70);
im.addObject("Rwristdown", 70);
im.objectAddIgnore("i01.rightArm.bicep", "Rwristup");
im.startEngine("leftArm");
im.startEngine("rightArm");
im.startEngine("kinect");
im.cog = new GravityCenter(im);
im.cog.setLinkMass("i01.torso.midStom", 2.832, 0.5);
im.cog.setLinkMass("i01.torso.topStom", 5.774, 0.5);
im.cog.setLinkMass("i01.leftArm.omoplate", 0.739, 0.5);
im.cog.setLinkMass("i01.rightArm.omoplate", 0.739, 0.5);
im.cog.setLinkMass("i01.leftArm.rotate", 0.715, 0.5754);
im.cog.setLinkMass("i01.rightArm.rotate", 0.715, 0.5754);
im.cog.setLinkMass("i01.leftArm.shoulder", 0.513, 0.5);
im.cog.setLinkMass("i01.rightArm.shoulder", 0.513, 0.5);
im.cog.setLinkMass("i01.leftArm.bicep", 0.940, 0.4559);
im.cog.setLinkMass("i01.rightArm.bicep", 0.940, 0.4559);
im.cog.setLinkMass("i01.leftHand.wrist", 0.176, 0.7474);
im.cog.setLinkMass("i01.rightHand.wrist", 0.176, 0.7474);
im.setJmeApp(vinMoovApp);
im.setOpenni(openni);
}
public Double getUltrasonicSensorDistance() {
if (ultrasonicSensor != null) {
return ultrasonicSensor.range();
} else {
warn("No UltrasonicSensor attached");
return 0.0;
}
}
public void setNeopixelAnimation(String animation, Integer red, Integer green, Integer blue, Integer speed) {
if (neopixel != null && neopixelArduino != null) {
neopixel.setAnimation(animation, red, green, blue, speed);
} else {
warn("No Neopixel attached");
}
}
public void stopNeopixelAnimation() {
if (neopixel != null && neopixelArduino != null) {
neopixel.animationStop();
} else {
warn("No Neopixel attached");
}
}
/**
* TODO : use system locale set language for InMoov service used by chatbot +
* ear + mouth
*
* @param l
* - format : java Locale
*/
public boolean setLanguage(String l) {
if (languages.containsKey(l)) {
this.language = l;
info("Set language to %s", languages.get(l));
Runtime runtime = Runtime.getInstance();
runtime.setLocale(l);
languagePack.load(language);
return true;
// this.broadcastState();
} else {
error("InMoov not yet support {}", l);
return false;
}
}
/**
* get current language
*/
public String getLanguage() {
if (this.language == null) {
// check if default locale supported by inmoov
if (languages.containsKey(Locale.getDefault().toLanguageTag())) {
this.language = Locale.getDefault().toLanguageTag();
} else {
this.language = "en-US";
}
}
// to be sure runtime == inmoov language
if (!Locale.getDefault().toLanguageTag().equals(this.language)) {
setLanguage(this.language);
}
return this.language;
}
/**
* @return the mute startup state ( InMoov vocal startup actions )
*/
public Boolean getMute() {
return mute;
}
// END GENERAL METHODS / TO SORT
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(InMoov.class.getCanonicalName());
meta.addDescription("The InMoov service");
meta.addCategory("robot");
// meta.addDependency("inmoov.fr", "1.0.0");
// meta.addDependency("org.myrobotlab.inmoov", "1.0.0");
meta.addDependency("inmoov.fr", "inmoov", "1.1.11", "zip");
meta.addDependency("inmoov.fr", "jm3-model", "1.0.0", "zip");
meta.sharePeer("head.arduino", "left", "Arduino", "shared left arduino");
meta.sharePeer("torso.arduino", "left", "Arduino", "shared left arduino");
meta.sharePeer("leftArm.arduino", "left", "Arduino", "shared left arduino");
meta.sharePeer("leftHand.arduino", "left", "Arduino", "shared left arduino");
// eyelidsArduino peer for backward compatibility
meta.sharePeer("eyelidsArduino", "right", "Arduino", "shared right arduino");
meta.sharePeer("rightArm.arduino", "right", "Arduino", "shared right arduino");
meta.sharePeer("rightHand.arduino", "right", "Arduino", "shared right arduino");
meta.sharePeer("eyesTracking.opencv", "opencv", "OpenCV", "shared head OpenCV");
meta.sharePeer("eyesTracking.controller", "left", "Arduino", "shared head Arduino");
meta.sharePeer("eyesTracking.x", "head.eyeX", "Servo", "shared servo");
meta.sharePeer("eyesTracking.y", "head.eyeY", "Servo", "shared servo");
meta.sharePeer("mouthControl.mouth", "mouth", speechService, "shared Speech");
meta.sharePeer("headTracking.opencv", "opencv", "OpenCV", "shared head OpenCV");
meta.sharePeer("headTracking.controller", "left", "Arduino", "shared head Arduino");
meta.sharePeer("headTracking.x", "head.rothead", "Servo", "shared servo");
meta.sharePeer("headTracking.y", "head.neck", "Servo", "shared servo");
// Global - undecorated by self name
meta.addRootPeer("python", "Python", "shared Python service");
// put peer definitions in
meta.addPeer("torso", "InMoovTorso", "torso");
meta.addPeer("eyelids", "InMoovEyelids", "eyelids");
meta.addPeer("leftArm", "InMoovArm", "left arm");
meta.addPeer("leftHand", "InMoovHand", "left hand");
meta.addPeer("rightArm", "InMoovArm", "right arm");
meta.addPeer("rightHand", "InMoovHand", "right hand");
// webkit speech.
meta.addPeer("ear", speechRecognizer, "InMoov webkit speech recognition service");
// meta.addPeer("ear", "Sphinx", "InMoov Sphinx speech recognition
// service");
meta.addPeer("eyesTracking", "Tracking", "Tracking for the eyes");
meta.addPeer("head", "InMoovHead", "the head");
meta.addPeer("headTracking", "Tracking", "Head tracking system");
meta.addPeer("mouth", speechService, "InMoov speech service");
meta.addPeer("mouthControl", "MouthControl", "MouthControl");
meta.addPeer("openni", "OpenNi", "Kinect service");
meta.addPeer("pid", "Pid", "Pid service");
// For VirtualInMoov
meta.addPeer("jme", "JMonkeyEngine", "Virtual inmoov");
meta.addPeer("ik3d", "InverseKinematics3D", "Virtual inmoov");
// For IntegratedMovement
meta.addPeer("integratedMovement", "IntegratedMovement", "Inverse kinematic type movement");
return meta;
}
public void setHead(InMoovHead head) {
this.head = head;
}
public InMoovHead startHead(ServoController controller) {
speakBlocking(languagePack.get("STARTINGHEAD"));
head = (InMoovHead) startPeer("head");
head.setController(controller);
// arduinos.put(port, head.controller); // FIXME - silly used by PIR -
// refactor out ..
return head;
}
public InMoovArm startArm(String side, ServoController controller) throws Exception {
// speakBlocking(languagePack.get("STARTINGLEFTARM"));
InMoovArm arm = (InMoovArm) startPeer(String.format("%sArm", side));
arm.setController(controller);
arms.put(side, arm);
arm.setSide(side);// FIXME WHO USES SIDE - THIS SHOULD BE NAME !!!
if ("left".equals(side)) {
leftArm = arm;
} else if ("right".equals(side)) {
rightArm = arm;
}
return arm;
}
public InMoovHand startHand(String side, ServoController sc) {
InMoovHand hand = (InMoovHand) startPeer(String.format("%sHand", side));
hand.setSide(side);
hands.put(side, hand);
hand.setController(sc);
if ("left".equals(side)) {
leftHand = hand;
} else if ("right".equals(side)) {
rightHand = hand;
}
return hand;
}
public InMoovTorso startTorso(ServoController controller) throws Exception {
torso = (InMoovTorso) startPeer("torso");
torso.setController(controller);
return torso;
}
@Override
public void onJointAngles(Map<String, Double> angleMap) {
// TODO Auto-generated method stub
log.info("onJointAngles {}", angleMap);
// here we can make decisions on what ik sets we want to use and
// what body parts are to move
for (String name : angleMap.keySet()) {
ServiceInterface si = Runtime.getService(name);
if (si instanceof Servo) {
((Servo)si).moveTo(angleMap.get(name));
}
}
}
public void startIK3d() throws Exception {
ik3d = (InverseKinematics3D) Runtime.start("ik3d", "InverseKinematics3D");
ik3d.setCurrentArm("rightArm", InMoovArm.getDHRobotArm(getName(), "left"));
// Runtime.createAndStart("gui", "SwingGui");
// OpenCV cv1 = (OpenCV)Runtime.createAndStart("cv1", "OpenCV");
// OpenCVFilterAffine aff1 = new OpenCVFilterAffine("aff1");
// aff1.setAngle(270);
// aff1.setDx(-80);
// aff1.setDy(-80);
// cv1.addFilter(aff1);
// cv1.setCameraIndex(0);
// cv1.capture();
// cv1.undockDisplay(true);
/*
* SwingGui gui = new SwingGui("gui"); gui.startService();
*/
/*
* Joystick joystick = (Joystick) Runtime.start("joystick", "Joystick");
* joystick.setController(2);
*
* // joystick.startPolling();
*
* // attach the joystick input to the ik3d service. //
* joystick.addInputListener(ik3d); joystick.attach(this);
*/
}
public static void main(String[] args) throws Exception {
LoggingFactory.init(Level.INFO);
String leftPort = "COM3";
String rightPort = "COM4";
Platform.setVirtual(true);
Runtime.start("gui", "SwingGui");
Runtime.start("python", "Python");
InMoov i01 = (InMoov) Runtime.start("i01", "InMoov");
i01.setLanguage("en-US");
i01.startMouth();
i01.startEar();
WebGui webgui = (WebGui) Runtime.create("webgui", "WebGui");
webgui.autoStartBrowser(false);
webgui.startService();
webgui.startBrowser("http://localhost:8888/#/service/i01.ear");
HtmlFilter htmlFilter = (HtmlFilter) Runtime.start("htmlFilter", "HtmlFilter");
i01.chatBot = (ProgramAB) Runtime.start("i01.chatBot", "ProgramAB");
i01.chatBot.addTextListener(htmlFilter);
htmlFilter.addListener("publishText", "i01", "speak");
i01.chatBot.attach((Attachable) i01.ear);
i01.startBrain();
i01.startHead(leftPort);
i01.startMouthControl(i01.head.jaw, i01.mouth);
i01.loadGestures("InMoov/gestures");
i01.startVinMoov();
i01.startOpenCV();
i01.execGesture("BREAKITdaVinci()");
}
public void startVinMoov() throws Exception {
startSimulator();
}
@Override
public void onJoystickInput(JoystickData input) throws Exception {
// TODO Auto-generated method stub
}
Point ikPoint = null;
public void startSimulator() throws Exception {
if (jme == null) {
jme = (JMonkeyEngine) startPeer("jme");
}
// disable the frustrating servo events ...
// Servo.eventsEnabledDefault(false);
jme.setRotation("i01.head.jaw", "x");
jme.setRotation("i01.head.neck", "x");
jme.setRotation("i01.head.rothead", "y");
jme.setRotation("i01.head.rollNeck", "z");
jme.setRotation("i01.head.eyeY", "x");
jme.setRotation("i01.head.eyeX", "y");
jme.setRotation("i01.torso.topStom", "z");
jme.setRotation("i01.torso.midStom", "y");
jme.setRotation("i01.torso.lowStom", "x");
jme.setRotation("i01.rightArm.bicep", "x");
jme.setRotation("i01.leftArm.bicep", "x");
jme.setRotation("i01.rightArm.shoulder", "x");
jme.setRotation("i01.leftArm.shoulder", "x");
jme.setRotation("i01.rightArm.rotate", "y");
jme.setRotation("i01.leftArm.rotate", "y");
jme.setRotation("i01.rightArm.omoplate", "z");
jme.setRotation("i01.leftArm.omoplate", "z");
jme.setRotation("i01.rightHand.wrist", "y");
jme.setRotation("i01.leftHand.wrist", "y");
jme.setMapper("i01.head.jaw", 0, 180, -5, 80);
jme.setMapper("i01.head.neck", 0, 180, 20, -20);
jme.setMapper("i01.head.rollNeck", 0, 180, 30, -30);
jme.setMapper("i01.head.eyeY", 0, 180, 40, 140);
jme.setMapper("i01.head.eyeX", 0, 180, -10, 70); //HERE there need to be two eyeX (left and right?)
jme.setMapper("i01.rightArm.bicep", 0, 180, 0, -150);
jme.setMapper("i01.leftArm.bicep", 0, 180, 0, -150);
jme.setMapper("i01.rightArm.shoulder", 0, 180, 30, -150);
jme.setMapper("i01.leftArm.shoulder", 0, 180, 30, -150);
jme.setMapper("i01.rightArm.rotate", 0, 180, 80, -80);
jme.setMapper("i01.leftArm.rotate", 0, 180, -80, 80);
jme.setMapper("i01.rightArm.omoplate", 0, 180, 10, -180);
jme.setMapper("i01.leftArm.omoplate", 0, 180, -10, 180);
jme.setMapper("i01.rightHand.wrist", 0, 180, -20, 60);
jme.setMapper("i01.leftHand.wrist", 0, 180, 20, -60);
jme.setMapper("i01.torso.topStom", 0, 180, -30, 30);
jme.setMapper("i01.torso.midStom", 0, 180, 50, 130);
jme.setMapper("i01.torso.lowStom", 0, 180, -30, 30);
jme.attach("i01.leftHand.thumb", "i01.leftHand.thumb1", "i01.leftHand.thumb2", "i01.leftHand.thumb3");
jme.setRotation("i01.leftHand.thumb1", "y");
jme.setRotation("i01.leftHand.thumb2", "x");
jme.setRotation("i01.leftHand.thumb3", "x");
jme.attach("i01.leftHand.index", "i01.leftHand.index", "i01.leftHand.index2", "i01.leftHand.index3");
jme.setRotation("i01.leftHand.index", "x");
jme.setRotation("i01.leftHand.index2", "x");
jme.setRotation("i01.leftHand.index3", "x");
jme.attach("i01.leftHand.majeure", "i01.leftHand.majeure", "i01.leftHand.majeure2", "i01.leftHand.majeure3");
jme.setRotation("i01.leftHand.majeure", "x");
jme.setRotation("i01.leftHand.majeure2", "x");
jme.setRotation("i01.leftHand.majeure3", "x");
jme.attach("i01.leftHand.ringFinger", "i01.leftHand.ringFinger", "i01.leftHand.ringFinger2", "i01.leftHand.ringFinger3");
jme.setRotation("i01.leftHand.ringFinger", "x");
jme.setRotation("i01.leftHand.ringFinger2", "x");
jme.setRotation("i01.leftHand.ringFinger3", "x");
jme.attach("i01.leftHand.pinky", "i01.leftHand.pinky", "i01.leftHand.pinky2", "i01.leftHand.pinky3");
jme.setRotation("i01.leftHand.pinky", "x");
jme.setRotation("i01.leftHand.pinky2", "x");
jme.setRotation("i01.leftHand.pinky3", "x");
// left hand mapping complexities of the fingers
jme.setMapper("i01.leftHand.index", 0, 180, -110, -179);
jme.setMapper("i01.leftHand.index2", 0, 180, -110, -179);
jme.setMapper("i01.leftHand.index3", 0, 180, -110, -179);
jme.setMapper("i01.leftHand.majeure", 0, 180, -110, -179);
jme.setMapper("i01.leftHand.majeure2", 0, 180, -110, -179);
jme.setMapper("i01.leftHand.majeure3", 0, 180, -110, -179);
jme.setMapper("i01.leftHand.ringFinger", 0, 180, -110, -179);
jme.setMapper("i01.leftHand.ringFinger2", 0, 180, -110, -179);
jme.setMapper("i01.leftHand.ringFinger3", 0, 180, -110, -179);
jme.setMapper("i01.leftHand.pinky", 0, 180, -110, -179);
jme.setMapper("i01.leftHand.pinky2", 0, 180, -110, -179);
jme.setMapper("i01.leftHand.pinky3", 0, 180, -110, -179);
jme.setMapper("i01.leftHand.thumb1", 0, 180, -30, -100);
jme.setMapper("i01.leftHand.thumb2", 0, 180, 80, 20);
jme.setMapper("i01.leftHand.thumb3", 0, 180, 80, 20);
// right hand
jme.attach("i01.rightHand.thumb", "i01.rightHand.thumb1", "i01.rightHand.thumb2", "i01.rightHand.thumb3");
jme.setRotation("i01.rightHand.thumb1", "y");
jme.setRotation("i01.rightHand.thumb2", "x");
jme.setRotation("i01.rightHand.thumb3", "x");
jme.attach("i01.rightHand.index", "i01.rightHand.index", "i01.rightHand.index2", "i01.rightHand.index3");
jme.setRotation("i01.rightHand.index", "x");
jme.setRotation("i01.rightHand.index2", "x");
jme.setRotation("i01.rightHand.index3", "x");
jme.attach("i01.rightHand.majeure", "i01.rightHand.majeure", "i01.rightHand.majeure2", "i01.rightHand.majeure3");
jme.setRotation("i01.rightHand.majeure", "x");
jme.setRotation("i01.rightHand.majeure2", "x");
jme.setRotation("i01.rightHand.majeure3", "x");
jme.attach("i01.rightHand.ringFinger", "i01.rightHand.ringFinger", "i01.rightHand.ringFinger2", "i01.rightHand.ringFinger3");
jme.setRotation("i01.rightHand.ringFinger", "x");
jme.setRotation("i01.rightHand.ringFinger2", "x");
jme.setRotation("i01.rightHand.ringFinger3", "x");
jme.attach("i01.rightHand.pinky", "i01.rightHand.pinky", "i01.rightHand.pinky2", "i01.rightHand.pinky3");
jme.setRotation("i01.rightHand.pinky", "x");
jme.setRotation("i01.rightHand.pinky2", "x");
jme.setRotation("i01.rightHand.pinky3", "x");
i01.jme.setMapper("i01.rightHand.index", 0, 180, 65, -10);
jme.setMapper("i01.rightHand.index2", 0, 180, 70, -10);
jme.setMapper("i01.rightHand.index3", 0, 180, 70, -10);
jme.setMapper("i01.rightHand.majeure", 0, 180, 65, -10);
jme.setMapper("i01.rightHand.majeure2", 0, 180, 70, -10);
jme.setMapper("i01.rightHand.majeure3", 0, 180, 70, -10);
jme.setMapper("i01.rightHand.ringFinger", 0, 180, 65, -10);
jme.setMapper("i01.rightHand.ringFinger2", 0, 180, 70, -10);
jme.setMapper("i01.rightHand.ringFinger3", 0, 180, 70, -10);
jme.setMapper("i01.rightHand.pinky", 0, 180, 65, -10);
jme.setMapper("i01.rightHand.pinky2", 0, 180, 70, -10);
jme.setMapper("i01.rightHand.pinky3", 0, 180, 60, -10);
jme.setMapper("i01.rightHand.thumb1", 0, 180, 30, 110);
jme.setMapper("i01.rightHand.thumb2", 0, 180, -100, -150);
jme.setMapper("i01.rightHand.thumb3", 0, 180, -100, -160);
// additional experimental mappings
/*
* jme.attach("i01.leftHand.pinky", "i01.leftHand.index2");
* jme.attach("i01.leftHand.thumb", "i01.leftHand.index3");
* jme.setRotation("i01.leftHand.index2", "x");
* jme.setRotation("i01.leftHand.index3", "x");
* jme.setMapper("i01.leftHand.index", 0, 180, -90, -270);
* jme.setMapper("i01.leftHand.index2", 0, 180, -90, -270);
* jme.setMapper("i01.leftHand.index3", 0, 180, -90, -270);
*/
// creating a virtual inmoov with virtual servo controller
ServoController sc = jme.getServoController();
InMoov i01 = (InMoov) Runtime.start("i01", "InMoov");
i01.startHead(sc);
i01.startArm("left", sc);
i01.startArm("right", sc);
i01.startHand("left", sc);
i01.startHand("right", sc);
i01.startTorso(sc);
i01.startMouth();
i01.startMouthControl();
i01.rest();
}
public void setIkPoint(double x, double y, double z) {
if (ikPoint == null) {
ikPoint = new Point(x, y, z);
jme.addBox("ikPoint", x, y, z, "cc0000", true);
}
// move target marker
jme.moveTo("ikPoint", x, y, z);
if (ik3d == null) {
ik3d = (InverseKinematics3D) startPeer("ik3d");
ik3d.setCurrentArm("i01.leftArm", InMoovArm.getDHRobotArm("i01", "left"));
ik3d.attach(this);
}
// move arm to target
ik3d.moveTo("i01.leftArm", ikPoint);
}
public JMonkeyEngine getSimulator() {
if (jme == null) {
jme = (JMonkeyEngine) startPeer("jme");
}
return jme;
}
} |
package cgeo.geocaching.activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Message;
/**
* progress dialog wrapper for easier management of resources
*/
public class Progress {
private ProgressDialog dialog;
public synchronized void dismiss() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
}
dialog = null;
}
public synchronized void show(final Context context, final String title, final String message, final boolean indeterminate, final Message cancelMessage) {
if (dialog == null) {
dialog = ProgressDialog.show(context, title, message, indeterminate, cancelMessage != null);
dialog.setProgress(0);
if (cancelMessage != null) {
dialog.setCancelMessage(cancelMessage);
}
}
}
public synchronized void show(final Context context, final String title, final String message, final int style, final Message cancelMessage) {
if (dialog == null) {
dialog = new ProgressDialog(context);
dialog.setProgress(0);
dialog.setTitle(title);
dialog.setMessage(message);
dialog.setProgressStyle(style);
if (cancelMessage != null) {
dialog.setCancelable(true);
dialog.setCancelMessage(cancelMessage);
} else {
dialog.setCancelable(false);
}
dialog.show();
}
}
public synchronized void setMessage(final String message) {
if (dialog != null && dialog.isShowing()) {
dialog.setMessage(message);
}
}
public synchronized boolean isShowing() {
return dialog != null && dialog.isShowing();
}
public synchronized void setMaxProgressAndReset(final int max) {
if (dialog != null && dialog.isShowing()) {
dialog.setMax(max);
dialog.setProgress(0);
}
}
public synchronized void setProgress(final int progress) {
if (dialog != null && dialog.isShowing()) {
dialog.setProgress(progress);
}
}
} |
package org.naaccr.xml.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;
import org.apache.commons.io.IOUtils;
import org.naaccr.xml.NaaccrFormat;
import org.naaccr.xml.NaaccrValidationError;
import org.naaccr.xml.NaaccrValidationException;
import org.naaccr.xml.NaaccrXmlOptions;
import org.naaccr.xml.NaaccrXmlUtils;
import org.naaccr.xml.PatientXmlReader;
import org.naaccr.xml.entity.Patient;
import org.naaccr.xml.entity.dictionary.runtime.RuntimeNaaccrDictionary;
@SuppressWarnings("unchecked")
public class Standalone {
public static void main(String[] args) {
if (System.getProperty("os.name").toUpperCase().contains("windows")) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (ClassNotFoundException | InstantiationException | UnsupportedLookAndFeelException | IllegalAccessException e) {
// ignored, the look and feel will be the default Java one...
}
UIManager.put("TabbedPane.contentBorderInsets", new Insets(0, 0, 0, 0));
Insets insets = UIManager.getInsets("TabbedPane.tabAreaInsets");
insets.bottom = 0;
UIManager.put("TabbedPane.tabAreaInsets", insets);
}
final JFrame frame = new StandaloneFrame();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
frame.pack();
frame.setLocation(200, 200);
frame.setVisible(true);
}
});
}
private static class StandaloneFrame extends JFrame {
private JFileChooser _fileChooser;
public StandaloneFrame() {
this.setTitle("NAACCR XML Utility v0.2");
this.setPreferredSize(new Dimension(1000, 700));
this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
JPanel contentPnl = new JPanel();
contentPnl.setOpaque(true);
contentPnl.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
contentPnl.setLayout(new BorderLayout());
contentPnl.setBackground(new Color(180, 191, 211));
this.getContentPane().setLayout(new BorderLayout());
this.getContentPane().add(contentPnl, BorderLayout.CENTER);
JPanel northPnl = new JPanel(new FlowLayout(FlowLayout.LEADING));
northPnl.setOpaque(false);
JLabel northLbl = new JLabel("This GUI is in a very early phase; feel free to report bugs in the \"Java library beta testing\" basecamp thread.");
northLbl.setForeground(new Color(150, 0, 0));
northPnl.add(northLbl);
contentPnl.add(northPnl, BorderLayout.NORTH);
JTabbedPane pane = new JTabbedPane();
pane.add(" Flat to XML ", crateFlatToXmlPanel());
pane.add(" XML to Flat ", crateXmlToFlatPanel());
pane.add(" Validation Test ", crateValidationTestPanel());
pane.add(" Dictionary ", crateDictionaryPanel());
contentPnl.add(pane, BorderLayout.CENTER);
_fileChooser = new JFileChooser();
_fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
_fileChooser.setDialogTitle("Select File");
_fileChooser.setApproveButtonToolTipText("Select file");
_fileChooser.setMultiSelectionEnabled(false);
}
private String invertFilename(File file) {
String[] name = file.getName().split("\\.");
if (name.length < 2)
return null;
String extension = name[name.length - 1];
boolean compressed = false;
if (extension.equalsIgnoreCase("gz")) {
extension = name[name.length - 2];
compressed = true;
}
StringBuilder result = new StringBuilder();
for (int i = 0; i < (compressed ? name.length - 2 : name.length - 1); i++)
result.append(name[i]).append(".");
result.append(extension.equalsIgnoreCase("xml") ? "txt" : "xml");
if (compressed)
result.append(".gz");
return new File(file.getParentFile(), result.toString()).getAbsolutePath();
}
private JPanel crateFlatToXmlPanel() {
final JPanel pnl = new JPanel();
pnl.setOpaque(false);
pnl.setBorder(null);
pnl.setLayout(new BoxLayout(pnl, BoxLayout.PAGE_AXIS));
JPanel row1Pnl = new JPanel();
row1Pnl.setOpaque(false);
row1Pnl.setBorder(null);
row1Pnl.setLayout(new FlowLayout(FlowLayout.LEADING, 10, 5));
JLabel flatToXmlSourceLbl = new JLabel("Source Flat File:");
flatToXmlSourceLbl.setFont(flatToXmlSourceLbl.getFont().deriveFont(Font.BOLD));
row1Pnl.add(flatToXmlSourceLbl);
final JTextField flatToXmlSourceFld = new JTextField(75);
row1Pnl.add(flatToXmlSourceFld);
JButton flatToXmlSourceBtn = new JButton("Browse...");
row1Pnl.add(flatToXmlSourceBtn);
pnl.add(row1Pnl);
JPanel row3Pnl = new JPanel();
row3Pnl.setOpaque(false);
row3Pnl.setBorder(null);
row3Pnl.setLayout(new FlowLayout(FlowLayout.LEADING, 10, 5));
JLabel flatToXmlFormatLbl = new JLabel("File Format:");
flatToXmlFormatLbl.setFont(flatToXmlFormatLbl.getFont().deriveFont(Font.BOLD));
flatToXmlFormatLbl.setPreferredSize(flatToXmlSourceLbl.getPreferredSize());
flatToXmlFormatLbl.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
row3Pnl.add(flatToXmlFormatLbl);
List<String> supportedFormat = new ArrayList<>(NaaccrFormat.getSupportedFormats());
supportedFormat.add("< none selected >");
Collections.sort(supportedFormat);
final JComboBox flatToXmlFormatBox = new JComboBox(supportedFormat.toArray(new String[supportedFormat.size()]));
row3Pnl.add(flatToXmlFormatBox);
row3Pnl.add(new JLabel(" (the format will be automatically set after you select a source file, if possible)"));
pnl.add(row3Pnl);
JPanel row2Pnl = new JPanel();
row2Pnl.setOpaque(false);
row2Pnl.setBorder(null);
row2Pnl.setLayout(new FlowLayout(FlowLayout.LEADING, 10, 5));
JLabel flatToXmlTargetLbl = new JLabel("Target XML File:");
flatToXmlTargetLbl.setFont(flatToXmlTargetLbl.getFont().deriveFont(Font.BOLD));
row2Pnl.add(flatToXmlTargetLbl);
final JTextField flatToXmlTargetFld = new JTextField(75);
row2Pnl.add(flatToXmlTargetFld);
JButton flatToXmlTargetBtn = new JButton("Browse...");
row2Pnl.add(flatToXmlTargetBtn);
pnl.add(row2Pnl);
JPanel row5Pnl = new JPanel();
row5Pnl.setOpaque(false);
row5Pnl.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));
row5Pnl.setLayout(new FlowLayout(FlowLayout.CENTER));
final JLabel flatToXmlResultLbl = new JLabel("Provide a value for the parameters and click the Process File button...");
flatToXmlResultLbl.setFont(flatToXmlResultLbl.getFont().deriveFont(Font.ITALIC));
row5Pnl.add(flatToXmlResultLbl);
pnl.add(row5Pnl);
JPanel row4Pnl = new JPanel();
row4Pnl.setOpaque(false);
row4Pnl.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0));
row4Pnl.setLayout(new FlowLayout(FlowLayout.CENTER));
final JButton flatToXmlProcessBtn = new JButton("Process File");
row4Pnl.add(flatToXmlProcessBtn);
pnl.add(row4Pnl);
flatToXmlSourceBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int returnVal = _fileChooser.showDialog(StandaloneFrame.this, "Select");
if (returnVal == JFileChooser.APPROVE_OPTION) {
flatToXmlSourceFld.setText(_fileChooser.getSelectedFile().getAbsolutePath());
String format = NaaccrXmlUtils.getFormatFromFlatFile(_fileChooser.getSelectedFile());
if (format != null)
flatToXmlFormatBox.setSelectedItem(format);
flatToXmlTargetFld.setText(invertFilename(_fileChooser.getSelectedFile()));
flatToXmlProcessBtn.requestFocusInWindow();
}
}
});
flatToXmlTargetBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int returnVal = _fileChooser.showDialog(StandaloneFrame.this, "Select");
if (returnVal == JFileChooser.APPROVE_OPTION)
flatToXmlTargetFld.setText(_fileChooser.getSelectedFile().getAbsolutePath());
}
});
flatToXmlProcessBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
File sourceFile = new File(flatToXmlSourceFld.getText());
File targetFile = new File(flatToXmlTargetFld.getText());
String format = (String)flatToXmlFormatBox.getSelectedItem();
flatToXmlResultLbl.setText("Processing file...");
pnl.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
int numRecords = NaaccrXmlUtils.flatToXml(sourceFile, targetFile, format, new NaaccrXmlOptions(), null);
flatToXmlResultLbl.setText("Done processing source flat file; processed " + numRecords + " records!");
}
catch (IOException | NaaccrValidationException ex) {
JOptionPane.showMessageDialog(StandaloneFrame.this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
flatToXmlResultLbl.setText("Provide a value for the parameters and click the Process File button...");
}
finally {
pnl.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
});
JPanel wrapperPnl = new JPanel(new BorderLayout());
wrapperPnl.setOpaque(true);
wrapperPnl.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.GRAY), BorderFactory.createEmptyBorder(10, 10, 10, 10)));
wrapperPnl.add(pnl, BorderLayout.NORTH);
return wrapperPnl;
}
private JPanel crateXmlToFlatPanel() {
final JPanel pnl = new JPanel();
pnl.setOpaque(false);
pnl.setBorder(null);
pnl.setLayout(new BoxLayout(pnl, BoxLayout.PAGE_AXIS));
JPanel row1Pnl = new JPanel();
row1Pnl.setOpaque(false);
row1Pnl.setBorder(null);
row1Pnl.setLayout(new FlowLayout(FlowLayout.LEADING, 10, 5));
JLabel xmlToFlatSourceLbl = new JLabel("Source XML File:");
xmlToFlatSourceLbl.setFont(xmlToFlatSourceLbl.getFont().deriveFont(Font.BOLD));
row1Pnl.add(xmlToFlatSourceLbl);
final JTextField xmlToFlatSourceFld = new JTextField(75);
row1Pnl.add(xmlToFlatSourceFld);
JButton xmlToFlatSourceBtn = new JButton("Browse...");
row1Pnl.add(xmlToFlatSourceBtn);
pnl.add(row1Pnl);
JPanel row2Pnl = new JPanel();
row2Pnl.setOpaque(false);
row2Pnl.setBorder(null);
row2Pnl.setLayout(new FlowLayout(FlowLayout.LEADING, 10, 5));
JLabel xmlToFlatFormatLbl = new JLabel("File Format:");
xmlToFlatFormatLbl.setFont(xmlToFlatFormatLbl.getFont().deriveFont(Font.BOLD));
xmlToFlatFormatLbl.setPreferredSize(xmlToFlatSourceLbl.getPreferredSize());
xmlToFlatFormatLbl.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
row2Pnl.add(xmlToFlatFormatLbl);
List<String> supportedFormat = new ArrayList<>(NaaccrFormat.getSupportedFormats());
supportedFormat.add("< none selected >");
Collections.sort(supportedFormat);
final JComboBox xmlToFlatFormatBox = new JComboBox(supportedFormat.toArray(new String[supportedFormat.size()]));
row2Pnl.add(xmlToFlatFormatBox);
row2Pnl.add(new JLabel(" (the format will be automatically set after you select a source file, if possible)"));
pnl.add(row2Pnl);
JPanel row3Pnl = new JPanel();
row3Pnl.setOpaque(false);
row3Pnl.setBorder(null);
row3Pnl.setLayout(new FlowLayout(FlowLayout.LEADING, 10, 5));
JLabel xmlToFlatTargetLbl = new JLabel("Target Flat File:");
xmlToFlatTargetLbl.setFont(xmlToFlatTargetLbl.getFont().deriveFont(Font.BOLD));
row3Pnl.add(xmlToFlatTargetLbl);
final JTextField xmlToFlatTargetFld = new JTextField(75);
row3Pnl.add(xmlToFlatTargetFld);
JButton xmlToFlatTargetBtn = new JButton("Browse...");
row3Pnl.add(xmlToFlatTargetBtn);
pnl.add(row3Pnl);
JPanel row4Pnl = new JPanel();
row4Pnl.setOpaque(false);
row4Pnl.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));
row4Pnl.setLayout(new FlowLayout(FlowLayout.CENTER));
final JLabel xmlToFlatResultLbl = new JLabel("Provide a value for the parameters and click the Process File button...");
xmlToFlatResultLbl.setFont(xmlToFlatResultLbl.getFont().deriveFont(Font.ITALIC));
row4Pnl.add(xmlToFlatResultLbl);
pnl.add(row4Pnl);
JPanel row5Pnl = new JPanel();
row5Pnl.setOpaque(false);
row5Pnl.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0));
row5Pnl.setLayout(new FlowLayout(FlowLayout.CENTER));
final JButton xmlToFlatProcessBtn = new JButton("Process File");
row5Pnl.add(xmlToFlatProcessBtn);
pnl.add(row5Pnl);
xmlToFlatSourceBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int returnVal = _fileChooser.showDialog(StandaloneFrame.this, "Select");
if (returnVal == JFileChooser.APPROVE_OPTION) {
xmlToFlatSourceFld.setText(_fileChooser.getSelectedFile().getAbsolutePath());
String format = NaaccrXmlUtils.getFormatFromXmlFile(_fileChooser.getSelectedFile());
if (format != null)
xmlToFlatFormatBox.setSelectedItem(format);
xmlToFlatTargetFld.setText(invertFilename(_fileChooser.getSelectedFile()));
xmlToFlatProcessBtn.requestFocusInWindow();
}
}
});
xmlToFlatTargetBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int returnVal = _fileChooser.showDialog(StandaloneFrame.this, "Select");
if (returnVal == JFileChooser.APPROVE_OPTION)
xmlToFlatTargetFld.setText(_fileChooser.getSelectedFile().getAbsolutePath());
}
});
xmlToFlatProcessBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
File sourceFile = new File(xmlToFlatSourceFld.getText());
File targetFile = new File(xmlToFlatTargetFld.getText());
String format = (String)xmlToFlatFormatBox.getSelectedItem();
xmlToFlatResultLbl.setText("Processing file...");
pnl.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
int numRecords = NaaccrXmlUtils.xmlToFlat(sourceFile, targetFile, format, new NaaccrXmlOptions(), null);
xmlToFlatResultLbl.setText("Done processing source XML file; processed " + numRecords + " tumors!");
}
catch (IOException | NaaccrValidationException ex) {
JOptionPane.showMessageDialog(StandaloneFrame.this, ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
xmlToFlatResultLbl.setText("Provide a value for the parameters and click the Process File button...");
}
finally {
pnl.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
}
});
JPanel wrapperPnl = new JPanel(new BorderLayout());
wrapperPnl.setOpaque(true);
wrapperPnl.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.GRAY), BorderFactory.createEmptyBorder(10, 10, 10, 10)));
wrapperPnl.add(pnl, BorderLayout.NORTH);
return wrapperPnl;
}
private JPanel crateValidationTestPanel() {
JPanel pnl = new JPanel(new BorderLayout());
pnl.setOpaque(true);
pnl.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.GRAY), BorderFactory.createEmptyBorder(10, 10, 10, 10)));
JPanel disclaimerPnl = new JPanel(new FlowLayout(FlowLayout.LEADING));
disclaimerPnl.setOpaque(false);
disclaimerPnl.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0));
JLabel disclaimerLbl = new JLabel("Modify the XML to introduce some errors, and click the Validate button to see the errors.");
disclaimerLbl.setFont(disclaimerLbl.getFont().deriveFont(Font.BOLD));
disclaimerPnl.add(disclaimerLbl);
pnl.add(disclaimerPnl, BorderLayout.NORTH);
JPanel textPnl = new JPanel(new BorderLayout());
textPnl.setOpaque(false);
textPnl.setBorder(null);
final JTextArea textFld = new JTextArea();
StringWriter writer = new StringWriter();
try (InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("testing-template.xml")) {
IOUtils.copy(inputStream, writer, "UTF-8");
textFld.setText(writer.toString());
}
catch (IOException e) {
textFld.setText("Unexpected error reading template file...");
}
textPnl.add(new JScrollPane(textFld), BorderLayout.CENTER);
pnl.add(textPnl, BorderLayout.CENTER);
JPanel validationPnl = new JPanel(new BorderLayout());
validationPnl.setOpaque(false);
validationPnl.setBorder(null);
JPanel buttonPnl = new JPanel(new GridBagLayout());
buttonPnl.setBorder(BorderFactory.createEmptyBorder(10, 0, 10, 10));
JButton validateBtn = new JButton(" Validate ");
buttonPnl.add(validateBtn);
validationPnl.add(buttonPnl, BorderLayout.NORTH);
final JTextArea errorsFld = new JTextArea();
errorsFld.setRows(10);
validationPnl.add(new JScrollPane(errorsFld), BorderLayout.CENTER);
pnl.add(validationPnl, BorderLayout.SOUTH);
validateBtn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
errorsFld.setText(null);
String format = NaaccrXmlUtils.getFormatFromXmlReader(new StringReader(textFld.getText()));
if (format == null)
format = NaaccrFormat.NAACCR_FORMAT_14_ABSTRACT; // TODO this should be an error
RuntimeNaaccrDictionary dictionary = new RuntimeNaaccrDictionary(format, NaaccrXmlUtils.getStandardDictionary(), null);
try (PatientXmlReader reader = new PatientXmlReader(new StringReader(textFld.getText()), NaaccrXmlUtils.getStandardXStream(dictionary, new NaaccrXmlOptions()))) {
do {
Patient patient = reader.readPatient();
if (patient == null)
break;
for (NaaccrValidationError error : patient.getAllValidationErrors()) {
errorsFld.setForeground(new Color(125, 0, 0));
if (!errorsFld.getText().isEmpty())
errorsFld.append("\n");
errorsFld.append("Line #" + error.getLineNumber() + ": DATA validation error\n");
errorsFld.append(" message: " + (error.getMessage() == null ? "<not available>" : error.getMessage()) + "\n");
errorsFld.append(" path: " + (error.getPath() == null ? "<not available>" : error.getPath()) + "\n");
errorsFld.append(" item ID: " + (error.getNaaccrId() == null ? "<not available>" : error.getNaaccrId()) + "\n");
errorsFld.append(" item #: " + (error.getNaaccrNum() == null ? "<not available>" : error.getNaaccrNum()) + "\n");
errorsFld.append(" value: " + (error.getValue() == null ? "<blank>" : error.getValue()) + "\n");
}
}
while (true);
if (errorsFld.getText().isEmpty()) {
errorsFld.append("Reading completed; found no error.");
errorsFld.setForeground(new Color(0, 115, 0));
}
}
catch (NaaccrValidationException error) {
errorsFld.setForeground(new Color(125, 0, 0));
if (!errorsFld.getText().isEmpty())
errorsFld.append("\n");
errorsFld.append("Line " + (error.getLineNumber() == null ? "?" : ("#" + error.getLineNumber())) + ": SYNTAX validation error\n");
errorsFld.append(" message: " + (error.getMessage() == null ? "<not available>" : error.getMessage()) + "\n");
errorsFld.append(" path: " + (error.getPath() == null ? "<not available>" : error.getPath()) + "\n");
errorsFld.append(" item ID: <not available>\n");
errorsFld.append(" item #: <not available>\n");
errorsFld.append(" value: <not available>\n");
errorsFld.append("\nReading interrupted because of a syntax error...");
}
catch (IOException ex) {
errorsFld.setForeground(new Color(125, 0, 0));
errorsFld.append("Unexpected error:\n");
errorsFld.append(" -> " + ex.getMessage() + "\n");
errorsFld.append("Reading interrupted...");
}
errorsFld.setCaretPosition(0);
}
});
return pnl;
}
private JPanel crateDictionaryPanel() {
JPanel pnl = new JPanel(new BorderLayout());
pnl.setOpaque(true);
pnl.setBorder(BorderFactory.createLineBorder(Color.GRAY));
JTextArea area = new JTextArea();
area.setEditable(false);
try {
area.setText(IOUtils.toString(Thread.currentThread().getContextClassLoader().getResourceAsStream("naaccr-dictionary-140.xml"), "UTF-8"));
}
catch (IOException e) {
area.setText("Unable to read dictionary...");
}
JScrollPane pane = new JScrollPane(area);
pane.setBorder(null);
pnl.add(pane, BorderLayout.CENTER);
return pnl;
}
}
} |
package org.narwhal.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The <code>Column</code> annotation marks particular
* field of the class which maps on the column of the database table.
*
* @author Miron Aseev
*/
@Target(value = ElementType.FIELD)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Column {
/**
* Returns database column name.
*
* @return Database column name.
* */
String value();
/**
* Checks whether a class field is a primary key or not.
*
* @return True if class field is a primary key. False otherwise.
* */
boolean primaryKey() default false;
} |
package org.openflow.protocol;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.LinkedList;
import java.util.ArrayList;
import org.openflow.util.HexString;
import org.openflow.util.U8;
import org.openflow.util.U16;
import org.openflow.util.U32;
/**
* Represents an ofp_match structure
*
* @author Srini Seetharaman (srini.seetharaman@gmail.com)
*
*/
public class OFMatch implements Cloneable {
public static int MINIMUM_LENGTH = 8;
public static final short ETH_TYPE_IPV4 = (short)0x800;
public static final short ETH_TYPE_IPV6 = (short)0x86dd;
public static final short ETH_TYPE_ARP = (short)0x806;
public static final short ETH_TYPE_VLAN = (short)0x8100;
public static final short ETH_TYPE_LLDP = (short)0x88cc;
public static final short ETH_TYPE_MPLS_UNICAST = (short)0x8847;
public static final short ETH_TYPE_MPLS_MULTICAST = (short)0x8848;
public static final byte IP_PROTO_ICMP = 0x1;
public static final byte IP_PROTO_TCP = 0x6;
public static final byte IP_PROTO_UDP = 0x11;
public static final byte IP_PROTO_SCTP = (byte)0x84;
enum OFMatchType {
STANDARD, OXM
}
// Note: Only supporting OXM and OpenFlow_Basic matches
public enum OFMatchClass {
NXM_0 ((short)0x0000),
NXM_1 ((short)0x0001),
OPENFLOW_BASIC ((short)0x8000),
VENDOR ((short)0xffff);
protected short value;
private OFMatchClass(short value) {
this.value = value;
}
/**
* @return the value
*/
public short getValue() {
return value;
}
}
protected OFMatchType type;
protected short length; //total length including padding
protected short matchLength; // length excluding padding
protected List<OFMatchField> matchFields;
/**
* By default, create a OFMatch that matches everything
* (mostly because it's the least amount of work to make a valid OFMatch)
*/
public OFMatch() {
this.type = OFMatchType.OXM;
this.length = U16.t(MINIMUM_LENGTH);
this.matchLength = 4; //No padding
this.matchFields = new ArrayList<OFMatchField>();
}
/**
* Get value of particular field
* @return
*/
public Object getMatchFieldValue(OFOXMFieldType matchType) {
for (OFMatchField matchField: matchFields) {
if (matchField.getOXMFieldType() == matchType)
return matchField.getOXMFieldValue();
}
throw new IllegalArgumentException("No match exists for matchfield " + matchType.getFieldName());
}
/**
* Get mask of particular field
* @return
*/
public Object getMatchFieldMask(OFOXMFieldType matchType) {
for (OFMatchField matchField: matchFields) {
if (matchField.getOXMFieldType() == matchType)
return matchField.getOXMFieldMask();
}
throw new IllegalArgumentException("No match exists for matchfield " + matchType.getFieldName());
}
/**
* Get in_port
* @return integer
*/
public int getInPort() {
return (Integer)getMatchFieldValue(OFOXMFieldType.IN_PORT);
}
/**
* Set in_port in match
* @param in_port
*/
public OFMatch setInPort(int inPort) {
this.setField(OFOXMFieldType.IN_PORT, inPort);
return this;
}
/**
* Get dl_dst
*
* @return an arrays of bytes
*/
public byte[] getDataLayerDestination() {
return (byte[])getMatchFieldValue(OFOXMFieldType.ETH_DST);
}
/**
* Set dl_dst
*
* @param dataLayerDestination
*/
public OFMatch setDataLayerDestination(byte[] dataLayerDestination) {
this.setField(OFOXMFieldType.ETH_DST, dataLayerDestination);
return this;
}
/**
* Set dl_dst, but first translate to byte[] using HexString
*
* @param mac
* A colon separated string of 6 pairs of octets, e..g.,
* "00:17:42:EF:CD:8D"
*/
public OFMatch setDataLayerDestination(String mac) {
byte bytes[] = HexString.fromHexString(mac);
if (bytes.length != OFPhysicalPort.OFP_ETH_ALEN)
throw new IllegalArgumentException("expected string with 6 octets, got '" + mac + "'");
this.setField(OFOXMFieldType.ETH_DST, bytes);
return this;
}
/**
* Get dl_src
*
* @return an array of bytes
*/
public byte[] getDataLayerSource() {
return (byte[])getMatchFieldValue(OFOXMFieldType.ETH_SRC);
}
/**
* Set dl_src
*
* @param dataLayerSource
*/
public OFMatch setDataLayerSource(byte[] dataLayerSource) {
this.setField(OFOXMFieldType.ETH_SRC, dataLayerSource);
return this;
}
/**
* Set dl_src, but first translate to byte[] using HexString
*
* @param mac
* A colon separated string of 6 pairs of octets, e..g.,
* "00:17:42:EF:CD:8D"
*/
public OFMatch setDataLayerSource(String mac) {
byte bytes[] = HexString.fromHexString(mac);
if (bytes.length != OFPhysicalPort.OFP_ETH_ALEN)
throw new IllegalArgumentException("expected string with 6 octets, got '" + mac + "'");
this.setField(OFOXMFieldType.ETH_SRC, bytes);
return this;
}
/**
* Get dl_type
*
* @return ether_type
*/
public short getDataLayerType() {
return (Short)getMatchFieldValue(OFOXMFieldType.ETH_TYPE);
}
/**
* Set dl_type
*
* @param dataLayerType
*/
public OFMatch setDataLayerType(short dataLayerType) {
this.setField(OFOXMFieldType.ETH_TYPE, dataLayerType);
return this;
}
/**
* Get dl_vlan
*
* @return vlan tag without the VLAN present bit set
*/
public short getDataLayerVirtualLan() {
try {
return (short)((Short)getMatchFieldValue(OFOXMFieldType.VLAN_VID) & 0xFFF);
} catch (IllegalArgumentException e) {
return OFVlanId.OFPVID_NONE.getValue();
}
}
/**
* Set dl_vlan
*
* @param dataLayerVirtualLan VLAN ID without the VLAN present bit set
*/
public OFMatch setDataLayerVirtualLan(short vlan) {
this.setField(OFOXMFieldType.VLAN_VID, vlan | OFVlanId.OFPVID_PRESENT.getValue());
return this;
}
/**
* Get dl_vlan_pcp
*
* @return VLAN PCP value
*/
public byte getDataLayerVirtualLanPriorityCodePoint() {
try {
return (Byte) getMatchFieldValue(OFOXMFieldType.VLAN_PCP);
} catch (IllegalArgumentException e) {
return 0;
}
}
/**
* Set dl_vlan_pcp
*
* @param pcp
*/
public OFMatch setDataLayerVirtualLanPriorityCodePoint(byte pcp) {
this.setField(OFOXMFieldType.VLAN_VID, pcp);
return this;
}
/**
* Get nw_proto
*
* @return
*/
public byte getNetworkProtocol() {
return (Byte)getMatchFieldValue(OFOXMFieldType.IP_PROTO);
}
/**
* Set nw_proto
*
* @param networkProtocol
*/
public OFMatch setNetworkProtocol(byte networkProtocol) {
this.setField(OFOXMFieldType.IP_PROTO, networkProtocol);
return this;
}
/**
* Get nw_tos OFMatch stores the ToS bits as 6-bits in the lower significant bits
*
* @return : 6-bit DSCP value (0-63)
*/
public byte getNetworkTypeOfService() {
try {
return (byte)((Byte)getMatchFieldValue(OFOXMFieldType.IP_DSCP) & 0x3f);
} catch (IllegalArgumentException e) {
return 0;
}
}
/**
* Set nw_tos OFMatch stores the ToS bits as lower 6-bits
*
* @param networkTypeOfService TOS value including ECN in the lower 2 bits
* : 6-bit DSCP value (0-63)
*/
public OFMatch setNetworkTypeOfService(byte networkTypeOfService) {
this.setField(OFOXMFieldType.IP_DSCP, (byte)((networkTypeOfService >> 2) & 0x3f));
this.setField(OFOXMFieldType.IP_ECN, (byte)(networkTypeOfService & 0x3));
return this;
}
/**
* Get nw_dst
*
* @return integer destination IP address
*/
public int getNetworkDestination() {
return (Integer)getMatchFieldValue(OFOXMFieldType.IPV4_DST);
}
/**
* Get nw_dst mask
*
* @return integer destination IP address mask
*/
public int getNetworkDestinationMask() {
Object mask = getMatchFieldMask(OFOXMFieldType.IPV4_DST);
if (mask == null)
return 0;
else
return (Integer)mask;
}
/**
* Set nw_dst
*
* @param networkDestination destination IP address
*/
public OFMatch setNetworkDestination(int networkDestination) {
setNetworkDestination(ETH_TYPE_IPV4, networkDestination);
return this;
}
/**
* Set nw_dst
*
* @param dataLayerType ether type
* @param networkDestination destination IP address
*/
public OFMatch setNetworkDestination(short dataLayerType, int networkDestination) {
switch (dataLayerType) {
case ETH_TYPE_IPV4:
this.setField(OFOXMFieldType.IPV4_DST, networkDestination);
break;
case ETH_TYPE_IPV6:
this.setField(OFOXMFieldType.IPV6_DST, networkDestination);
break;
case ETH_TYPE_ARP:
this.setField(OFOXMFieldType.ARP_THA, networkDestination);
break;
}
return this;
}
/**
* Get nw_src
*
* @return integer source IP address
*/
// TODO: Add support for IPv6
public int getNetworkSource() {
return (Integer)getMatchFieldValue(OFOXMFieldType.IPV4_SRC);
}
/**
* Get nw_src mask
*
* @return integer source IP address mask
*/
public int getNetworkSourceMask() {
Object mask = getMatchFieldMask(OFOXMFieldType.IPV4_SRC);
if (mask == null)
return 0;
else
return (Integer)mask;
}
/**
* Set nw_src
*
* @param networkSource source IP address
*/
// TODO: Add support for IPv6
public OFMatch setNetworkSource(int networkSource) {
setNetworkSource(ETH_TYPE_IPV4, networkSource);
return this;
}
/**
* Set nw_src
*
* @param dataLayerType ether type
* @param networkSource source IP address
*/
// TODO: Add support for IPv6
public OFMatch setNetworkSource(short dataLayerType, int networkSource) {
switch (dataLayerType) {
case ETH_TYPE_IPV4:
this.setField(OFOXMFieldType.IPV4_SRC, networkSource);
break;
case ETH_TYPE_ARP:
this.setField(OFOXMFieldType.ARP_SHA, networkSource);
break;
}
return this;
}
/**
* Get tp_dst
*
* @return destination port number
*/
public short getTransportDestination() {
byte networkProtocol = getNetworkProtocol();
switch (networkProtocol) {
case IP_PROTO_TCP:
return (Short)getMatchFieldValue(OFOXMFieldType.TCP_DST);
case IP_PROTO_UDP:
return (Short)getMatchFieldValue(OFOXMFieldType.UDP_DST);
case IP_PROTO_SCTP:
return (Short)getMatchFieldValue(OFOXMFieldType.SCTP_DST);
}
throw new IllegalArgumentException("Network Protocol invalid for extracting port number");
}
/**
* Set tp_dst
*
* @param transportDestination TCP destination port number
*/
public OFMatch setTransportDestination(short transportDestination) {
setTransportSource(IP_PROTO_TCP, transportDestination);
return this;
}
/**
* Set tp_dst
*
* @param networkProtocol IP protocol
* @param transportDestination Destination Transport port number
*/
public OFMatch setTransportDestination(byte networkProtocol, short transportDestination) {
switch (networkProtocol) {
case IP_PROTO_TCP:
this.setField(OFOXMFieldType.TCP_DST, transportDestination);
break;
case IP_PROTO_UDP:
this.setField(OFOXMFieldType.UDP_DST, transportDestination);
break;
case IP_PROTO_SCTP:
this.setField(OFOXMFieldType.SCTP_DST, transportDestination);
break;
}
return this;
}
/**
* Get tp_src
*
* @return transportSource Source Transport port number
*/
public short getTransportSource() {
byte networkProtocol = getNetworkProtocol();
switch (networkProtocol) {
case IP_PROTO_TCP:
return (Short)getMatchFieldValue(OFOXMFieldType.TCP_SRC);
case IP_PROTO_UDP:
return (Short)getMatchFieldValue(OFOXMFieldType.UDP_SRC);
case IP_PROTO_SCTP:
return (Short)getMatchFieldValue(OFOXMFieldType.SCTP_SRC);
}
throw new IllegalArgumentException("Network Protocol invalid for extracting port number");
}
/**
* Set tp_src
*
* @param transportSource TCP source port number
*/
public OFMatch setTransportSource(short transportSource) {
setTransportSource(IP_PROTO_TCP, transportSource);
return this;
}
/**
* Set tp_src
*
* @param networkProtocol IP protocol
* @param transportSource Source Transport port number
*/
public OFMatch setTransportSource(byte networkProtocol, short transportSource) {
switch (networkProtocol) {
case IP_PROTO_TCP:
this.setField(OFOXMFieldType.TCP_SRC, transportSource);
break;
case IP_PROTO_UDP:
this.setField(OFOXMFieldType.UDP_SRC, transportSource);
break;
case IP_PROTO_SCTP:
this.setField(OFOXMFieldType.SCTP_SRC, transportSource);
break;
}
return this;
}
public OFMatchType getType() {
return type;
}
/**
* Get the length of this message
* @return length
*/
public short getLength() {
return length;
}
/**
* Get the length of this message, unsigned
* @return unsigned length
*/
public int getLengthU() {
return U16.f(length);
}
public short getMatchLength() {
return matchLength;
}
/** Sets match field. In case of existing field, checks for existing value
*
* @param matchField Check for uniqueness of field and add matchField
*/
public void setField(OFMatchField newMatchField) {
if (this.matchFields == null)
this.matchFields = new ArrayList<OFMatchField>();
for (OFMatchField matchField: this.matchFields) {
if (matchField.getOXMFieldType() == newMatchField.getOXMFieldType()) {
matchField.setOXMFieldValue(newMatchField.getOXMFieldValue());
matchField.setOXMFieldMask(newMatchField.getOXMFieldMask());
return;
}
}
this.matchFields.add(newMatchField);
this.matchLength += newMatchField.getOXMFieldLength();
this.length = U16.t(8*((this.matchLength + 7)/8)); //includes padding
}
public void setField(OFOXMFieldType matchFieldType, Object matchFieldValue) {
OFMatchField matchField = new OFMatchField(matchFieldType, matchFieldValue);
setField(matchField);
}
public void setField(OFOXMFieldType matchFieldType, Object matchFieldValue, Object matchFieldMask) {
OFMatchField matchField = new OFMatchField(matchFieldType, matchFieldValue, matchFieldMask);
setField(matchField);
}
/**
* Returns read-only copies of the matchfields contained in this OFMatch
* @return a list of ordered OFMatchField objects
*/
public List<OFMatchField> getMatchFields() {
return this.matchFields;
}
/**
* Sets the list of matchfields this OFMatch contains
* @param matchFields a list of ordered OFMatchField objects
*/
public OFMatch setMatchFields(List<OFMatchField> matchFields) {
this.matchFields = matchFields;
//Recalculate lengths
this.matchLength = 4; //No padding
for (OFMatchField newMatchField: this.matchFields)
this.matchLength += newMatchField.getOXMFieldLength();
this.length = U16.t(8*((this.matchLength + 7)/8)); //includes padding
return this;
}
/**
* Utility function to wildcard all fields except those specified in list
* @param nonWildcardedFieldTypes list of match field types preserved,
* if null all fields are wildcarded
*/
public OFMatch setNonWildcards(List<OFOXMFieldType> nonWildcardedFieldTypes) {
List <OFMatchField> newMatchFields = new ArrayList<OFMatchField>();
if (nonWildcardedFieldTypes != null) {
for (OFMatchField matchField: matchFields) {
OFOXMFieldType type = matchField.getOXMFieldType();
if (nonWildcardedFieldTypes.contains(type))
newMatchFields.add(matchField);
}
}
setMatchFields(newMatchFields);
return this;
}
public void readFrom(ByteBuffer data) {
byte[] dataLayerAddress = new byte[OFPhysicalPort.OFP_ETH_ALEN];
byte[] dataLayerAddressMask = new byte[OFPhysicalPort.OFP_ETH_ALEN];
int networkAddress;
int networkAddressMask;
int wildcards;
short dataLayerType = 0;
byte networkProtocol = 0;
byte networkTOS;
short transportNumber;
int mplsLabel;
byte mplsTC;
this.type = OFMatchType.values()[data.getShort()];
this.length = data.getShort();
int remaining = this.getLengthU() - 4; //length - sizeof(type and length)
int end = data.position() + remaining; //includes padding in case of STANDARD match
if (type == OFMatchType.OXM) {
int padLength = 8*((length + 7)/8) - length;
end += padLength; // including pad
if (data.remaining() < remaining)
remaining = data.remaining();
this.matchFields = new ArrayList<OFMatchField>();
while (remaining >= OFMatchField.MINIMUM_LENGTH) {
OFMatchField matchField = new OFMatchField();
matchField.readFrom(data);
this.matchFields.add(matchField);
remaining -= U32.f(matchField.getOXMFieldLength()+4); //value length + header length
}
} else {
this.setField(OFOXMFieldType.IN_PORT, data.getInt());
wildcards = data.getInt();
if ((wildcards & OFMatchWildcardMask.ALL.getValue()) == 0) {
data.position(end);
return;
}
data.get(dataLayerAddress);
data.get(dataLayerAddressMask);
this.setField(OFOXMFieldType.ETH_SRC, dataLayerAddress.clone(), dataLayerAddressMask.clone());
data.get(dataLayerAddress);
data.get(dataLayerAddressMask);
this.setField(OFOXMFieldType.ETH_DST, dataLayerAddress.clone(), dataLayerAddressMask.clone());
if ((wildcards & OFMatchWildcardMask.DL_VLAN.getValue()) == 0)
setDataLayerVirtualLan(data.getShort());
else
data.getShort(); //skip
if ((wildcards & OFMatchWildcardMask.DL_VLAN_PCP.getValue()) == 0)
setDataLayerVirtualLanPriorityCodePoint(data.get());
else
data.get(); //skip
data.get(); //pad
if ((wildcards & OFMatchWildcardMask.DL_TYPE.getValue()) == 0) {
dataLayerType = data.getShort();
setDataLayerType(dataLayerType);
} else
data.getShort(); //skip
if ((dataLayerType != ETH_TYPE_IPV4) && (dataLayerType != ETH_TYPE_ARP) && (dataLayerType != ETH_TYPE_VLAN) &&
(dataLayerType != ETH_TYPE_MPLS_UNICAST) && (dataLayerType != ETH_TYPE_MPLS_MULTICAST)) {
data.position(end);
return;
}
if ((wildcards & OFMatchWildcardMask.NW_TOS.getValue()) == 0) {
networkTOS = data.get();
setNetworkTypeOfService(networkTOS);
} else
data.get(); //skip
if ((wildcards & OFMatchWildcardMask.NW_PROTO.getValue()) == 0) {
networkProtocol = data.get();
setNetworkProtocol(networkProtocol);
} else
data.get(); //skip
networkAddress = data.getInt();
networkAddressMask = data.getInt();
if (networkAddress != 0)
this.setField(OFOXMFieldType.IPV4_SRC, networkAddress, networkAddressMask);
networkAddress = data.getInt();
networkAddressMask = data.getInt();
if (networkAddress != 0)
this.setField(OFOXMFieldType.IPV4_DST, networkAddress, networkAddressMask);
transportNumber = data.getShort();
if ((wildcards & OFMatchWildcardMask.TP_SRC.getValue()) == 0) {
setTransportSource(networkProtocol, transportNumber);
}
transportNumber = data.getShort();
if ((wildcards & OFMatchWildcardMask.TP_DST.getValue()) == 0) {
setTransportDestination(networkProtocol, transportNumber);
}
mplsLabel = data.getInt();
mplsTC = data.get();
if ((dataLayerType == ETH_TYPE_MPLS_UNICAST) ||
(dataLayerType == ETH_TYPE_MPLS_MULTICAST)) {
if ((wildcards & OFMatchWildcardMask.MPLS_LABEL.getValue()) == 0)
this.setField(OFOXMFieldType.MPLS_LABEL, mplsLabel);
if ((wildcards & OFMatchWildcardMask.MPLS_TC.getValue()) == 0)
this.setField(OFOXMFieldType.MPLS_TC, mplsTC);
}
data.get(); //pad
data.get(); //pad
data.get(); //pad
this.setField(OFOXMFieldType.METADATA, data.getLong(), data.getLong());
}
data.position(end);
}
public void writeTo(ByteBuffer data) {
short matchLength = getMatchLength();
data.putShort((short)this.type.ordinal());
data.putShort(matchLength); //length does not include padding
for (OFMatchField matchField : matchFields)
matchField.writeTo(data);
int padLength = 8*((matchLength + 7)/8) - matchLength;
for (;padLength>0;padLength
data.put((byte)0); //pad
}
public int hashCode() {
final int prime = 227;
int result = 1;
result = prime * result + ((matchFields == null) ? 0 : matchFields.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof OFMatchField)) {
return false;
}
OFMatch other = (OFMatch) obj;
if (matchFields == null) {
if (other.matchFields != null)
return false;
} else if (!matchFields.equals(other.matchFields)) {
return false;
}
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#clone()
*/
@Override
public OFMatch clone() {
OFMatch match = new OFMatch();
try {
List<OFMatchField> neoMatchFields = new LinkedList<OFMatchField>();
for(OFMatchField matchField: this.matchFields)
neoMatchFields.add((OFMatchField) matchField.clone());
match.setMatchFields(neoMatchFields);
return match;
} catch (CloneNotSupportedException e) {
// Won't happen
throw new RuntimeException(e);
}
}
/**
* Load and return a new OFMatch based on supplied packetData, see
* {@link #loadFromPacket(byte[], short)} for details.
*
* @param packetData
* @param inputPort
* @return
*/
public static OFMatch load(byte[] packetData, int inPort) {
OFMatch ofm = new OFMatch();
return ofm.loadFromPacket(packetData, inPort);
}
/**
* Initializes this OFMatch structure with the corresponding data from the
* specified packet.
*
* Must specify the input port, to ensure that this.in_port is set
* correctly.
*
* Specify OFPort.NONE or OFPort.ANY if input port not applicable or
* available
*
* @param packetData
* The packet's data
* @param inputPort
* the port the packet arrived on
*/
public OFMatch loadFromPacket(byte[] packetData, int inPort) {
short scratch;
byte[] dataLayerAddress = new byte[OFPhysicalPort.OFP_ETH_ALEN];
short dataLayerType = 0;
byte networkProtocol = 0;
int transportOffset = 34;
ByteBuffer packetDataBB = ByteBuffer.wrap(packetData);
int limit = packetDataBB.limit();
setInPort(inPort);
//TODO: Extend to support more packet types
assert (limit >= 14);
// dl dst
packetDataBB.get(dataLayerAddress);
setDataLayerDestination(dataLayerAddress.clone());
// dl src
packetDataBB.get(dataLayerAddress);
setDataLayerSource(dataLayerAddress.clone());
// dl type
dataLayerType = packetDataBB.getShort();
setDataLayerType(dataLayerType);
if (dataLayerType == (short) ETH_TYPE_VLAN) { // need cast to avoid signed
// has vlan tag
scratch = packetDataBB.getShort();
setDataLayerVirtualLan((short) (0xfff & scratch));
setDataLayerVirtualLanPriorityCodePoint((byte) ((0xe000 & scratch) >> 13));
dataLayerType = packetDataBB.getShort();
}
//TODO: Add support for IPv6
switch (dataLayerType) {
case ETH_TYPE_IPV4: // ipv4
// check packet length
scratch = packetDataBB.get();
scratch = (short) (0xf & scratch);
transportOffset = (packetDataBB.position() - 1) + (scratch * 4);
// nw tos (dscp and ecn)
setNetworkTypeOfService(packetDataBB.get());
// nw protocol
packetDataBB.position(packetDataBB.position() + 7);
networkProtocol = packetDataBB.get();
setNetworkProtocol(networkProtocol);
// nw src
packetDataBB.position(packetDataBB.position() + 2);
setNetworkSource(dataLayerType, packetDataBB.getInt());
// nw dst
setNetworkDestination(dataLayerType, packetDataBB.getInt());
packetDataBB.position(transportOffset);
break;
case ETH_TYPE_ARP: // arp
int arpPos = packetDataBB.position();
// opcode
scratch = packetDataBB.getShort(arpPos + 6);
this.setField(OFOXMFieldType.ARP_OP, ((short) (0xff & scratch)));
scratch = packetDataBB.getShort(arpPos + 2);
// if ipv4 and addr len is 4
if (scratch == 0x800 && packetDataBB.get(arpPos + 5) == 4) {
// nw src
this.setField(OFOXMFieldType.ARP_SPA, packetDataBB.getInt(arpPos + 14));
// nw dst
this.setField(OFOXMFieldType.ARP_TPA, packetDataBB.getInt(arpPos + 24));
}
return this;
default: //No OXM field added
return this;
}
switch (networkProtocol) {
case IP_PROTO_ICMP:
// icmp type
this.setField(OFOXMFieldType.ICMPV4_TYPE, packetDataBB.get());
// code
this.setField(OFOXMFieldType.ICMPV4_CODE, packetDataBB.get());
break;
case IP_PROTO_TCP:
case IP_PROTO_UDP:
case IP_PROTO_SCTP:
setTransportSource(networkProtocol, packetDataBB.getShort());
setTransportDestination(networkProtocol, packetDataBB.getShort());
break;
default:
break;
}
return this;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "OFMatch [type=" + type + "length=" + length + "matchFields=" + matchFields + "]";
}
private void setNetworkAddressFromCIDR(OFMatch m, String cidr, OFOXMFieldType which)
throws IllegalArgumentException {
String values[] = cidr.split("/");
String[] ip_str = values[0].split("\\.");
int ip = 0;
ip += Integer.valueOf(ip_str[0]) << 24;
ip += Integer.valueOf(ip_str[1]) << 16;
ip += Integer.valueOf(ip_str[2]) << 8;
ip += Integer.valueOf(ip_str[3]);
int prefix = 32; // all bits are fixed, by default
if (values.length >= 2)
prefix = Integer.valueOf(values[1]);
int mask = (Integer.MAX_VALUE - 1) << (32 - prefix);
m.setField(which, ip, mask);
}
public OFMatch fromString(String match) throws IllegalArgumentException {
OFMatch m = new OFMatch();
if (match.equals("") || match.equalsIgnoreCase("any")
|| match.equalsIgnoreCase("all") || match.equals("[]"))
match = "OFMatch[]";
String[] tokens = match.split("[\\[,\\]]");
String[] values;
byte networkProtocol = 0;
int initArg = 0;
if (tokens[0].equals("OFMatch"))
initArg = 1;
int i;
for (i = initArg; i < tokens.length; i++) {
values = tokens[i].split("=");
if (values.length != 2)
throw new IllegalArgumentException(
"Token " + tokens[i]
+ " does not have form 'key=value' parsing "
+ match);
values[0] = values[0].toLowerCase(); // try to make this case insensitive
if (values[0].equals(OFOXMFieldType.IN_PORT.getFieldName())
|| values[0].equals("input_port")) {
m.setInPort(U16.t(Integer.valueOf(values[1])));
} else if (values[0].equals(OFOXMFieldType.ETH_DST.getFieldName())
|| values[0].equals("dl_dst")) {
m.setDataLayerDestination(HexString.fromHexString(values[1]));
} else if (values[0].equals(OFOXMFieldType.ETH_SRC.getFieldName())
|| values[0].equals("dl_src")) {
m.setDataLayerSource(HexString.fromHexString(values[1]));
} else if (values[0].equals(OFOXMFieldType.ETH_TYPE.getFieldName())
|| values[0].equals("dl_type")) {
if (values[1].startsWith("0x"))
m.setDataLayerType(U16.t(Integer.valueOf(values[1].replaceFirst("0x", ""), 16)));
else
m.setDataLayerType(U16.t(Integer.valueOf(values[1])));
} else if (values[0].equals(OFOXMFieldType.VLAN_VID.getFieldName())
|| values[0].equals("dl_vlan")) {
if (values[1].startsWith("0x"))
m.setDataLayerVirtualLan(U16.t(Integer.valueOf(values[1].replaceFirst("0x", ""), 16)));
else
m.setDataLayerVirtualLan(U16.t(Integer.valueOf(values[1])));
} else if (values[0].equals(OFOXMFieldType.VLAN_PCP.getFieldName())
|| values[0].equals("dl_vlan_pcp")) {
m.setDataLayerVirtualLanPriorityCodePoint(U8.t(Short.valueOf(values[1])));
} else if (values[0].equals(OFOXMFieldType.IPV4_DST.getFieldName())
|| values[0].equals("ip_dst") || values[0].equals("nw_dst")) {
setNetworkAddressFromCIDR(m, values[1], OFOXMFieldType.IPV4_DST);
} else if (values[0].equals(OFOXMFieldType.IPV4_SRC.getFieldName())
|| values[0].equals("ip_src") || values[0].equals("nw_src")) {
setNetworkAddressFromCIDR(m, values[1], OFOXMFieldType.IPV4_SRC);
} else if (values[0].equals(OFOXMFieldType.IP_PROTO.getFieldName()) || values[0].equals("nw_proto")) {
if (values[1].startsWith("0x"))
networkProtocol = U8.t(Short.valueOf(values[1].replaceFirst("0x",""),16));
else
networkProtocol = U8.t(Short.valueOf(values[1]));
m.setNetworkProtocol(networkProtocol);
} else if (values[0].equals(OFOXMFieldType.IP_DSCP.getFieldName())
|| values[0].equals("nw_tos")) {
m.setNetworkTypeOfService(U8.t(Short.valueOf(values[1])));
} else if (values[0].equals(OFOXMFieldType.TCP_DST.getFieldName())
|| values[0].equals(OFOXMFieldType.UDP_DST.getFieldName())
|| values[0].equals("tp_dst")) {
if (networkProtocol == 0)
throw new IllegalArgumentException("specifying transport src/dst without establishing nw_proto first");
m.setTransportDestination(networkProtocol, U16.t(Integer.valueOf(values[1])));
} else if (values[0].equals(OFOXMFieldType.TCP_SRC.getFieldName())
|| values[0].equals(OFOXMFieldType.UDP_SRC.getFieldName())
|| values[0].equals("tp_src")) {
if (networkProtocol == 0)
throw new IllegalArgumentException("specifying transport src/dst without establishing nw_proto first");
m.setTransportSource(networkProtocol, U16.t(Integer.valueOf(values[1])));
} else {
throw new IllegalArgumentException("unknown token "
+ tokens[i] + " parsing "
+ match);
}
}
return m;
}
} |
package org.takes.facets.auth;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.xml.bind.DatatypeConverter;
import lombok.EqualsAndHashCode;
import org.takes.Request;
import org.takes.Response;
import org.takes.misc.Opt;
/**
* Pass that checks the user according RFC-2617.
*
* <p>The class is immutable and thread-safe.
*
* @author Endrigo Antonini (teamed@endrigo.com.br)
* @version $Id$
* @since 0.20
*/
@EqualsAndHashCode(of = { "entry" })
public final class PsBasic implements Pass {
/**
* Authorization response HTTP head.
*/
private static final String AUTH_HEAD = "Authorization: Basic";
/**
* Entry to validate user information.
*/
private final transient PsBasic.Entry entry;
/**
* Ctor.
* @param basic Entry
*/
public PsBasic(final PsBasic.Entry basic) {
this.entry = basic;
}
@Override
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public Opt<Identity> enter(final Request request) throws IOException {
String authorization = "";
String user = "";
String pass = "";
boolean found = false;
Opt<Identity> identity = new Opt.Empty<Identity>();
for (final String head : request.head()) {
if (head.startsWith(AUTH_HEAD)) {
authorization = head.split(AUTH_HEAD)[1].trim();
authorization = new String(
DatatypeConverter.parseBase64Binary(authorization)
);
user = authorization.split(":")[0];
pass = authorization.substring(user.length() + 1);
found = true;
break;
}
}
if (found && this.entry.check(user, pass)) {
final ConcurrentMap<String, String> props =
new ConcurrentHashMap<String, String>(0);
identity = new Opt.Single<Identity>(
new Identity.Simple(
String.format("urn:basic:%s", user),
props
)
);
}
return identity;
}
@Override
public Response exit(final Response response, final Identity identity)
throws IOException {
return response;
}
/**
* Entry interface that is used to check if the received information is
* valid.
*
* @author Endrigo Antonini (teamed@endrigo.com.br)
* @version $Id$
* @since 0.20
*/
public interface Entry {
/**
* Check if is a valid user.
* @param user User
* @param pwd Password
* @return If valid it return <code>true</code>.
*/
boolean check(String user, String pwd);
}
} |
package quantisan.qte_lmax;
import com.lmax.api.FixedPointNumber;
import com.lmax.api.order.Execution;
import com.lmax.api.position.PositionEvent;
public final class EdnMessage {
private EdnMessage() {}
private static boolean isOrderComplete(com.lmax.api.order.Order order)
{
long completedQuantity = order.getFilledQuantity().longValue() + order.getCancelledQuantity().longValue();
return order.getQuantity().longValue() == completedQuantity;
}
public static Long safeLongValue(FixedPointNumber x) {
if (x == null)
return null;
else
return x.longValue();
}
public static String executionEvent(Execution exe) {
com.lmax.api.order.Order o = exe.getOrder();
String lmaxOrderId = o.getOrderId(); // TODO refactor into return
String lmaxOrderType = o.getOrderType().toString();
String orderId = o.getInstructionId();
String originalOrderId = o.getOriginalInstructionId();
Long fillPrice = exe.getPrice().longValue();
Long quantity = o.getQuantity().longValue();
Long filledQuantity = o.getFilledQuantity().longValue();
Long cancelledQuantity = o.getCancelledQuantity().longValue();
String instrument = Instrument.toName(o.getInstrumentId());
Long commission = o.getCommission().longValue();
boolean complete = isOrderComplete(o);
return "{:message-type :execution-event" +
", :user-id \"" + ThinBot.USER_NAME + "\""
+ ", :lmax-order-type \"" + lmaxOrderType + "\""
+ ", :lmax-order-id \"" + lmaxOrderId + "\""
+ ", :order-id \"" + orderId + "\""
+ ", :original-order-id \"" + originalOrderId + "\""
+ ", :instrument \"" + instrument + "\""
+ ", :fill-price " + fillPrice
+ ", :stop-reference-price " + safeLongValue(o.getStopReferencePrice())
+ ", :stop-offset " + safeLongValue(o.getStopLossOffset())
+ ", :take-profit-offset" + safeLongValue(o.getStopProfitOffset())
+ ", :quantity " + quantity
+ ", :filled-quantity " + filledQuantity
+ ", :cancelled-quantity " + cancelledQuantity
+ ", :commission " + commission
+ ", :completed? " + complete + "}";
}
public static String positionEvent(PositionEvent pe) {
return "{:message-type :position-event" +
", :user-id \"" + ThinBot.USER_NAME + "\"" +
", :instrument \"" + Instrument.toName(pe.getInstrumentId()) + "\"" +
", :valuation " + safeLongValue(pe.getValuation()) +
", :short-unfilled-cost " + safeLongValue(pe.getShortUnfilledCost()) +
", :long-unfilled-cost " + safeLongValue(pe.getLongUnfilledCost()) +
", :quantity " + safeLongValue(pe.getOpenQuantity()) +
", :cumulative-cost " + safeLongValue(pe.getCumulativeCost()) +
", :open-cost " + safeLongValue(pe.getOpenCost()) + "}";
}
} |
package com.haulmont.cuba.core.sys;
import com.haulmont.bali.db.QueryRunner;
import com.haulmont.bali.db.ResultSetHandler;
import com.haulmont.cuba.core.Locator;
import com.haulmont.cuba.core.PersistenceProvider;
import com.haulmont.cuba.core.app.ServerConfig;
import com.haulmont.cuba.core.global.ConfigProvider;
import com.haulmont.cuba.core.sys.DbUpdater;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.text.StrMatcher;
import org.apache.commons.lang.text.StrTokenizer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.annotation.ManagedBean;
import javax.inject.Inject;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
@ManagedBean(DbUpdater.NAME)
public class DbUpdaterImpl implements DbUpdater {
private boolean changelogTableExists;
protected File dbDir;
private Log log = LogFactory.getLog(DbUpdaterImpl.class);
@Inject
public void setConfigProvider(ConfigProvider cp) {
String dbDirName = cp.doGetConfig(ServerConfig.class).getServerDbDir();
if (dbDirName != null)
dbDir = new File(dbDirName);
}
public void updateDatabase() {
if (dbInitialized()) {
doUpdate();
} else {
doInit();
}
}
private boolean dbInitialized() {
Connection connection = null;
try {
connection = Locator.getDataSource().getConnection();
DatabaseMetaData dbMetaData = connection.getMetaData();
ResultSet tables = dbMetaData.getTables(null, null, null, null);
boolean found = false;
while (tables.next()) {
String tableName = tables.getString("TABLE_NAME");
if ("SYS_DB_CHANGELOG".equalsIgnoreCase(tableName)) {
changelogTableExists = true;
}
if ("SEC_USER".equalsIgnoreCase(tableName)) {
found = true;
}
}
return found;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (connection != null)
try {
connection.close();
} catch (SQLException e) {
}
}
}
private void doInit() {
log.info("Initializing database");
createChangelogTable();
List<File> initFiles = getInitScripts();
for (File file : initFiles) {
executeScript(file);
markScript(getScriptName(file), true);
}
List<File> updateFiles = getUpdateScripts();
for (File file : updateFiles) {
markScript(getScriptName(file), true);
}
log.info("Database initialized");
}
private List<File> getUpdateScripts() {
List<File> files = new ArrayList<File>();
String[] moduleDirs = dbDir.list();
Arrays.sort(moduleDirs);
for (String moduleDirName : moduleDirs) {
File moduleDir = new File(dbDir, moduleDirName);
File initDir = new File(moduleDir, "update");
File scriptDir = new File(initDir, PersistenceProvider.getDbDialect().getName());
if (scriptDir.exists()) {
List<File> list = new ArrayList(FileUtils.listFiles(scriptDir, null, true));
Collections.sort(list, new Comparator<File>() {
public int compare(File f1, File f2) {
return f1.getName().compareTo(f2.getName());
}
});
files.addAll(list);
}
}
return files;
}
private String getScriptName(File file) {
try {
String path = file.getCanonicalPath();
String dir = dbDir.getCanonicalPath();
return path.substring(dir.length() + 1).replace("\\", "/");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void doUpdate() {
log.info("Updating database");
if (!changelogTableExists) {
log.info("Changelog table not found, creating it and mark all scripts as executed");
createChangelogTable();
// just mark all scripts as executed before
List<File> initFiles = getInitScripts();
for (File file : initFiles) {
markScript(getScriptName(file), true);
}
List<File> updateFiles = getUpdateScripts();
for (File file : updateFiles) {
markScript(getScriptName(file), true);
}
return;
}
List<File> files = getUpdateScripts();
Set<String> scripts = getExecutedScripts();
for (File file : files) {
String name = getScriptName(file);
if (!scripts.contains(name)) {
executeScript(file);
markScript(name, false);
}
}
log.info("Database is up-to-date");
}
private Set<String> getExecutedScripts() {
QueryRunner runner = new QueryRunner(Locator.getDataSource());
try {
Set<String> scripts = runner.query("select SCRIPT_NAME from SYS_DB_CHANGELOG",
new ResultSetHandler<Set<String>>() {
public Set<String> handle(ResultSet rs) throws SQLException {
Set<String> rows = new HashSet<String>();
while (rs.next()) {
rows.add(rs.getString(1));
}
return rows;
}
});
return scripts;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
private void createChangelogTable() {
QueryRunner runner = new QueryRunner(Locator.getDataSource());
try {
runner.update("create table SYS_DB_CHANGELOG(" +
"SCRIPT_NAME varchar(300) not null primary key, " +
"CREATE_TS timestamp default current_timestamp, " +
"IS_INIT integer default 0)");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
private void executeScript(File file) {
log.info("Executing script " + file.getPath());
String script;
try {
script = FileUtils.readFileToString(file);
} catch (IOException e) {
throw new RuntimeException(e);
}
StrTokenizer tokenizer = new StrTokenizer(script,
StrMatcher.charSetMatcher(PersistenceProvider.getDbDialect().getScriptSeparator()),
StrMatcher.singleQuoteMatcher()
);
QueryRunner runner = new QueryRunner(Locator.getDataSource());
while (tokenizer.hasNext()) {
String sql = tokenizer.nextToken();
try {
runner.update(sql);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
private void markScript(String name, boolean init) {
QueryRunner runner = new QueryRunner(Locator.getDataSource());
try {
runner.update("insert into SYS_DB_CHANGELOG (SCRIPT_NAME, IS_INIT) values (?, ?)",
new Object[] { name, init ? 1 : 0 }
);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
private List<File> getInitScripts() {
List<File> files = new ArrayList<File>();
String[] moduleDirs = dbDir.list();
Arrays.sort(moduleDirs);
for (String moduleDirName : moduleDirs) {
File moduleDir = new File(dbDir, moduleDirName);
File initDir = new File(moduleDir, "init");
File scriptDir = new File(initDir, PersistenceProvider.getDbDialect().getName());
File file = new File(scriptDir, "create-db.sql");
if (file.exists()) {
files.add(file);
}
}
return files;
}
} |
package com.illposed.osc;
import com.illposed.osc.argument.ArgumentHandler;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class OSCSerializer {
private final SizeTrackingOutputStream stream;
private final Map<Class, Boolean> classToMarker;
private final Map<Class, ArgumentHandler> classToType;
private final Map<Object, ArgumentHandler> markerValueToType;
public OSCSerializer(final List<ArgumentHandler> types, final OutputStream wrappedStream) {
final Map<Class, Boolean> classToMarkerTmp = new HashMap<Class, Boolean>(types.size());
final Map<Class, ArgumentHandler> classToTypeTmp = new HashMap<Class, ArgumentHandler>();
final Map<Object, ArgumentHandler> markerValueToTypeTmp = new HashMap<Object, ArgumentHandler>();
for (final ArgumentHandler type : types) {
final Class typeJava = type.getJavaClass();
final Boolean registeredIsMarker = classToMarkerTmp.get(typeJava);
if ((registeredIsMarker != null) && (registeredIsMarker != type.isMarkerOnly())) {
throw new IllegalStateException(ArgumentHandler.class.getSimpleName()
+ " implementations disagree on the marker nature of their class: "
+ typeJava);
}
classToMarkerTmp.put(typeJava, type.isMarkerOnly());
if (type.isMarkerOnly()) {
try {
final Object markerValue = type.parse(null);
final ArgumentHandler previousType = markerValueToTypeTmp.get(markerValue);
if (previousType != null) {
throw new IllegalStateException("Marker value \"" + markerValue
+ "\" is already used for type "
+ previousType.getClass().getCanonicalName());
}
markerValueToTypeTmp.put(markerValue, type);
} catch (final OSCParseException ex) {
throw new IllegalStateException("Developper error; this should never happen",
ex);
}
} else {
final ArgumentHandler previousType = classToTypeTmp.get(typeJava);
if (previousType != null) {
throw new IllegalStateException("Java argument type "
+ typeJava.getCanonicalName() + " is already used for type "
+ previousType.getClass().getCanonicalName());
}
classToTypeTmp.put(typeJava, type);
}
}
this.classToMarker = Collections.unmodifiableMap(classToMarkerTmp);
this.classToType = Collections.unmodifiableMap(classToTypeTmp);
this.markerValueToType = Collections.unmodifiableMap(markerValueToTypeTmp);
this.stream = new SizeTrackingOutputStream(wrappedStream);
}
public Map<Class, ArgumentHandler> getClassToTypeMapping() {
return classToType;
}
/**
* Align the stream by padding it with '0's so it has a size divisible by 4.
*/
private void alignStream() throws IOException {
final int alignmentOverlap = stream.size() % 4;
final int padLen = (4 - alignmentOverlap) % 4;
for (int pci = 0; pci < padLen; pci++) {
stream.write(0);
}
}
private byte[] convertToByteArray(final OSCPacket packet) throws IOException {
final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
final OSCSerializer packetStream = OSCSerializerFactory.createDefaultFactory().create(buffer); // HACK this should not use the default one, but the one that created us! but in the end, this part should be externalized anyway, as it is not part of the core serialization, but rather a requirement for the TCP transport convention (see OSC spec. 1.1)
// packetStream.setCharset(getCharset()); // see HACK of the previous line
if (packet instanceof OSCBundle) {
packetStream.write((OSCBundle) packet);
} else if (packet instanceof OSCMessage) {
packetStream.write((OSCMessage) packet);
} else {
throw new UnsupportedOperationException("We do not support writing packets of type: "
+ packet.getClass());
}
return buffer.toByteArray();
}
private void write(final OSCBundle bundle) throws IOException {
write("#bundle");
write(bundle.getTimestamp());
for (final OSCPacket pkg : bundle.getPackets()) {
writeInternal(pkg);
}
}
/**
* Serializes a messages address.
* @param message the address of this message will be serialized
*/
private void writeAddress(final OSCMessage message) throws IOException {
final String address = message.getAddress();
if (!OSCMessage.isValidAddress(address)) {
throw new IllegalStateException("Can not serialize a message with invalid address: \""
+ address + "\"");
}
write(address);
}
/**
* Serializes the arguments of a message.
* @param message the arguments of this message will be serialized
*/
private void writeArguments(final OSCMessage message) throws IOException {
stream.write(OSCParser.TYPES_VALUES_SEPARATOR);
writeTypeTags(message.getArguments());
for (final Object argument : message.getArguments()) {
write(argument);
}
}
private void write(final OSCMessage message) throws IOException {
writeAddress(message);
writeArguments(message);
}
private void writeInternal(final OSCPacket packet) throws IOException {
// HACK NOTE We have to do it in this ugly way,
// because we have to know the packets size in bytes
// and write it to the stream,
// before we can write the packets content to the stream.
final byte[] packetBytes = convertToByteArray(packet);
write(packetBytes); // this first writes the #bytes, before the actual bytes
}
public void write(final OSCPacket packet) throws IOException {
stream.reset();
if (packet instanceof OSCBundle) {
write((OSCBundle) packet);
} else if (packet instanceof OSCMessage) {
write((OSCMessage) packet);
} else {
throw new UnsupportedOperationException("We do not support writing packets of type: "
+ packet.getClass());
}
}
private ArgumentHandler findType(final Object argumentValue) {
final ArgumentHandler type;
final Class argumentClass = extractTypeClass(argumentValue);
final Boolean markerType = classToMarker.get(argumentClass);
if (markerType == null) {
throw new IllegalArgumentException("No type handler registered for serializing class "
+ argumentClass.getCanonicalName());
} else if (markerType) {
type = markerValueToType.get(argumentValue);
} else {
type = classToType.get(argumentClass);
}
return type;
}
/**
* Write an object into the byte stream.
* @param anObject (usually) one of Float, Double, String, Character, Integer, Long,
* or array of these.
*/
private void write(final Object anObject) throws IOException {
if (anObject instanceof Collection) {
@SuppressWarnings("unchecked") final Collection<Object> theArray = (Collection<Object>) anObject;
for (final Object entry : theArray) {
write(entry);
}
} else {
final ArgumentHandler type = findType(anObject);
type.serialize(stream, anObject);
}
}
private static Class extractTypeClass(final Object value) {
return (value == null) ? Object.class : value.getClass();
}
/**
* Write the OSC specification type tag for the type a certain Java type
* converts to.
* @param value of this argument, we need to write the type identifier
*/
private void writeType(final Object value) throws IOException {
final ArgumentHandler type = findType(value);
stream.write(type.getDefaultIdentifier());
}
/**
* Write the type tags for a given list of arguments.
* @param arguments array of base Objects
* @throws IOException if the underlying stream produces an exception when written to
*/
private void writeTypeTagsRaw(final List<?> arguments) throws IOException {
for (final Object argument : arguments) {
if (argument instanceof List) {
// This is used for nested arguments.
// open the array
stream.write(OSCParser.TYPE_ARRAY_BEGIN);
// fill the [] with the nested argument types
@SuppressWarnings("unchecked") List<Object> collArg = (List<Object>) argument;
writeTypeTagsRaw(collArg);
// close the array
stream.write(OSCParser.TYPE_ARRAY_END);
} else {
// write a single, simple arguments type
writeType(argument);
}
}
}
/**
* Write the type tags for a given list of arguments, and cleanup the stream.
* @param arguments the arguments to an OSCMessage
* @throws IOException if the underlying stream produces an exception when written to
*/
public void writeTypeTags(final List<?> arguments) throws IOException {
writeTypeTagsRaw(arguments);
// we always need to terminate with a zero,
// even if (especially when) the stream is already aligned.
stream.write((byte) 0);
// align the stream with padded bytes
alignStream();
}
} |
package de.graeuler.garden.config;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This interface defines the default configuration. Implementing classes may load modified values from other sources
* like property files. The {@link Key} enum embedded in this interface provides methods to read values from AppConfig
* implementations like this:
*
* <pre>
* {@code AppConfig.Key.API_TOKEN.from(new AppConfig()); }
* </pre>
*
* @author bernhard.graeuler
*
*/
public interface AppConfig {
/**
* @param key The key of the configuration value
* @return Must return the configuration value assigned to the key.
*/
public Object get(Key key);
public Object get(Key key, Object defaultValue);
/**
* The AppConfig.Key enumeration holds the default configuration. Each enum predefines a string representation,
* a default value and an optional converter implementing the {@link ConfigValueConverter} interface.
*
* @author bernhard.graeuler
*
*/
public enum Key {
// keys, external property names and default values , converter , { Validator,... }
TF_DAEMON_HOST ("tinkerforge.brickdaemon.host" , "localhost" , null , null),
TF_DAEMON_PORT ("tinkerforge.brickdaemon.port" , 4223 , new IntegerConverter(), null),
DC_JDBC_DERBY_URL ("datacollector.jdbc-derby-url" , "jdbc:derby:data;create=true", null , null),
UPLINK_ADRESS ("uplink.address" , "http://localhost/collect/garden" , null, null),
API_TOKEN ("uplink.api-token" , "default-token" , null , null),
COLLECT_TIME_RATE ("collect.time.rate" , 6 , new IntegerConverter(), null),
COLLECT_TIME_UNIT ("collect.time.unit" , TimeUnit.HOURS , new TimeUnitConverter(), null),
WATERLVL_CHG_THD ("waterlevel.change.threshold.cm" , 2 , new IntegerConverter(), null),
WATERLVL_DEBOUNCE ("waterlevel.debounce.period.ms" , 10000 , new IntegerConverter(), null),
WATERLVL_MOVING_AVG ("waterlevel.moving.average" , 60 , new IntegerConverter(),
new ConfigValueValidator[] { new IntLimitValidator(0, 100) }),
TEMP_CHG_THD ("temperature.change.threshold.degc" , 1 , new IntegerConverter(), null),
TEMP_DEBOUNCE ("temperature.debounce.period.ms" , 1000 , new IntegerConverter(), null),
NETWORK_VNSTAT_CMD ("net.vnstat.oneline.command" , "vnstat --oneline" , null , null),
NETWORK_VNSTAT_LANG_TAG("net.vnstat.language.tag" , "en" , null , null),
NET_TIME_RATE ("net.check.time.rate" , 1 , new IntegerConverter(), null),
NET_TIME_UNIT ("net.check.time.unit" , TimeUnit.MINUTES , new TimeUnitConverter(), null),
NET_VOL_CHG_THD ("net.volume.change.threshold.bytes" , 102400 , new IntegerConverter(), null),
CURRENT_CHG_THD ("current.change.threshold.mamp" , 10 , new IntegerConverter(), null),
VOLTAGE_CHG_THD ("voltage.change.threshold.mvolt" , 1000 , new IntegerConverter(), null),
;
private Logger log = LoggerFactory.getLogger(Key.class);
private String propertyName;
private Object defaultValue;
private ConfigValueConverter configKeyConverter;
private ConfigValueValidator[] configValueValidators;
public String getPropertyName() {return propertyName;}
public Object getDefaultValue() {return defaultValue;}
/**
*
* @param propertyName Identifier of this configuration key
* @param defaultValue
* @param converter
* @param validators Are used to check the returned configuration value.
*/
Key(String propertyName, Object defaultValue, ConfigValueConverter converter, ConfigValueValidator[] validators) {
this.propertyName = propertyName;
this.defaultValue = defaultValue;
this.configKeyConverter = converter;
this.configValueValidators = validators;
}
/**
* Reads the value of this key from the given configuration.
* @param configuration where the value should be read from.
* @return the configuration value converted by this Keys converter.
*/
public Object from(AppConfig configuration) {
Object value = this.getConvertedValue(configuration.get(this));
return validate(value);
}
/**
* Similar to from, but returns the default value if this key is not available in the given configuration.
* @param config configuration where the value should be read from.
* @param defaultValue the default value if this key is not available.
* @return the converted (given default) value
*/
public Object from(AppConfig config, Object defaultValue) {
Object value = this.getConvertedValue(config.get(this, defaultValue));
return validate(value);
}
private Object getConvertedValue(Object value) {
if(null == this.configKeyConverter) {
return value;
} else {
try {
return this.configKeyConverter.convert(value);
} catch (Exception e) {
log.warn("Unable to convert {}... using {}.",
String.format("%1.25s", value.toString()),
this.configKeyConverter.getClass().getName());
return this.getDefaultValue();
}
}
}
private Object validate(Object value) {
ConfigValueValidator[] validators = this.getConfigValidators();
boolean isValid = true;
for ( ConfigValueValidator v : validators ) {
if ( v.isValid(value) ) {
continue;
} else {
isValid = false;
break;
}
}
if ( isValid ) {
return value;
} else {
log.warn("Invalid configuration value provided for {}. Using the default.", this.getPropertyName());
return this.getDefaultValue();
}
}
private ConfigValueValidator[] getConfigValidators() {
if ( null == this.configValueValidators ) {
return new ConfigValueValidator[] {};
} else {
return this.configValueValidators;
}
}
}
} |
package ru.naumen.core.storage;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import ru.naumen.model.User;
import com.google.common.collect.Iterables;
/**
* @author astarovoyt
*
*/
@Repository
public class DBImpl
{
public final static boolean IS_DEBUG = true;
public static final String DB_NAME = "userdb";
@PersistenceContext
EntityManager entityManager;
@SuppressWarnings("unchecked")
@Transactional
public User findByAccessKey(String accessKey)
{
Query query = getEntityManager().createQuery(
"SELECT p from " + User.class.getName() + " p where p.accessKey = :accessKey");
query.setParameter("accessKey", accessKey);
query.setHint("org.hibernate.cacheable", true);
List resultList = query.getResultList();
return (User)Iterables.get(resultList, 0, null);
}
@SuppressWarnings("unchecked")
@Transactional
public User findByEmail(String email)
{
Query query = getEntityManager().createQuery(
"SELECT p from " + User.class.getName() + " p where p.email = :email");
query.setParameter("email", email);
query.setHint("org.hibernate.cacheable", true);
List resultList = query.getResultList();
return (User)Iterables.get(resultList, 0, null);
}
@PostConstruct
public void init()
{
}
@Transactional
public void store(User user)
{
getEntityManager().persist(user);
}
@Transactional
public void update(User user)
{
getEntityManager().merge(user);
}
EntityManager getEntityManager()
{
return entityManager;
}
} |
/**
* Require nc binary (netcat-openbsd package for Debian/Ubuntu).
*/
package com.github.dddpaul.netcat;
import android.util.Log;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowLog;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import static com.github.dddpaul.netcat.NetCater.*;
import static com.github.dddpaul.netcat.NetCater.Op.CONNECT;
import static com.github.dddpaul.netcat.NetCater.Op.DISCONNECT;
import static com.github.dddpaul.netcat.NetCater.Op.LISTEN;
import static com.github.dddpaul.netcat.NetCater.Op.RECEIVE;
import static com.github.dddpaul.netcat.NetCater.Op.SEND;
import static org.hamcrest.core.Is.is;
@Config( emulateSdk = 18 )
@RunWith( RobolectricTestRunner.class )
public class NetCatTest extends Assert implements NetCatListener
{
final static String INPUT_TEST = "Input from this test, привет, €, ";
final static String INPUT_NC = "Input from netcat process, пока, £, ";
final static String HOST = "localhost";
final String CLASS_NAME = ( (Object) this ).getClass().getSimpleName();
NetCater netCat;
Result result;
CountDownLatch latch;
Process process;
String inputFromTest, inputFromProcess;
@BeforeClass
public static void init()
{
ShadowLog.stream = System.out;
}
@Before
public void setUp() throws Exception
{
netCat = new NetCat( this );
inputFromTest = INPUT_TEST;
inputFromProcess = INPUT_NC;
}
@After
public void tearDown() throws InterruptedException
{
disconnect();
process.destroy();
}
@Test
public void testTCPConnect() throws IOException, InterruptedException
{
startConnectTest( Proto.TCP );
}
@Test
public void testTCPListen() throws IOException, InterruptedException
{
startListenTest( Proto.TCP );
}
@Test
public void testUDPConnect() throws IOException, InterruptedException
{
inputFromTest = inputFromTest + "\n";
inputFromProcess = inputFromProcess + "\n";
startConnectTest( Proto.UDP );
}
@Test
public void testUDPListen() throws IOException, InterruptedException
{
inputFromTest = inputFromTest + "\n";
inputFromProcess = inputFromProcess + "\n";
startListenTest( Proto.UDP );
}
public void startConnectTest( Proto proto ) throws InterruptedException, IOException
{
String port = "9998";
// Start external nc listener
List<String> nc = new ArrayList<>();
nc.add( "nc" );
nc.add( "-v" );
if( proto == Proto.UDP ) {
nc.add( "-u" );
}
nc.add( "-l" );
nc.add( port );
process = new ProcessBuilder( nc ).redirectErrorStream( true ).start();
// Execute connect operation after some delay
Thread.sleep( 500 );
connect( proto, port );
send();
receive();
}
public void startListenTest( Proto proto ) throws InterruptedException, IOException
{
String port = "9997";
// Connect to NetCat by external nc after some delay required for NetCat listener to start
final List<String> nc = new ArrayList<>();
nc.add( "nc" );
nc.add( "-v" );
if( proto == Proto.UDP ) {
nc.add( "-u" );
}
nc.add( HOST );
nc.add( port );
new Thread( new Runnable()
{
@Override
public void run()
{
try {
Thread.sleep( 500 );
process = new ProcessBuilder( nc ).redirectErrorStream( true ).start();
} catch( Exception e ) {
e.printStackTrace();
}
}
} ).start();
// Start NetCat listener
listen( proto, port );
if( proto == Proto.TCP ) {
send();
receive();
} else {
// UDP listener must wait for receive to move into connected state then send
receive();
send();
}
}
@Override
public void netCatIsStarted()
{
latch = new CountDownLatch( 1 );
}
@Override
public void netCatIsCompleted( Result result )
{
this.result = result;
latch.countDown();
}
@Override
public void netCatIsFailed( Result result )
{
this.result = result;
Log.e( CLASS_NAME, result.getErrorMessage() );
latch.countDown();
}
public Closeable connect( Proto proto, String port ) throws InterruptedException
{
netCat.execute( CONNECT.toString(), proto.toString(), HOST, port );
latch.await( 5, TimeUnit.SECONDS );
assertNotNull( result );
assertNull( result.exception );
assertThat( result.op, is( CONNECT ));
assertNotNull( result.getSocket() );
return result.getSocket();
}
public Closeable listen( Proto proto, String port ) throws InterruptedException
{
netCat.execute( LISTEN.toString(), proto.toString(), port );
latch.await( 5, TimeUnit.SECONDS );
assertNotNull( result );
assertNull( result.exception );
assertThat( result.op, is( LISTEN ));
assertNotNull( result.getSocket() );
return result.getSocket();
}
public void disconnect() throws InterruptedException
{
netCat.execute( DISCONNECT.toString() );
latch.await( 5, TimeUnit.SECONDS );
assertNotNull( result );
assertNull( result.exception );
assertThat( result.op, is( DISCONNECT ));
}
public void send() throws InterruptedException, IOException
{
// Send string to external nc process
netCat.setInput( new ByteArrayInputStream( inputFromTest.getBytes() ) );
netCat.execute( SEND.toString() );
latch.await( 5, TimeUnit.SECONDS );
assertNotNull( result );
assertEquals( SEND, result.op );
// Wait till nc process will be started definitely
while( process == null ) {
Thread.sleep( 100 );
}
// Get received string by external nc process
BufferedReader b = new BufferedReader( new InputStreamReader( process.getInputStream() ) );
String line;
do {
line = b.readLine();
Log.i( CLASS_NAME, line );
} while( !INPUT_TEST.equals( line ) );
}
public void receive() throws IOException, InterruptedException
{
// Wait till nc process will be started definitely
while( process == null ) {
Thread.sleep( 100 );
}
// Send string from external nc process
process.getOutputStream().write( inputFromProcess.getBytes() );
process.getOutputStream().flush();
process.getOutputStream().close();
// Receive string from external nc process
netCat.createOutput();
netCat.execute( RECEIVE.toString() );
latch.await( 5, TimeUnit.SECONDS );
assertNotNull( result );
assertThat( result.op, is( RECEIVE ));
String line = netCat.getOutputString();
Log.i( CLASS_NAME, line );
assertThat( line, is( INPUT_NC ));
}
} |
package simcity.gui;
import simcity.PersonAgent;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import javax.imageio.ImageIO;
import simcity.DRestaurant.DCustomerRole;
public class PersonGui implements Gui {
private PersonAgent agent = null;
public boolean waiterAtFront()
{
if(xPos==-20 && yPos==-20) return true;
else return false;
}
private boolean isPresent = false;
private boolean isHungry = false;
private int busStop = 0;
SimCityGui gui;
private int tableGoingTo;
public static final int x_Offset = 100;
private int xPos = 0, yPos = 0;//default waiter position
private int xDestination = 0, yDestination = 0;//default start position
// private int xFoodDestination, yFoodDestination;
private boolean cookedLabelVisible=false;
private boolean foodIsFollowingWaiter=false;
private boolean madeToCashier=false;
private boolean tryingToGetToFront=false;
private boolean madeToFront=true;
//private String foodReady;
// static List<CookLabel> foodz = Collections.synchronizedList(new ArrayList<CookLabel>());
//private int hangout_x = 50, hangout_y=50;
public static final int streetWidth = 30;
public static final int sidewalkWidth = 20;
public static final int housingWidth=30;
public static final int housingLength=35;
public static final int parkingGap = 22;
public static final int yardSpace=11;
HashMap<String, Point> myMap = new HashMap<String, Point>();
//int numPlating=1;
enum Command {none, GoToRestaurant, GoHome, other, GoToBusStop};
Command command= Command.none;
//public String[] foodReady= new String[nTABLES];
//public boolean[] labelIsShowing = new boolean[nTABLES];
private boolean labelIsShowing=false;
String foodReady;
// private int seatingAt;
private DCustomerRole takingOrderFrom;//, orderFrom;
private int seatingAt_x, seatingAt_y;
private int tablegoingto_x, tablegoingto_y;
//f private void setSeatingAt(int t) { seatingAt=t; }
public PersonGui(PersonAgent agent, SimCityGui g) {
gui=g;
this.agent = agent;
madeToFront=true;
// for(int i=0; i<labelIsShowing.length;i++)
// labelIsShowing[i]=false;
//coordinates are from citypanel, find the building you want to ppl to go to and copy/paste coordinates to this map
myMap.put("Restaurant 1", new Point(2*yardSpace+2*housingWidth+2*sidewalkWidth+streetWidth+30, streetWidth+sidewalkWidth));
myMap.put("Restaurant 2", new Point(2*yardSpace+2*housingWidth+2*sidewalkWidth+streetWidth+30, streetWidth+4*housingLength+ sidewalkWidth+ 5*parkingGap));
myMap.put("Restaurant 3", new Point(2*yardSpace+3*housingWidth+4*sidewalkWidth+2*streetWidth-10, streetWidth+sidewalkWidth));
myMap.put("Restaurant 4", new Point(3*yardSpace+4*housingWidth+4*sidewalkWidth+2*streetWidth+30, streetWidth+sidewalkWidth));
myMap.put("Restaurant 5", new Point(3*yardSpace+4*housingWidth+4*sidewalkWidth+2*streetWidth+30, streetWidth+4*housingLength+ sidewalkWidth+ 5*parkingGap));
myMap.put("Restaurant 6", new Point(3*yardSpace+5*housingWidth+6*sidewalkWidth+3*streetWidth-10, streetWidth+4*housingLength+ sidewalkWidth+ 5*parkingGap));
myMap.put("House 1", new Point(yardSpace+30, streetWidth+sidewalkWidth));
myMap.put("House 2", new Point(yardSpace+30, streetWidth+sidewalkWidth+2*housingLength+ 2*parkingGap));
myMap.put("House 3", new Point(yardSpace+30, streetWidth+sidewalkWidth+4*housingLength+ 5*parkingGap));
myMap.put("House 4", new Point(yardSpace+housingWidth+2*sidewalkWidth+streetWidth-10, streetWidth+housingLength+ sidewalkWidth + parkingGap));
myMap.put("House 5", new Point(yardSpace+housingWidth+2*sidewalkWidth+streetWidth-10, streetWidth+3*housingLength+ sidewalkWidth+ 3*parkingGap));
myMap.put("House 6", new Point(2*yardSpace+2*housingWidth+2*sidewalkWidth+streetWidth+30, streetWidth+2*housingLength+ sidewalkWidth+ 2*parkingGap));
myMap.put("House 7", new Point(2*yardSpace+3*housingWidth+4*sidewalkWidth+2*streetWidth-10, streetWidth+housingLength+ sidewalkWidth+ parkingGap));
myMap.put("House 8", new Point(2*yardSpace+3*housingWidth+4*sidewalkWidth+2*streetWidth-10, streetWidth+3*housingLength+ sidewalkWidth+ 3*parkingGap));
myMap.put("House 9", new Point(3*yardSpace+4*housingWidth+4*sidewalkWidth+2*streetWidth+30, streetWidth+2*housingLength+ sidewalkWidth+ 2*parkingGap));
myMap.put("House 10", new Point(3*yardSpace+5*housingWidth+6*sidewalkWidth+3*streetWidth-10, streetWidth+housingLength+ sidewalkWidth+ parkingGap));
myMap.put("House 11", new Point(3*yardSpace+5*housingWidth+6*sidewalkWidth+3*streetWidth-10, streetWidth+3*housingLength+ sidewalkWidth+ 3*parkingGap));
myMap.put("House 12", new Point(4*yardSpace+6*housingWidth+6*sidewalkWidth+3*streetWidth+30, streetWidth+housingLength+ sidewalkWidth+ parkingGap));
myMap.put("House 13", new Point(4*yardSpace+6*housingWidth+6*sidewalkWidth+3*streetWidth+30, streetWidth+3*housingLength+ sidewalkWidth+ 3*parkingGap));
myMap.put("House 14", new Point(4*yardSpace+7*housingWidth+8*sidewalkWidth+4*streetWidth-10, streetWidth+housingLength+ sidewalkWidth+ parkingGap));
myMap.put("House 15", new Point(4*yardSpace+7*housingWidth+8*sidewalkWidth+4*streetWidth-10, streetWidth+3*housingLength+ sidewalkWidth+ 3*parkingGap));
myMap.put("Apartment 1", new Point(yardSpace+30, streetWidth+sidewalkWidth+housingLength+ parkingGap));
myMap.put("Apartment 2", new Point(yardSpace+30, streetWidth+sidewalkWidth+3*housingLength+ 3*parkingGap));
myMap.put("Apartment 3", new Point(yardSpace+housingWidth+2*sidewalkWidth+streetWidth-10, streetWidth+2*housingLength+ sidewalkWidth+ 2*parkingGap));
myMap.put("Apartment 4", new Point(2*yardSpace+2*housingWidth+2*sidewalkWidth+streetWidth+30, streetWidth+housingLength + sidewalkWidth+ parkingGap));
myMap.put("Apartment 5", new Point(2*yardSpace+2*housingWidth+2*sidewalkWidth+streetWidth+30, streetWidth+3*housingLength+ sidewalkWidth+ 3*parkingGap));
myMap.put("Apartment 6", new Point(2*yardSpace+3*housingWidth+4*sidewalkWidth+2*streetWidth-10, streetWidth+2*housingLength+ sidewalkWidth+ 2*parkingGap));
myMap.put("Apartment 7", new Point(3*yardSpace+4*housingWidth+4*sidewalkWidth+2*streetWidth+30, streetWidth+housingLength+ sidewalkWidth+ parkingGap));
myMap.put("Apartment 8", new Point(3*yardSpace+4*housingWidth+4*sidewalkWidth+2*streetWidth+30, streetWidth+3*housingLength+ sidewalkWidth+ 3*parkingGap));
myMap.put("Apartment 9", new Point(3*yardSpace+5*housingWidth+6*sidewalkWidth+3*streetWidth-10, streetWidth+2*housingLength+ sidewalkWidth+ 2*parkingGap));
myMap.put("Apartment 10", new Point(4*yardSpace+6*housingWidth+6*sidewalkWidth+3*streetWidth+30, streetWidth+2*housingLength+ sidewalkWidth+ 2*parkingGap));
myMap.put("Apartment 11", new Point(4*yardSpace+7*housingWidth+8*sidewalkWidth+4*streetWidth-10, streetWidth+sidewalkWidth));
myMap.put("Apartment 12", new Point(4*yardSpace+7*housingWidth+8*sidewalkWidth+4*streetWidth-10, streetWidth+2*housingLength+ sidewalkWidth+ 2*parkingGap));
myMap.put("Homeless Shelter", new Point(4*yardSpace+7*housingWidth+8*sidewalkWidth+4*streetWidth-10, streetWidth+4*housingLength+ sidewalkWidth+ 5*parkingGap));
myMap.put("Bank 1", new Point(yardSpace+housingWidth+2*sidewalkWidth+streetWidth-10, streetWidth+sidewalkWidth+4*housingLength+ 5*parkingGap));
myMap.put("Bank 2", new Point(4*yardSpace+6*housingWidth+6*sidewalkWidth+3*streetWidth+30, streetWidth+sidewalkWidth));
myMap.put("Market 1", new Point(yardSpace+housingWidth+2*sidewalkWidth+streetWidth-10, streetWidth+sidewalkWidth));
myMap.put("Market 2", new Point(2*yardSpace+3*housingWidth+4*sidewalkWidth+2*streetWidth-10, streetWidth+4*housingLength+ sidewalkWidth+ 5*parkingGap));
myMap.put("Market 3", new Point(3*yardSpace+5*housingWidth+6*sidewalkWidth+3*streetWidth-10, streetWidth+sidewalkWidth));
myMap.put("Market 4", new Point(4*yardSpace+6*housingWidth+6*sidewalkWidth+3*streetWidth+30, streetWidth+4*housingLength+ sidewalkWidth+ 5*parkingGap));
myMap.put("Stop1", new Point(100,30));
myMap.put("Stop2", new Point(475,30));
myMap.put("Stop3", new Point(475,345));
myMap.put("Stop4", new Point(100,345));
//Figuring out where the person starts off when created
String personAddress=agent.homeAddress;
if(personAddress.contains("Apartment")) {
// System.err.println("need to truncate");
personAddress=personAddress.substring(0, personAddress.length()-1);
//System.err.println(personAddress);
}
if (personAddress.equals("House 1") || personAddress.equals("House 2") || personAddress.equals("Apartment 1")
|| personAddress.equals("House 3") || personAddress.equals("Apartment 2") ) {
xPos = myMap.get(personAddress).x;
yPos = myMap.get(personAddress).y;
}
else if (personAddress.equals("Market 1") || personAddress.equals("House 4") || personAddress.equals("Apartment 3")
|| personAddress.equals("House 5") || personAddress.equals("Bank 1") ) {
xPos = myMap.get(personAddress).x;
yPos = myMap.get(personAddress).y;
}
else if (personAddress.equals("Restaurant 1") || personAddress.equals("Apartment 4") || personAddress.equals("Apartment 5")
|| personAddress.equals("House 6") || personAddress.equals("Restaurant 2") ) {
xPos = myMap.get(personAddress).x;
yPos = myMap.get(personAddress).y;
}
else if (personAddress.equals("Restaurant 3") || personAddress.equals("House 7") || personAddress.equals("Apartment 6")
|| personAddress.equals("House 8") || personAddress.equals("Market 2") ) {
xPos = myMap.get(personAddress).x;
yPos = myMap.get(personAddress).y;
}
else if (personAddress.equals("Restaurant 4") || personAddress.equals("Apartment 7") || personAddress.equals("House 9")
|| personAddress.equals("Apartment 8") || personAddress.equals("Restaurant 5") ) {
xPos = myMap.get(personAddress).x;
yPos = myMap.get(personAddress).y;
}
else if (personAddress.equals("Market 3") || personAddress.equals("House 10") || personAddress.equals("Apartment 9")
|| personAddress.equals("House 11") || personAddress.equals("Restaurant 6") ) {
xPos = myMap.get(personAddress).x;
yPos = myMap.get(personAddress).y;
}
else if (personAddress.equals("Bank 2") || personAddress.equals("House 12") || personAddress.equals("Apartment 10")
|| personAddress.equals("House 13") || personAddress.equals("Market 4") ) {
xPos = myMap.get(personAddress).x;
yPos = myMap.get(personAddress).y;
}
else if (personAddress.equals("Apartment 11") || personAddress.equals("House 14") || personAddress.equals("Apartment 12")
|| personAddress.equals("House 15") || personAddress.equals("Homeless Shelter") ) {
xPos = myMap.get(personAddress).x;
yPos = myMap.get(personAddress).y;
}
xDestination=xPos;
yDestination=yPos;
}
@Override
public void updatePosition() {
//System.out.println("x pos: "+ xPos + " // y pos: "+ yPos+" // xDestination: " + xDestination + " // yDestination: " + yDestination);
if (xPos != xDestination) {
if (yPos == 40 || yPos == 350) {
if (xPos < xDestination)
xPos++;
else if (xPos > xDestination)
xPos
}
else
if (350 - yDestination <= 150 && yPos >= 40)
yPos++;
else if (350 - yDestination > 150 && yPos <= 350)
yPos
}
if (xPos == xDestination && yPos != yDestination) {
if (yPos < yDestination)
yPos++;
else if (yPos > yDestination)
yPos
}
if (xPos == xDestination && yPos == yDestination)
{
if(command==Command.GoToRestaurant ||command==Command.GoHome||command==Command.other) {
agent.msgAnimationArivedAtRestaurant();
}
else if(command==Command.GoToBusStop) {
agent.msgAnimationAtBusStop();
}
command=Command.none;
}
}
@Override
public void draw(Graphics2D g) {
// g.setColor(Color.magenta);
// g.fillRect(xPos, yPos, 10, 10);
g.setColor(Color.BLACK);
g.setFont(new Font("Arial", Font.PLAIN, 10));
String name = agent.getName();
Image image = null;
try {
image = ImageIO.read(new File("images/person.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
g.drawImage(image, xPos, yPos-3, null);
g.drawString(name.substring(0, 1), xPos + 4, yPos-4); // if(labelIsShowing) {
// g.setColor(Color.BLACK);
// g.drawString(foodReady.substring(0,2),xFood, yFood);
}
@Override
public boolean isPresent() {
return isPresent;
}
public void setHungry() {
isHungry = true;
// agent.gotHungry();
setPresent(true);
}
public void setPresent(boolean p) {
isPresent = p;
}
public int getXPos() {
return xPos;
}
public int getYPos() {
return yPos;
}
public void DoGoTo(String destination) {
System.out.print("Going to " + destination);
isPresent = true;
if(destination.contains("Restaurant")) {
Point myDest = myMap.get(destination);
xDestination = myDest.x;
yDestination = myDest.y;
command=Command.GoToRestaurant;
}
if(destination.contains("Stop")) {
Point myDest = myMap.get(destination);
xDestination = myDest.x;
yDestination = myDest.y;
if (busStop == 0) {
command=Command.GoToBusStop;
busStop++;
}
else if (busStop > 0){
busStop = 0;
command = Command.none;
}
}
if(destination.contains("Bank")) {
Point myDest = myMap.get(destination);
xDestination = myDest.x;
yDestination = myDest.y;
command=Command.GoToRestaurant;
}
if(destination.contains("House") || destination.contains("Apartment")) {
if(destination.contains("Apartment")) {
destination=destination.substring(0, destination.length()-1);
//System.err.println(destination);
}
Point myDest = myMap.get(destination);
xDestination = myDest.x;
yDestination = myDest.y;
command=Command.GoHome;
}
}
// static class CookLabel {
// String food;
// int xPos, yPos;
// boolean isFollowing;
// enum LabelState {ingredient, cooking, cooked, plating, plated};
// LabelState state;
// CookLabel(String f, int x, int y) {
//// System.err.println(f);
// food=f;
// xPos=x;
// yPos=y;
// isFollowing=true;
// state=LabelState.ingredient;
//// System.err.println("added");
} |
package net.bytten.zosoko.player;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import net.bytten.zosoko.IPuzzle;
import net.bytten.zosoko.Tile;
import net.bytten.zosoko.util.Bounds;
import net.bytten.zosoko.util.Coords;
public class PuzzleRenderer {
private Graphics2D g;
private double scale;
private IPuzzle puzzle;
private Bounds bounds;
private void drawFloor() {
g.setColor(Color.WHITE);
g.fillRect(0, 0, (int)scale+1, (int)scale+1);
}
private void drawWall() {
g.setColor(Color.DARK_GRAY);
g.fillRect(0, 0, (int)scale, (int)scale);
}
private void drawGoal() {
g.setColor(Color.WHITE);
g.fillRect(0, 0, (int)scale+1, (int)scale+1);
g.setColor(Color.BLACK);
g.drawString("GOAL", (int)scale/2, (int)scale/2);
}
private void drawTile(Tile tile, int x, int y) {
AffineTransform origXfm = g.getTransform();
g.translate((int)(x * scale), (int)(y * scale));
switch (tile) {
case FLOOR:
drawFloor();
break;
case WALL:
drawWall();
break;
case GOAL:
drawGoal();
break;
}
g.setTransform(origXfm);
}
private void drawBounds() {
if (puzzle.isPlayerBounded()) {
g.setColor(Color.DARK_GRAY);
g.fillRect(-(int)scale, -(int)scale,
(int)(scale*(puzzle.getWidth()+2)),
(int)(scale*(puzzle.getHeight()+2)));
}
}
private void drawMap() {
for (int x = 0; x < bounds.width(); ++x)
for (int y = 0; y < bounds.height(); ++y) {
drawTile(puzzle.getTile(x,y), x,y);
}
g.setColor(Color.LIGHT_GRAY);
for (int x = 0; x <= bounds.width(); ++x) {
g.drawLine((int)(x * scale), 0, (int)(x * scale),
(int)(bounds.height() * scale));
}
for (int y = 0; y <= bounds.height(); ++y) {
g.drawLine(0, (int)(y * scale), (int)(bounds.width() * scale),
(int)(y * scale));
}
}
private void drawBox(Coords xy) {
AffineTransform origXfm = g.getTransform();
g.translate((int)(xy.x * scale), (int)(xy.y * scale));
g.setColor(Color.BLUE);
g.fillRect((int)(scale/4), (int)(scale/4), (int)(scale/2),
(int)(scale/2));
g.setTransform(origXfm);
}
private void drawPlayer(Coords xy) {
AffineTransform origXfm = g.getTransform();
g.translate((int)(xy.x * scale), (int)(xy.y * scale));
g.setColor(Color.RED);
g.fillOval((int)(scale/4), (int)(scale/4), (int)(scale/2),
(int)(scale/2));
g.setTransform(origXfm);
}
public void draw(Graphics2D g, Dimension dim, IPuzzle puzzle) {
this.g = g;
this.puzzle = puzzle;
AffineTransform origXfm = g.getTransform();
// Figure out scale & translation to draw the dungeon at
synchronized (puzzle) {
bounds = puzzle.getBounds();
scale = Math.min(((double)dim.width) / (bounds.width() + 2),
((double)dim.height) / (bounds.height() + 2));
// move the graph into view
g.translate(scale * (1 - bounds.left), scale * (1 - bounds.top));
drawBounds();
drawMap();
if (puzzle instanceof PlayingPuzzle) {
PlayingPuzzle ppuzzle = (PlayingPuzzle)puzzle;
for (Coords xy: ppuzzle.getBoxPositions()) {
drawBox(xy);
}
drawPlayer(ppuzzle.getPlayerPosition());
} else {
for (Coords xy: puzzle.getBoxStartPositions()) {
drawBox(xy);
}
drawPlayer(puzzle.getPlayerStartPosition());
}
}
g.setTransform(origXfm);
}
} |
package com.rafkind.paintown.animator;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
import java.util.HashMap;
import com.rafkind.paintown.animator.events.*;
import com.rafkind.paintown.animator.events.scala.EffectPoint;
import com.rafkind.paintown.Token;
import com.rafkind.paintown.exception.*;
import com.rafkind.paintown.Lambda1;
import java.awt.image.*;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.AlphaComposite;
import javax.swing.JComponent;
public class Animation implements Runnable {
private String name;
private boolean alive = true;
private boolean running;
private List drawables;
private List notifiers;
private Vector<AnimationEvent> events;
private String sequence;
private BufferedImage image;
private BoundingBox attackArea;
private BoundingBox defenseArea;
private int eventIndex;
private double delay;
private int delayTime;
private int x;
private int y;
private int offsetX;
private int offsetY;
private String baseDirectory;
private int range;
private String type;
private double animationSpeed;
/* when something is changed in the animation 'listeners' are notified */
private List listeners;
private List<Lambda1> loopers = new ArrayList<Lambda1>();
private boolean onionSkinning = false;
private int onionSkins = 1;
private boolean onionSkinFront = true;
private List<EffectPoint> effectPoints = new ArrayList<EffectPoint>();
private Vector<String> keys;
private HashMap remapData;
public Animation(){
drawables = new ArrayList();
events = new Vector<AnimationEvent>();
/* give the animation something so it rests a little bit */
events.add( new NopEvent() );
notifiers = new ArrayList();
listeners = new ArrayList();
image = null;
animationSpeed = 1.0;
sequence = "none";
attackArea = new BoundingBox( 0, 0, 0, 0 );
defenseArea = new BoundingBox( 0, 0, 0, 0 );
keys = new Vector();
baseDirectory = ".";
type = "none";
name = "New Animation";
}
public Animation(final Animation copy){
this.name = copy.name;
this.type = copy.type;
this.baseDirectory = copy.baseDirectory;
animationSpeed = copy.animationSpeed;
sequence = copy.sequence;
drawables = new ArrayList();
events = new Vector();
/* give the animation something so it rests a little bit */
notifiers = new ArrayList();
listeners = new ArrayList();
keys = new Vector();
keys.addAll(copy.keys);
attackArea = new BoundingBox(0, 0, 0, 0);
defenseArea = new BoundingBox(0, 0, 0, 0);
for (AnimationEvent event: copy.events){
events.add(event.copy());
}
}
public Animation(String name){
this();
this.name = name;
}
public Animation(Vector events){
this();
this.events = events;
}
public Animation(Token data) throws LoadException {
this();
loadData( data );
}
public void setType(String s){
type = s;
updateAll();
}
public String getType(){
return type;
}
public void addEffectPoint(EffectPoint point){
effectPoints.add(point);
}
public void clearEffectPoints(){
effectPoints = new ArrayList<EffectPoint>();
}
public void setOnionSkinning(boolean what){
this.onionSkinning = what;
}
public boolean isOnionSkinned(){
return this.onionSkinning;
}
public int getOnionSkins(){
return onionSkins;
}
public void setOnionSkins(int skins){
onionSkins = skins;
}
public boolean getOnionSkinFront(){
return onionSkinFront;
}
public void setOnionSkinFront(boolean what){
onionSkinFront = what;
}
public int getHeight(){
if ( image != null ){
return image.getHeight( null );
}
return 0;
}
public int getWidth(){
if ( image != null ){
return image.getWidth( null );
}
return 0;
}
public boolean hasImage(){
return image != null;
}
public void setRange( int r ){
range = r;
updateAll();
}
public int getRange(){
return range;
}
/* Returns the index of the added key */
public int addKey(String key){
keys.add(key);
updateAll();
return keys.size() - 1;
}
public void setMap( HashMap remap ){
this.remapData = remap;
}
public HashMap getMap(){
return this.remapData;
}
public void setSequence( String s ){
sequence = s;
updateAll();
}
public String getSequence(){
return sequence;
}
public void removeKey(int index){
keys.remove(index);
updateAll();
}
public Vector<String> getKeys(){
return keys;
}
public String toString(){
return name != null ? name : "No name set";
}
public void setAttack( BoundingBox attack ){
attackArea = attack;
updateAll();
}
public void setDefense( BoundingBox defense ){
defenseArea = defense;
updateAll();
}
private BufferedImage currentImage(){
return image;
}
public void setName( String s ){
this.name = s;
updateAll();
}
public String getName(){
return name;
}
public void addLoopNotifier(Lambda1 lambda){
if (!loopers.contains(lambda)){
loopers.add(lambda);
}
}
public void removeLoopNotifier(Lambda1 lambda){
loopers.remove(lambda);
}
public void addEventNotifier(Lambda1 lambda){
notifiers.add(lambda);
}
public void removeEventNotifier(Lambda1 lambda){
notifiers.remove(lambda);
}
public synchronized void setImage(BufferedImage image){
this.image = image;
updateDrawables();
updateAll();
}
public void forceRedraw(){
updateDrawables();
}
public void addChangeUpdate(Lambda1 update){
listeners.add(update);
}
public void removeChangeUpdate(Lambda1 update){
listeners.remove(update);
}
private void updateAll(){
for (Iterator it = listeners.iterator(); it.hasNext();){
Lambda1 update = (Lambda1) it.next();
update.invoke_(this);
}
}
/* tell the components that know about this animation that its time
* to redraw the canvas.
* for things like updating the current frame or the attack box
*/
private void updateDrawables(){
synchronized (drawables){
for (Iterator it = drawables.iterator(); it.hasNext();){
JComponent draw = (JComponent) it.next();
draw.repaint();
}
}
}
public synchronized void kill(){
alive = false;
}
private synchronized boolean isAlive(){
return alive;
}
private synchronized boolean isRunning(){
return running;
}
public synchronized void stopRunning(){
running = false;
}
public synchronized void startRunning(){
running = true;
}
public int addEvent(AnimationEvent e, int index){
synchronized (events){
events.add(index, e);
return index;
}
}
public int addEvent(AnimationEvent e){
synchronized (events){
return addEvent(e, events.size());
}
}
public void clearEvents(){
synchronized(events){
events.clear();
}
}
/* swap position of e1 and e2 within event structure */
public void swapEvents(int e1, int e2){
synchronized(events){
AnimationEvent a1 = events.get(e1);
AnimationEvent a2 = events.get(e2);
events.set(e1, a2);
events.set(e2, a1);
}
}
/* return a new list that contains the current events
* do not edit the returned list, to add new events use
* addEvent/removeEvent
*/
public Vector<AnimationEvent> getEvents(){
synchronized(events){
return new Vector<AnimationEvent>(events);
}
}
public void removeEvent(AnimationEvent e){
synchronized (events){
events.remove(e);
}
}
public void removeEvent(int i){
synchronized (events){
events.remove(i);
}
}
public String getBaseDirectory(){
return baseDirectory;
}
public void setBaseDirectory( String b ){
baseDirectory = b;
}
public void setAnimationSpeed(double n){
animationSpeed = n;
}
public double getAnimationSpeed(){
return animationSpeed;
}
/* draws a skin of the animation upto the given event */
private void drawSkin(Graphics graphics, int x, int y, int event){
Animation clone = new Animation();
clone.setBaseDirectory(getBaseDirectory());
for (int use = 0; use <= event; use++){
clone.updateEvent((AnimationEvent) events.get(use));
}
clone.draw(graphics, x, y);
}
private boolean isFrameEvent(AnimationEvent event){
/* sort of a hack to use instanceof */
return event instanceof com.rafkind.paintown.animator.events.scala.FrameEvent;
}
private void drawOnionSkins(Graphics graphics, int x, int y, int skins){
Graphics2D translucent = (Graphics2D) graphics.create();
int direction = -1;
if (skins < 0){
direction = 1;
}
synchronized (events){
if (events.isEmpty()){
return;
}
int here = (eventIndex + direction + events.size()) % events.size();
int skinsLeft = skins;
while (skinsLeft != 0 && here != eventIndex){
AlphaComposite newComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, (float) skinsLeft / (float) skins * (float) 0.5);
translucent.setComposite(newComposite);
AnimationEvent event = (AnimationEvent) events.get(here);
/* sort of a hack to use instanceof */
if (isFrameEvent(event)){
skinsLeft += direction;
drawSkin(translucent, x, y, here);
}
here = (here + direction + events.size()) % events.size();
}
}
}
private void resetPosition(){
this.x = 0;
this.y = 0;
this.offsetX = 0;
this.offsetY = 0;
}
private void drawEffectPoints(Graphics graphics, int x, int y){
Graphics2D g2d = (Graphics2D) graphics.create();
int height = g2d.getFontMetrics(g2d.getFont()).getHeight();
for (EffectPoint effect: effectPoints){
g2d.setColor(new Color(0, 0, 255));
g2d.fillOval(x + effect.x(), y + effect.y(), 1, 1);
g2d.setColor(new Color(255, 255, 255));
g2d.drawOval(x + effect.x() - 2, y + effect.y() - 2, 4, 4);
int width = g2d.getFontMetrics(g2d.getFont()).stringWidth(effect.name());
g2d.drawString(effect.name(),
x - width / 2 + effect.x(),
y - height / 2 + effect.y());
}
}
public synchronized void draw(Graphics g, int x, int y){
int trueX = x + this.x + this.offsetX - getWidth() / 2;
int trueY = y + this.y + this.offsetY - getHeight();
if (isOnionSkinned() && !getOnionSkinFront()){
drawOnionSkins(g, x, y, getOnionSkins());
}
if (currentImage() != null){
g.drawImage(currentImage(), trueX, trueY, null);
}
if (isOnionSkinned() && getOnionSkinFront()){
drawOnionSkins(g, x, y, getOnionSkins());
}
if (getRange() != 0){
Color old = g.getColor();
g.setColor(new Color(255, 255, 255));
g.fillRect(x + this.x, y + this.y, getRange(), 5);
g.setColor(old);
}
if (! attackArea.empty()){
attackArea.render(g, trueX, trueY, new Color(236, 30, 30));
}
if (! defenseArea.empty()){
defenseArea.render(g, trueX, trueY, new Color(51, 133, 243));
}
drawEffectPoints(g, trueX + getWidth() / 2, trueY + getHeight());
}
public synchronized void setImageX( int x ){
this.x = x;
}
public synchronized void setImageY( int y ){
this.y = y;
}
public synchronized void moveX( int x ){
this.x += x;
}
public synchronized void moveY( int y ){
this.y += y;
}
public synchronized int getX(){
return x;
}
public synchronized int getY(){
return y;
}
public synchronized void setOffsetX( int x ){
this.offsetX = x;
}
public synchronized int getOffsetX(){
return this.offsetX;
}
public synchronized void setOffsetY(int y){
this.offsetY = y;
}
public synchronized int getOffsetY(){
return this.offsetY;
}
public void addDrawable(JComponent draw){
synchronized (drawables){
drawables.add(draw);
}
}
public void removeDrawable(JComponent draw){
synchronized (drawables){
drawables.remove(draw);
}
}
private void rest(int ms){
try{
Thread.sleep(ms);
} catch (Exception e){
}
}
/* runs through all the events again */
public void reset(){
applyEvents();
}
public void applyEvents(){
resetPosition();
for (int event = 0; event <= eventIndex; event++){
AnimationEvent use = (AnimationEvent) events.get(event);
updateEvent(use);
}
}
private void findNextFrame(int direction){
int last = eventIndex;
clearEffectPoints();
synchronized (events){
eventIndex = (eventIndex + direction + events.size()) % events.size();
while (eventIndex != last && !isFrameEvent((AnimationEvent) events.get(eventIndex))){
eventIndex = (eventIndex + direction + events.size()) % events.size();
}
applyEvents();
}
}
public void previousFrame(){
findNextFrame(-1);
}
public void nextFrame(){
findNextFrame(1);
}
private int previous(int index, int max){
int last = index - 1;
if (last < 0){
last = max - 1;
}
return last;
}
private int next(int index, int max){
int next = index + 1;
if (next >= max){
next = 0;
}
return next;
}
private void updateEvent(AnimationEvent event){
event.interact(this);
for (Iterator it = notifiers.iterator(); it.hasNext();){
Lambda1 lambda = (Lambda1) it.next();
lambda.invoke_(event);
}
}
/* can be called to step backward through the animation */
public void previousEvent(){
synchronized (events){
if (! events.isEmpty()){
if (isFrameEvent((AnimationEvent) events.get(eventIndex))){
clearEffectPoints();
}
eventIndex = previous(eventIndex, events.size());
if (eventIndex == 0){
setImageX(0);
setImageY(0);
}
updateEvent((AnimationEvent) events.get(eventIndex));
}
}
}
/* Called when the animation loops */
private void notifyLoopers(){
for (Lambda1 loop: loopers){
loop.invoke_(this);
}
}
/* can be called to step foreward through the animation */
public void nextEvent(){
synchronized (events){
if ( ! events.isEmpty() ){
if (isFrameEvent((AnimationEvent) events.get(eventIndex))){
clearEffectPoints();
}
eventIndex = next(eventIndex, events.size());
if (eventIndex == 0){
setImageX(0);
setImageY(0);
notifyLoopers();
}
updateEvent((AnimationEvent) events.get(eventIndex));
}
}
}
public int getEventIndex(){
return eventIndex;
}
private void checkIndex(){
if (eventIndex < 0){
eventIndex = 0;
}
if (eventIndex >= events.size()){
eventIndex = events.size() - 1;
}
}
public void nextEvent(AnimationEvent event){
synchronized (events){
checkIndex();
if (events.contains(event)){
while ((AnimationEvent) events.get(eventIndex) != event){
nextEvent();
}
}
}
}
public void setDelay(double delay){
this.delay = delay;
}
public double getDelay(){
return delay;
}
public int getDelayTime(){
return delayTime;
}
public void setDelayTime(int i){
delayTime = i;
}
public void delay(){
delayTime = (int)(getDelay() * getAnimationSpeed());
}
/* if the animation doesnt contain something that will cause delay this
* thread will just chew up cpu time
*/
public void run(){
while (isAlive()){
if (isRunning() && ! events.isEmpty()){
nextEvent();
if (getDelayTime() != 0){
rest((int) getDelayTime());
}
setDelayTime(0);
} else {
rest(200);
}
}
}
public void loadData(Token token) throws LoadException {
if ( ! token.getName().equals( "anim" ) ){
throw new LoadException( "Starting token is not 'anim'" );
}
Token nameToken = token.findToken( "name" );
if ( nameToken != null ){
setName( nameToken.readString(0) );
}
Token sequenceToken = token.findToken( "sequence" );
if ( sequenceToken != null ){
setSequence( sequenceToken.readString( 0 ) );
}
Token typeToken = token.findToken( "type" );
if ( typeToken != null ){
setType( typeToken.readString( 0 ) );
}
Token keyToken = token.findToken( "keys" );
if ( keyToken != null ){
for (Iterator it = keyToken.iterator(); it.hasNext(); ){
String key = ((Token)it.next()).toString();
keys.add(key);
}
/*
try{
for(int i = 0; ; i += 1 ){
String temp = keyToken.readString(i);
if ( temp != null ){
keys.add( temp );
} else {
break;
}
}
} catch(Exception e) {
e.printStackTrace();
}
*/
}
Token rangeToken = token.findToken( "range" );
if ( rangeToken != null ){
range = rangeToken.readInt(0);
}
Token basedirToken = token.findToken( "basedir" );
if ( basedirToken != null ){
setBaseDirectory( basedirToken.readString( 0 ) );
}
events.clear();
for ( Iterator it = token.getTokens().iterator(); it.hasNext(); ){
Token t = (Token) it.next();
AnimationEvent ae = EventFactory.getEvent(t.getName());
if( ae != null ){
ae.loadToken(t);
events.add( ae );
}
}
}
public Token getToken(){
Token token = new Token();
token.addToken( new Token( "anim" ) );
token.addToken(new String[]{"name", "\"" + name + "\""});
if ( ! type.equals("none") ){
token.addToken(new String[]{"type", type});
}
if ( ! sequence.equals( "none" ) ){
token.addToken( new String[]{ "sequence", "\"" + sequence + "\"", "junk" } );
}
if ( ! keys.isEmpty() ){
Token keyToken = new Token( "keys" );
keyToken.addToken( new Token( "keys"));
for ( Iterator it = keys.iterator(); it.hasNext(); ){
String key = (String) it.next();
keyToken.addToken( new Token( key ) );
}
token.addToken( keyToken );
}
if ( range != 0 ){
token.addToken(new String[]{"range", Integer.toString(range)});
}
if( ! baseDirectory.equals( "" ) ){
token.addToken(new String[]{"basedir", baseDirectory});
}
for ( Iterator it = events.iterator(); it.hasNext(); ){
AnimationEvent event = (AnimationEvent) it.next();
token.addToken( event.getToken() );
}
return token;
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.