answer
stringlengths 17
10.2M
|
|---|
package com.exedio.cope.instrument;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Modifier;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import com.exedio.cope.FinalViolationException;
import com.exedio.cope.Item;
import com.exedio.cope.LengthViolationException;
import com.exedio.cope.MandatoryViolationException;
import com.exedio.cope.SetValue;
import com.exedio.cope.Type;
import com.exedio.cope.UniqueViolationException;
import com.exedio.cope.util.ReactivationConstructorDummy;
final class Generator
{
private static final String STRING = String.class.getName();
private static final String SET_VALUE = SetValue.class.getName();
private static final String ITEM = Item.class.getName();
private static final String REACTIVATION = ReactivationConstructorDummy.class.getName();
private static final char ATTRIBUTE_MAP_KEY = 'k';
private static final String THROWS_NULL = "if {0} is null.";
private static final String THROWS_UNIQUE = "if {0} is not unique.";
private static final String THROWS_LENGTH = "if {0} violates its length constraint.";
private static final String CONSTRUCTOR_INITIAL = "Creates a new {0} with all the fields initially needed.";
private static final String CONSTRUCTOR_INITIAL_PARAMETER = "the initial value for field {0}.";
private static final String CONSTRUCTOR_INITIAL_CUSTOMIZE = "It can be customized with the tags " +
"<tt>@" + CopeType.TAG_INITIAL_CONSTRUCTOR + " public|package|protected|private|none</tt> " +
"in the class comment and " +
"<tt>@" + CopeFeature.TAG_INITIAL + "</tt> in the comment of fields.";
private static final String CONSTRUCTOR_GENERIC = "Creates a new {0} and sets the given fields initially.";
private static final String CONSTRUCTOR_GENERIC_CALLED = "This constructor is called by {0}.";
private static final String CONSTRUCTOR_GENERIC_CUSTOMIZE = "It can be customized with the tag " +
"<tt>@" + CopeType.TAG_GENERIC_CONSTRUCTOR + " public|package|protected|private|none</tt> " +
"in the class comment.";
private static final String CONSTRUCTOR_REACTIVATION = "Reactivation constructor. Used for internal purposes only.";
private static final String GETTER = "Returns the value of the persistent field {0}.";
private static final String GETTER_CUSTOMIZE = "It can be customized with the tag " +
"<tt>@" + CopeFeature.TAG_GETTER + " public|package|protected|private|none|non-final|boolean-as-is</tt> " +
"in the comment of the field.";
private static final String CHECKER = "Returns whether the given value corresponds to the hash in {0}.";
private static final String SETTER = "Sets a new value for the persistent field {0}.";
private static final String SETTER_CUSTOMIZE = "It can be customized with the tag " +
"<tt>@" + CopeFeature.TAG_SETTER + " public|package|protected|private|none|non-final</tt> " +
"in the comment of the field.";
private static final String SETTER_MEDIA = "Sets the content of media {0}.";
private static final String SETTER_MEDIA_IOEXCEPTION = "if accessing {0} throws an IOException.";
private static final String GETTER_MEDIA_IS_NULL = "Returns whether media {0} is null.";
private static final String GETTER_MEDIA_URL = "Returns a URL the content of the media {0} is available under.";
private static final String GETTER_MEDIA_CONTENT_TYPE = "Returns the content type of the media {0}.";
private static final String GETTER_MEDIA_LENGTH = "Returns the body length of the media {0}.";
private static final String GETTER_MEDIA_LASTMODIFIED = "Returns the last modification date of media {0}.";
private static final String GETTER_MEDIA_BODY_BYTE = "Returns the body of the media {0}.";
private static final String GETTER_MEDIA_BODY_STREAM = "Writes the body of media {0} into the given stream.";
private static final String GETTER_MEDIA_BODY_FILE = "Writes the body of media {0} into the given file.";
private static final String GETTER_MEDIA_BODY_EXTRA = "Does nothing, if the media is null.";
private static final String GETTER_STREAM_WARNING = "<b>You are responsible for closing the stream, when you are finished!</b>";
private static final String TOUCHER = "Sets the current date for the date field {0}.";
private static final String FINDER_UNIQUE = "Finds a {0} by it''s unique fields.";
private static final String FINDER_UNIQUE_PARAMETER = "shall be equal to field {0}.";
private static final String FINDER_UNIQUE_RETURN = "null if there is no matching item.";
private static final String QUALIFIER = "Returns the qualifier.";
private static final String QUALIFIER_GETTER = "Returns the qualifier.";
private static final String QUALIFIER_SETTER = "Sets the qualifier.";
private static final String ATTIBUTE_LIST_GETTER = "Returns the contents of the field list {0}.";
private static final String ATTIBUTE_LIST_SETTER = "Sets the contents of the field list {0}.";
private static final String ATTIBUTE_SET_GETTER = "Returns the contents of the field set {0}.";
private static final String ATTIBUTE_SET_SETTER = "Sets the contents of the field set {0}.";
private static final String ATTIBUTE_MAP_GETTER = "Returns the value mapped to <tt>" + ATTRIBUTE_MAP_KEY + "</tt> by the field map {0}.";
private static final String ATTIBUTE_MAP_SETTER = "Associates <tt>" + ATTRIBUTE_MAP_KEY + "</tt> to a new value in the field map {0}.";
private static final String RELATION_GETTER = "Returns the items associated to this item by the relation.";
private static final String RELATION_ADDER = "Adds an item to the items associated to this item by the relation.";
private static final String RELATION_REMOVER = "Removes an item from the items associated to this item by the relation.";
private static final String RELATION_SETTER = "Sets the items associated to this item by the relation.";
private static final String TYPE = "The persistent type information for {0}.";
private static final String TYPE_CUSTOMIZE = "It can be customized with the tag " +
"<tt>@" + CopeType.TAG_TYPE + " public|package|protected|private|none</tt> " +
"in the class comment.";
private static final String GENERATED = "This feature has been generated by the cope instrumentor and will be overwritten by the build process.";
/**
* All generated class features get this doccomment tag.
*/
static final String TAG_GENERATED = CopeFeature.TAG_PREFIX + "generated";
private final JavaFile javaFile;
private final Writer o;
private final CRC32 outputCRC = new CRC32();
private final String lineSeparator;
private final boolean longJavadoc;
private static final String localFinal = "final "; // TODO make switchable from ant target
Generator(final JavaFile javaFile, final File outputFile, final boolean longJavadoc) throws FileNotFoundException
{
this.javaFile = javaFile;
this.o = new OutputStreamWriter(new CheckedOutputStream(new FileOutputStream(outputFile), outputCRC));
final String systemLineSeparator = System.getProperty("line.separator");
if(systemLineSeparator==null)
{
System.out.println("warning: property \"line.separator\" is null, using LF (unix style).");
lineSeparator = "\n";
}
else
lineSeparator = systemLineSeparator;
this.longJavadoc = longJavadoc;
}
void close() throws IOException
{
if(o!=null)
o.close();
}
long getCRC()
{
return outputCRC.getValue();
}
private static final String toCamelCase(final String name)
{
final char first = name.charAt(0);
if (Character.isUpperCase(first))
return name;
else
return Character.toUpperCase(first) + name.substring(1);
}
private static final String lowerCamelCase(final String s)
{
final char first = s.charAt(0);
if(Character.isLowerCase(first))
return s;
else
return Character.toLowerCase(first) + s.substring(1);
}
private void writeThrowsClause(final Collection<Class> exceptions)
throws IOException
{
if(!exceptions.isEmpty())
{
o.write("\t\t\tthrows");
boolean first = true;
for(final Class e : exceptions)
{
if(first)
first = false;
else
o.write(',');
o.write(lineSeparator);
o.write("\t\t\t\t");
o.write(e.getName());
}
o.write(lineSeparator);
}
}
private void writeCommentHeader()
throws IOException
{
o.write("/**");
o.write(lineSeparator);
if(longJavadoc)
{
o.write(lineSeparator);
o.write("\t **");
o.write(lineSeparator);
}
}
private void writeCommentFooter()
throws IOException
{
writeCommentFooter(null);
}
private void writeCommentFooter(final String extraComment)
throws IOException
{
o.write("\t * @" + TAG_GENERATED + ' ');
o.write(GENERATED);
o.write(lineSeparator);
if(extraComment!=null)
{
o.write("\t * ");
o.write(extraComment);
o.write(lineSeparator);
}
o.write("\t */");
o.write(lineSeparator);
o.write('\t'); // TODO put this into calling methods
}
private static final String link(final String target)
{
return "{@link #" + target + '}';
}
private static final String link(final String target, final String name)
{
return "{@link #" + target + ' ' + name + '}';
}
private static final String format(final String pattern, final String parameter1)
{
return MessageFormat.format(pattern, new Object[]{ parameter1 });
}
private static final String format(final String pattern, final String parameter1, final String parameter2)
{
return MessageFormat.format(pattern, new Object[]{ parameter1, parameter2 });
}
private void writeInitialConstructor(final CopeType type)
throws IOException
{
if(!type.hasInitialConstructor())
return;
final List<CopeFeature> initialFeatures = type.getInitialFeatures();
final SortedSet<Class> constructorExceptions = type.getConstructorExceptions();
writeCommentHeader();
o.write("\t * ");
o.write(format(CONSTRUCTOR_INITIAL, type.name));
o.write(lineSeparator);
for(final CopeFeature feature : initialFeatures)
{
o.write("\t * @param ");
o.write(feature.name);
o.write(' ');
o.write(format(CONSTRUCTOR_INITIAL_PARAMETER, link(feature.name)));
o.write(lineSeparator);
}
for(Iterator i = constructorExceptions.iterator(); i.hasNext(); )
{
final Class constructorException = (Class)i.next();
o.write("\t * @throws ");
o.write(constructorException.getName());
o.write(' ');
boolean first = true;
final StringBuffer initialAttributesBuf = new StringBuffer();
for(final CopeFeature feature : initialFeatures)
{
if(!feature.getSetterExceptions().contains(constructorException))
continue;
if(first)
first = false;
else
initialAttributesBuf.append(", ");
initialAttributesBuf.append(feature.name);
}
final String pattern;
if(MandatoryViolationException.class.equals(constructorException))
pattern = THROWS_NULL;
else if(UniqueViolationException.class.equals(constructorException))
pattern = THROWS_UNIQUE;
else if(LengthViolationException.class.equals(constructorException))
pattern = THROWS_LENGTH;
else
throw new RuntimeException(constructorException.getName());
o.write(format(pattern, initialAttributesBuf.toString()));
o.write(lineSeparator);
}
writeCommentFooter(CONSTRUCTOR_INITIAL_CUSTOMIZE);
writeModifier(type.getInitialConstructorModifier());
o.write(type.name);
o.write('(');
boolean first = true;
for(final CopeFeature feature : initialFeatures)
{
if(first)
first = false;
else
o.write(',');
o.write(lineSeparator);
o.write("\t\t\t\tfinal ");
o.write(feature.getBoxedType());
o.write(' ');
o.write(feature.name);
}
o.write(')');
o.write(lineSeparator);
writeThrowsClause(constructorExceptions);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\tthis(new " + SET_VALUE + "[]{");
o.write(lineSeparator);
for(final CopeFeature feature : initialFeatures)
{
o.write("\t\t\t");
o.write(type.name);
o.write('.');
o.write(feature.name);
o.write(".map(");
o.write(feature.name);
o.write("),");
o.write(lineSeparator);
}
o.write("\t\t});");
o.write(lineSeparator);
o.write("\t}");
}
private void writeGenericConstructor(final CopeType type)
throws IOException
{
final Option option = type.genericConstructorOption;
if(!option.exists)
return;
writeCommentHeader();
o.write("\t * ");
o.write(format(CONSTRUCTOR_GENERIC, type.name));
o.write(lineSeparator);
o.write("\t * ");
o.write(format(CONSTRUCTOR_GENERIC_CALLED, "{@link " + Type.class.getName() + "#newItem Type.newItem}"));
o.write(lineSeparator);
writeCommentFooter(CONSTRUCTOR_GENERIC_CUSTOMIZE);
writeModifier(option.getModifier(type.allowSubTypes() ? Modifier.PROTECTED : Modifier.PRIVATE));
o.write(type.name);
o.write('(');
o.write(localFinal);
o.write(SET_VALUE + "... setValues)");
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\tsuper(setValues);");
o.write(lineSeparator);
o.write("\t}");
}
private void writeReactivationConstructor(final CopeType type)
throws IOException
{
final Option option = type.reactivationConstructorOption;
if(!option.exists)
return;
writeCommentHeader();
o.write("\t * ");
o.write(CONSTRUCTOR_REACTIVATION);
o.write(lineSeparator);
o.write("\t * @see " + ITEM + "#Item(" + REACTIVATION + ",int)");
o.write(lineSeparator);
writeCommentFooter();
writeModifier(option.getModifier(type.allowSubTypes() ? Modifier.PROTECTED : Modifier.PRIVATE));
o.write(type.name);
o.write('(');
o.write(localFinal);
o.write(REACTIVATION + " d,");
o.write(localFinal);
o.write("int pk)");
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\tsuper(d,pk);");
o.write(lineSeparator);
o.write("\t}");
}
private void writeAccessMethods(final CopeAttribute attribute)
throws InjectorParseException, IOException
{
final String type = attribute.getBoxedType();
// getter
if(attribute.getterOption.exists)
{
writeCommentHeader();
o.write("\t * ");
o.write(format(GETTER, link(attribute.name)));
o.write(lineSeparator);
writeStreamWarning(type);
writeCommentFooter(GETTER_CUSTOMIZE);
writeModifier(attribute.getGeneratedGetterModifier());
o.write(type);
if(attribute.hasIsGetter())
o.write(" is");
else
o.write(" get");
o.write(toCamelCase(attribute.name));
o.write(attribute.getterOption.suffix);
o.write("()");
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
writeGetterBody(attribute);
o.write("\t}");
}
writeSetter(attribute);
writeUniqueFinder(attribute);
}
private void writeSetter(final CopeFeature feature) throws IOException
{
final String type = feature.getBoxedType();
if(feature.hasGeneratedSetter())
{
writeCommentHeader();
o.write("\t * ");
o.write(format(SETTER, link(feature.name)));
o.write(lineSeparator);
writeCommentFooter(SETTER_CUSTOMIZE);
writeModifier(feature.getGeneratedSetterModifier());
o.write("void set");
o.write(toCamelCase(feature.name));
o.write(feature.setterOption.suffix);
o.write('(');
o.write(localFinal);
o.write(type);
o.write(' ');
o.write(feature.name);
o.write(')');
o.write(lineSeparator);
writeThrowsClause(feature.getSetterExceptions());
o.write("\t{");
o.write(lineSeparator);
writeSetterBody(feature);
o.write("\t}");
// touch for date attributes
if(feature.isTouchable())
{
writeCommentHeader();
o.write("\t * ");
o.write(format(TOUCHER, link(feature.name)));
o.write(lineSeparator);
writeCommentFooter();
writeModifier(feature.getGeneratedSetterModifier());
o.write("void touch");
o.write(toCamelCase(feature.name));
o.write("()");
o.write(lineSeparator);
writeThrowsClause(feature.getToucherExceptions());
o.write("\t{");
o.write(lineSeparator);
writeToucherBody(feature);
o.write("\t}");
}
}
}
private void writeHash(final CopeHash hash)
throws IOException, InjectorParseException
{
// checker
writeCommentHeader();
o.write("\t * ");
o.write(format(CHECKER, link(hash.name)));
o.write(lineSeparator);
writeCommentFooter();
writeModifier(hash.getGeneratedCheckerModifier());
o.write("boolean check");
o.write(toCamelCase(hash.name));
o.write('(');
o.write(localFinal);
o.write(STRING + ' ');
o.write(hash.name);
o.write(')');
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
writeCheckerBody(hash);
o.write("\t}");
writeSetter(hash);
}
private void writeMediaGetter(final CopeMedia media,
final Class returnType,
final String part,
final String commentPattern)
throws IOException
{
final String prefix = (boolean.class==returnType) ? "is" : "get";
writeCommentHeader();
o.write("\t * ");
o.write(format(commentPattern, link(media.name)));
o.write(lineSeparator);
writeStreamWarning(returnType.getName());
writeCommentFooter();
writeModifier(media.getGeneratedGetterModifier());
o.write(returnType.getName());
if(returnType==byte.class)
o.write("[]");
o.write(' ');
o.write(prefix);
o.write(toCamelCase(media.name));
o.write(part);
o.write("()");
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\treturn ");
o.write(media.parent.name);
o.write('.');
o.write(media.name);
o.write('.');
o.write(prefix);
o.write(part);
o.write("(this);");
o.write(lineSeparator);
o.write("\t}");
}
private void writeMediaGetter(
final CopeMedia media,
final Class dataType,
final String commentPattern)
throws IOException
{
writeCommentHeader();
o.write("\t * ");
o.write(format(commentPattern, link(media.name)));
o.write(lineSeparator);
o.write("\t * ");
o.write(GETTER_MEDIA_BODY_EXTRA);
o.write(lineSeparator);
o.write("\t * @throws ");
o.write(IOException.class.getName());
o.write(' ');
o.write(format(SETTER_MEDIA_IOEXCEPTION, "<tt>body</tt>"));
o.write(lineSeparator);
writeCommentFooter();
writeModifier(media.getGeneratedGetterModifier());
o.write("void get");
o.write(toCamelCase(media.name));
o.write("Body(");
o.write(localFinal);
o.write(dataType.getName());
o.write(" body)");
o.write(lineSeparator);
final TreeSet<Class> setterExceptions = new TreeSet<Class>();
setterExceptions.addAll(Arrays.asList(new Class[]{IOException.class})); // TODO
writeThrowsClause(setterExceptions);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\t");
o.write(media.parent.name);
o.write('.');
o.write(media.name);
o.write(".getBody(this,body);");
o.write(lineSeparator);
o.write("\t}");
}
private void writeMediaSetter(final CopeMedia media, final Class dataType)
throws IOException
{
writeCommentHeader();
o.write("\t * ");
o.write(format(SETTER_MEDIA, link(media.name)));
o.write(lineSeparator);
if(dataType!=byte.class)
{
o.write("\t * @throws ");
o.write(IOException.class.getName());
o.write(' ');
o.write(format(SETTER_MEDIA_IOEXCEPTION, "<tt>body</tt>"));
o.write(lineSeparator);
}
writeCommentFooter();
writeModifier(media.getGeneratedSetterModifier());
o.write("void set");
o.write(toCamelCase(media.name));
o.write('(');
o.write(localFinal);
o.write(dataType.getName());
if(dataType==byte.class)
o.write("[]");
o.write(" body,");
o.write(localFinal);
o.write(STRING + " contentType)");
o.write(lineSeparator);
if(dataType!=byte.class)
{
final SortedSet<Class> setterExceptions = new TreeSet<Class>();
setterExceptions.addAll(Arrays.asList(new Class[]{IOException.class})); // TODO
writeThrowsClause(setterExceptions);
}
o.write("\t{");
o.write(lineSeparator);
o.write("\t\t");
o.write(media.parent.name);
o.write('.');
o.write(media.name);
o.write(".set(this,body,contentType);");
o.write(lineSeparator);
o.write("\t}");
}
private void writeMedia(final CopeMedia media)
throws IOException
{
writeMediaGetter(media, boolean.class, "Null", GETTER_MEDIA_IS_NULL);
writeMediaGetter(media, String.class, "URL", GETTER_MEDIA_URL);
writeMediaGetter(media, String.class, "ContentType", GETTER_MEDIA_CONTENT_TYPE);
writeMediaGetter(media, long.class, "LastModified", GETTER_MEDIA_LASTMODIFIED);
writeMediaGetter(media, long.class, "Length", GETTER_MEDIA_LENGTH);
writeMediaGetter(media, byte.class, "Body", GETTER_MEDIA_BODY_BYTE);
writeMediaGetter(media, OutputStream.class, GETTER_MEDIA_BODY_STREAM);
writeMediaGetter(media, File.class, GETTER_MEDIA_BODY_FILE);
if(media.setterOption.exists)
{
writeMediaSetter(media, byte.class);
writeMediaSetter(media, InputStream.class);
writeMediaSetter(media, File.class);
}
}
private void writeUniqueFinder(final CopeAttribute attribute)
throws IOException, InjectorParseException
{
if(!attribute.isImplicitlyUnique())
return;
final String className = attribute.getParent().name;
writeCommentHeader();
o.write("\t * ");
o.write(format(FINDER_UNIQUE, lowerCamelCase(className)));
o.write(lineSeparator);
o.write("\t * @param ");
o.write(attribute.name);
o.write(' ');
o.write(format(FINDER_UNIQUE_PARAMETER, link(attribute.name)));
o.write(lineSeparator);
o.write("\t * @return ");
o.write(FINDER_UNIQUE_RETURN);
o.write(lineSeparator);
writeCommentFooter();
writeModifier((attribute.modifier & (Modifier.PRIVATE|Modifier.PROTECTED|Modifier.PUBLIC)) | (Modifier.STATIC|Modifier.FINAL) );
o.write(className);
o.write(" findBy");
o.write(toCamelCase(attribute.name));
o.write('(');
o.write(localFinal);
o.write(attribute.getBoxedType());
o.write(' ');
o.write(attribute.name);
o.write(')');
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\treturn (");
o.write(className);
o.write(')');
o.write(attribute.parent.name);
o.write('.');
o.write(attribute.name);
o.write(".searchUnique(");
writeAttribute(attribute);
o.write(");");
o.write(lineSeparator);
o.write("\t}");
}
private void writeUniqueFinder(final CopeUniqueConstraint constraint)
throws IOException, InjectorParseException
{
final CopeAttribute[] attributes = constraint.getAttributes();
final String className = attributes[0].getParent().name;
writeCommentHeader();
o.write("\t * ");
o.write(format(FINDER_UNIQUE, lowerCamelCase(className)));
o.write(lineSeparator);
for(int i=0; i<attributes.length; i++)
{
o.write("\t * @param ");
o.write(attributes[i].name);
o.write(' ');
o.write(format(FINDER_UNIQUE_PARAMETER, link(attributes[i].name)));
o.write(lineSeparator);
}
o.write("\t * @return ");
o.write(FINDER_UNIQUE_RETURN);
o.write(lineSeparator);
writeCommentFooter();
writeModifier((constraint.modifier & (Modifier.PRIVATE|Modifier.PROTECTED|Modifier.PUBLIC)) | (Modifier.STATIC|Modifier.FINAL) );
o.write(className);
o.write(" findBy");
o.write(toCamelCase(constraint.name));
o.write('(');
for(int i=0; i<attributes.length; i++)
{
if(i>0)
o.write(',');
final CopeAttribute attribute = attributes[i];
o.write(localFinal);
o.write(attribute.getBoxedType());
o.write(' ');
o.write(attribute.name);
}
o.write(')');
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\treturn (");
o.write(className);
o.write(')');
o.write(attributes[0].parent.name);
o.write('.');
o.write(constraint.name);
o.write(".searchUnique(new Object[]{");
writeAttribute(attributes[0]);
for(int i = 1; i<attributes.length; i++)
{
o.write(',');
writeAttribute(attributes[i]);
}
o.write("});");
o.write(lineSeparator);
o.write("\t}");
}
private void writeAttribute(final CopeAttribute attribute)
throws IOException
{
if(attribute.isBoxed())
o.write(attribute.getBoxingPrefix());
o.write(attribute.name);
if(attribute.isBoxed())
o.write(attribute.getBoxingPostfix());
}
private void writeQualifierParameters(final CopeQualifier qualifier)
throws IOException, InjectorParseException
{
final CopeAttribute[] keys = qualifier.getKeyAttributes();
for(int i = 0; i<keys.length; i++)
{
if(i>0)
o.write(',');
o.write(localFinal);
o.write(keys[i].persistentType);
o.write(' ');
o.write(keys[i].name);
}
}
private void writeQualifierCall(final CopeQualifier qualifier)
throws IOException, InjectorParseException
{
final CopeAttribute[] keys = qualifier.getKeyAttributes();
for(int i = 0; i<keys.length; i++)
{
o.write(',');
o.write(keys[i].name);
}
}
private void writeQualifier(final CopeQualifier qualifier)
throws IOException, InjectorParseException
{
final String qualifierClassName = qualifier.parent.javaClass.getFullName();
writeCommentHeader();
o.write("\t * ");
o.write(QUALIFIER);
o.write(lineSeparator);
writeCommentFooter();
o.write("public final "); // TODO: obey attribute visibility
o.write(qualifierClassName);
o.write(" get");
o.write(toCamelCase(qualifier.name));
o.write('(');
writeQualifierParameters(qualifier);
o.write(')');
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\treturn (");
o.write(qualifierClassName);
o.write(')');
o.write(qualifierClassName);
o.write('.');
o.write(qualifier.name);
o.write(".getQualifier(this");
writeQualifierCall(qualifier);
o.write(");");
o.write(lineSeparator);
o.write("\t}");
final List<CopeAttribute> qualifierAttributes = Arrays.asList(qualifier.getAttributes());
for(final CopeFeature feature : qualifier.parent.getFeatures())
{
if(feature instanceof CopeAttribute)
{
final CopeAttribute attribute = (CopeAttribute)feature;
if(qualifierAttributes.contains(attribute))
continue;
writeQualifierGetter(qualifier, attribute);
writeQualifierSetter(qualifier, attribute);
}
}
}
private void writeQualifierGetter(final CopeQualifier qualifier, final CopeAttribute attribute)
throws IOException, InjectorParseException
{
if(attribute.getterOption.exists)
{
final String qualifierClassName = qualifier.parent.javaClass.getFullName();
writeCommentHeader();
o.write("\t * ");
o.write(QUALIFIER_GETTER);
o.write(lineSeparator);
writeCommentFooter();
writeModifier(attribute.getGeneratedGetterModifier());
o.write(attribute.persistentType);
o.write(" get");
o.write(toCamelCase(attribute.name));
o.write(attribute.getterOption.suffix);
o.write('(');
writeQualifierParameters(qualifier);
o.write(')');
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\treturn ");
o.write(qualifierClassName);
o.write('.');
o.write(qualifier.name);
o.write(".get(");
o.write(qualifierClassName);
o.write('.');
o.write(attribute.name);
o.write(",this");
writeQualifierCall(qualifier);
o.write(");");
o.write(lineSeparator);
o.write("\t}");
}
}
private void writeQualifierSetter(final CopeQualifier qualifier, final CopeAttribute attribute)
throws IOException, InjectorParseException
{
if(attribute.setterOption.exists)
{
final String qualifierClassName = qualifier.parent.javaClass.getFullName();
writeCommentHeader();
o.write("\t * ");
o.write(QUALIFIER_SETTER);
o.write(lineSeparator);
writeCommentFooter();
writeModifier(attribute.getGeneratedSetterModifier());
o.write("void set");
o.write(toCamelCase(attribute.name));
o.write(attribute.setterOption.suffix);
o.write('(');
writeQualifierParameters(qualifier);
o.write(',');
o.write(localFinal);
o.write(attribute.getBoxedType());
o.write(' ');
o.write(attribute.name);
o.write(')');
o.write(lineSeparator);
writeThrowsClause(attribute.getSetterExceptions());
o.write("\t{");
o.write(lineSeparator);
o.write("\t\t");
o.write(qualifierClassName);
o.write('.');
o.write(qualifier.name);
o.write(".set(");
o.write(qualifierClassName);
o.write('.');
o.write(attribute.name);
o.write(',');
o.write(attribute.name);
o.write(",this");
writeQualifierCall(qualifier);
o.write(");");
o.write(lineSeparator);
o.write("\t}");
}
}
private void write(final CopeAttributeList list)
throws IOException
{
final String type = list.getType();
final String name = list.name;
writeCommentHeader();
o.write("\t * ");
o.write(MessageFormat.format(list.set?ATTIBUTE_SET_GETTER:ATTIBUTE_LIST_GETTER, link(name)));
o.write(lineSeparator);
writeCommentFooter();
o.write("public final "); // TODO: obey attribute visibility
o.write((list.set?Set.class:List.class).getName());
o.write('<');
o.write(type);
o.write("> get");
o.write(toCamelCase(list.name));
o.write("()");
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\treturn ");
o.write(list.parent.name);
o.write('.');
o.write(list.name);
o.write(".get(this);");
o.write(lineSeparator);
o.write("\t}");
writeCommentHeader();
o.write("\t * ");
o.write(MessageFormat.format(list.set?ATTIBUTE_SET_SETTER:ATTIBUTE_LIST_SETTER, link(name)));
o.write(lineSeparator);
writeCommentFooter();
o.write("public final void set"); // TODO: obey attribute visibility
o.write(toCamelCase(list.name));
o.write('(');
o.write(localFinal);
o.write(Collection.class.getName());
o.write("<? extends ");
o.write(type);
o.write("> ");
o.write(list.name);
o.write(')');
o.write(lineSeparator);
writeThrowsClause(Arrays.asList(new Class[]{
UniqueViolationException.class,
MandatoryViolationException.class,
LengthViolationException.class,
FinalViolationException.class,
ClassCastException.class}));
o.write("\t{");
o.write(lineSeparator);
o.write("\t\t");
o.write(list.parent.name);
o.write('.');
o.write(list.name);
o.write(".set(this,");
o.write(list.name);
o.write(");");
o.write(lineSeparator);
o.write("\t}");
}
private void write(final CopeAttributeMap map) throws IOException
{
if(true) // TODO SOON getter option
{
writeCommentHeader();
o.write("\t * ");
o.write(MessageFormat.format(ATTIBUTE_MAP_GETTER, link(map.name)));
o.write(lineSeparator);
writeCommentFooter();
o.write("public final "); // TODO SOON getter option
o.write(map.getValueType());
o.write(" get");
o.write(toCamelCase(map.name));
o.write('(');
o.write(localFinal);
o.write(map.getKeyType());
o.write(" " + ATTRIBUTE_MAP_KEY + ")");
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\treturn ");
o.write(map.parent.name);
o.write('.');
o.write(map.name);
o.write(".get(this," + ATTRIBUTE_MAP_KEY + ");");
o.write(lineSeparator);
o.write("\t}");
}
if(true) // TODO SOON setter option
{
writeCommentHeader();
o.write("\t * ");
o.write(MessageFormat.format(ATTIBUTE_MAP_SETTER, link(map.name)));
o.write(lineSeparator);
writeCommentFooter();
o.write("public final "); // TODO SOON setter option
o.write("void set");
o.write(toCamelCase(map.name));
o.write('(');
o.write(localFinal);
o.write(map.getKeyType());
o.write(" " + ATTRIBUTE_MAP_KEY + ',');
o.write(localFinal);
o.write(map.getValueType());
o.write(' ');
o.write(map.name);
o.write(')');
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\t");
o.write(map.parent.name);
o.write('.');
o.write(map.name);
o.write(".set(this," + ATTRIBUTE_MAP_KEY + ',');
o.write(map.name);
o.write(");");
o.write(lineSeparator);
o.write("\t}");
}
}
private void writeRelation(final CopeRelation relation, final boolean source)
throws IOException
{
final boolean vector = relation.vector;
final String endType = relation.getEndType(source);
final String endName = relation.getEndName(source);
final String endNameCamel = toCamelCase(endName);
final String methodName = source ? "Sources" : "Targets";
final String className = relation.parent.javaClass.getFullName();
// getter
if(!vector || !source)
{
writeCommentHeader();
o.write("\t * ");
o.write(RELATION_GETTER);
o.write(lineSeparator);
writeCommentFooter();
o.write("public final " + List.class.getName() + '<'); // TODO: obey attribute visibility
o.write(endType);
o.write("> get");
o.write(endNameCamel);
o.write("()");
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\treturn ");
o.write(className);
o.write('.');
o.write(relation.name);
o.write(".get");
o.write(methodName);
o.write("(this);");
o.write(lineSeparator);
o.write("\t}");
}
// adder
if(!vector)
{
writeCommentHeader();
o.write("\t * ");
o.write(RELATION_ADDER);
o.write(lineSeparator);
writeCommentFooter();
o.write("public final boolean addTo"); // TODO: obey attribute visibility
o.write(endNameCamel);
o.write('(');
o.write(localFinal);
o.write(endType);
o.write(' ');
o.write(endName);
o.write(')');
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\treturn ");
o.write(className);
o.write('.');
o.write(relation.name);
o.write(".addTo");
o.write(methodName);
o.write("(this,");
o.write(endName);
o.write(");");
o.write(lineSeparator);
o.write("\t}");
}
// remover
if(!vector)
{
writeCommentHeader();
o.write("\t * ");
o.write(RELATION_REMOVER);
o.write(lineSeparator);
writeCommentFooter();
o.write("public final boolean removeFrom"); // TODO: obey attribute visibility
o.write(endNameCamel);
o.write('(');
o.write(localFinal);
o.write(endType);
o.write(' ');
o.write(endName);
o.write(')');
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\treturn ");
o.write(className);
o.write('.');
o.write(relation.name);
o.write(".removeFrom");
o.write(methodName);
o.write("(this,");
o.write(endName);
o.write(");");
o.write(lineSeparator);
o.write("\t}");
}
// setter
if(!vector || !source)
{
writeCommentHeader();
o.write("\t * ");
o.write(RELATION_SETTER);
o.write(lineSeparator);
writeCommentFooter();
o.write("public final void set"); // TODO: obey attribute visibility
o.write(endNameCamel);
o.write('(');
o.write(localFinal);
o.write(Collection.class.getName() + "<? extends ");
o.write(endType);
o.write("> ");
o.write(endName);
o.write(')');
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\t");
o.write(className);
o.write('.');
o.write(relation.name);
o.write(".set");
o.write(methodName);
o.write("(this,");
o.write(endName);
o.write(");");
o.write(lineSeparator);
o.write("\t}");
}
}
private void writeType(final CopeType type)
throws IOException
{
final Option option = type.typeOption;
if(option.exists)
{
writeCommentHeader();
o.write("\t * ");
o.write(format(TYPE, lowerCamelCase(type.name)));
o.write(lineSeparator);
writeCommentFooter(TYPE_CUSTOMIZE);
writeModifier(option.getModifier(Modifier.PUBLIC) | Modifier.STATIC | Modifier.FINAL); // TODO obey class visibility
o.write(Type.class.getName()+'<');
o.write(type.name);
o.write("> TYPE = newType(");
o.write(type.name);
o.write(".class)");
o.write(lineSeparator);
o.write(';');
}
}
void write() throws IOException, InjectorParseException
{
final String buffer = javaFile.buffer.toString();
int previousClassEndPosition = 0;
for(final JavaClass javaClass : javaFile.getClasses())
{
final CopeType type = CopeType.getCopeType(javaClass);
final int classEndPosition = javaClass.getClassEndPosition();
if(type!=null)
{
assert previousClassEndPosition<=classEndPosition;
if(previousClassEndPosition<classEndPosition)
o.write(buffer, previousClassEndPosition, classEndPosition-previousClassEndPosition);
writeClassFeatures(type);
previousClassEndPosition = classEndPosition;
}
}
o.write(buffer, previousClassEndPosition, buffer.length()-previousClassEndPosition);
}
private void writeClassFeatures(final CopeType type)
throws IOException, InjectorParseException
{
if(!type.isInterface())
{
writeInitialConstructor(type);
writeGenericConstructor(type);
writeReactivationConstructor(type);
for(final CopeFeature feature : type.getFeatures())
{
if(feature instanceof CopeAttribute)
writeAccessMethods((CopeAttribute)feature);
else if(feature instanceof CopeUniqueConstraint)
writeUniqueFinder((CopeUniqueConstraint)feature);
else if(feature instanceof CopeAttributeList)
write((CopeAttributeList)feature);
else if(feature instanceof CopeAttributeMap)
write((CopeAttributeMap)feature);
else if(feature instanceof CopeMedia)
writeMedia((CopeMedia)feature);
else if(feature instanceof CopeHash)
writeHash((CopeHash)feature);
else if(feature instanceof CopeRelation || feature instanceof CopeQualifier)
; // is handled below
else
throw new RuntimeException(feature.getClass().getName());
}
for(final CopeQualifier qualifier : sort(type.getQualifiers()))
writeQualifier(qualifier);
for(final CopeRelation relation : sort(type.getRelations(true)))
writeRelation(relation, false);
for(final CopeRelation relation : sort(type.getRelations(false)))
writeRelation(relation, true);
writeType(type);
}
}
private static final <X extends CopeFeature> List<X> sort(final List<X> l)
{
final ArrayList<X> result = new ArrayList<X>(l);
Collections.sort(result, new Comparator<X>()
{
public int compare(final X a, final X b)
{
return a.parent.javaClass.getFullName().compareTo(b.parent.javaClass.getFullName());
}
});
return result;
}
/**
* Identation contract:
* This methods is called, when o stream is immediately after a line break,
* and it should return the o stream after immediately after a line break.
* This means, doing nothing fullfils the contract.
*/
private void writeGetterBody(final CopeAttribute attribute)
throws IOException
{
o.write("\t\treturn ");
o.write(attribute.parent.name);
o.write('.');
o.write(attribute.name);
o.write(".get");
if(attribute.isBoxed())
o.write("Mandatory");
o.write("(this)");
o.write(';');
o.write(lineSeparator);
}
/**
* Identation contract:
* This methods is called, when o stream is immediately after a line break,
* and it should return the o stream after immediately after a line break.
* This means, doing nothing fullfils the contract.
*/
private void writeSetterBody(final CopeFeature feature)
throws IOException
{
o.write("\t\t");
o.write(feature.parent.name);
o.write('.');
o.write(feature.name);
o.write(".set(this,");
o.write(feature.name);
o.write(");");
o.write(lineSeparator);
}
/**
* Identation contract:
* This methods is called, when o stream is immediately after a line break,
* and it should return the o stream after immediately after a line break.
* This means, doing nothing fullfils the contract.
*/
private void writeToucherBody(final CopeFeature feature)
throws IOException
{
o.write("\t\t");
o.write(feature.parent.name);
o.write('.');
o.write(feature.name);
o.write(".touch(this);");
o.write(lineSeparator);
}
/**
* Identation contract:
* This methods is called, when o stream is immediately after a line break,
* and it should return the o stream after immediately after a line break.
* This means, doing nothing fullfils the contract.
*/
private void writeCheckerBody(final CopeHash hash)
throws IOException
{
o.write("\t\treturn ");
o.write(hash.parent.name);
o.write('.');
o.write(hash.name);
o.write(".check(this,");
o.write(hash.name);
o.write(");");
o.write(lineSeparator);
}
/**
* Identation contract:
* This methods is called, when o stream is immediately after a line break,
* and it should return the o stream after immediately after a line break.
* This means, doing nothing fullfils the contract.
*/
private void writeSetterBody(final CopeHash hash)
throws IOException, InjectorParseException
{
o.write("\t\t");
o.write(hash.parent.name);
o.write('.');
o.write(hash.name);
o.write(".set(this,");
o.write(hash.name);
o.write(");");
o.write(lineSeparator);
}
private void writeStreamWarning(final String type) throws IOException
{
if(InputStream.class.getName().equals(type))
{
o.write("\t * ");
o.write(GETTER_STREAM_WARNING);
o.write(lineSeparator);
}
}
private void writeModifier(final int modifier) throws IOException
{
final String modifierString = Modifier.toString(modifier);
if(modifierString.length()>0)
{
o.write(modifierString);
o.write(' ');
}
}
}
|
package de.gurkenlabs.litiengine.util;
import de.gurkenlabs.litiengine.entities.Material;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EventListener;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public final class ReflectionUtilities {
private static final Logger log = Logger.getLogger(ReflectionUtilities.class.getName());
private ReflectionUtilities() {
throw new UnsupportedOperationException();
}
public static <T> Field getField(Class<T> cls, final String fieldName) {
return getField(cls, fieldName, true);
}
public static <T> Field getField(Class<T> cls, final String fieldName, boolean recursive) {
for (final Field field : cls.getDeclaredFields()) {
if (field.getName().equalsIgnoreCase(fieldName)) {
return field;
}
}
if (recursive && cls.getSuperclass() != null && !cls.getSuperclass().equals(Object.class)) {
Field f = getField(cls.getSuperclass(), fieldName, true);
if (f != null) {
return f;
}
}
log.log(Level.WARNING, "Could not find field [{0}] on class [{1}] or its parents.", new Object[]{fieldName, cls});
return null;
}
@SuppressWarnings("unchecked")
public static <V> V getStaticValue(Class<?> cls, String fieldName) {
Field keyField = ReflectionUtilities.getField(cls, fieldName);
if (keyField == null) {
return null;
}
try {
return (V) keyField.get(null);
} catch (Exception e) {
return null;
}
}
/**
* Recursively gets all fields of the specified type, respecting parent classes.
*
* @param fields The list containing all fields.
* @param type The type to retrieve the fields from.
* @return All fields of the specified type, including the fields of the parent classes.
*/
public static List<Field> getAllFields(List<Field> fields, Class<?> type) {
fields.addAll(Arrays.asList(type.getDeclaredFields()));
if (type.getSuperclass() != null && !type.getSuperclass().equals(Object.class)) {
getAllFields(fields, type.getSuperclass());
}
return fields;
}
/**
* Recursively gets a method by the the specified name respecting the parent classes and the parameters of the declaration.
*
* @param name The name of the method.
* @param type The type on which to search for the method.
* @param parameterTypes The types of the parameters defined by the method declaration.
* @return The found method or null if no such method exists.
*/
public static Method getMethod(String name, Class<?> type, Class<?>... parameterTypes) {
Method method = null;
try {
method = type.getDeclaredMethod(name, parameterTypes);
} catch (NoSuchMethodException e) {
if (type.getSuperclass() != null && !type.getSuperclass().equals(Object.class)) {
return getMethod(name, type.getSuperclass(), parameterTypes);
}
}
return method;
}
public static <T, C> boolean setValue(Class<C> cls, Object instance, final String fieldName, final T value) {
try {
final Method method = getSetter(cls, fieldName);
if (method != null) {
// set the new value with the setter
method.invoke(instance, value);
return true;
} else {
// if no setter is present, try to set the field directly
for (final Field field : cls.getDeclaredFields()) {
if (field.getName().equals(fieldName) && (field.getType() == value.getClass() || isWrapperType(field.getType(), value.getClass()) || isWrapperType(value.getClass(), field.getType()))) {
if (!field.isAccessible()) {
field.setAccessible(true);
}
field.set(instance, value);
return true;
}
}
}
} catch (final SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
log.log(Level.SEVERE, String.format("%s (%s-%s)", e.getMessage(), fieldName, value), e);
}
return false;
}
public static <T> boolean setEnumPropertyValue(Class<T> cls, Object instance, final Field field, String propertyName, String value) {
final Object[] enumArray = field.getType().getEnumConstants();
for (final Object enumConst : enumArray) {
if (enumConst != null && enumConst.toString().equalsIgnoreCase(value)) {
return ReflectionUtilities.setValue(cls, instance, propertyName, field.getType().cast(enumConst));
}
}
return false;
}
public static <T> Method getSetter(Class<T> cls, final String fieldName) {
for (final Method method : getSetters(cls)) {
if (method.getName().equalsIgnoreCase("set" + fieldName)) {
return method;
}
}
return null;
}
public static <T> Collection<Method> getSetters(Class<T> cls) {
Collection<Method> methods = new ArrayList<>();
for (final Method method : cls.getMethods()) {
// method must start with "set" and have only one parameter, matching the
// specified fieldType
if (method.getName().toLowerCase().startsWith("set") && method.getParameters().length == 1) {
if (!method.isAccessible()) {
try {
method.setAccessible(true);
} catch (SecurityException e) {
continue;
}
}
methods.add(method);
}
}
return Collections.unmodifiableCollection(methods);
}
public static <T, C> boolean isWrapperType(Class<T> primitive, Class<C> potentialWrapper) {
if (!primitive.isPrimitive() || potentialWrapper.isPrimitive()) {
return false;
}
if (primitive == boolean.class) {
return potentialWrapper == Boolean.class;
}
if (primitive == char.class) {
return potentialWrapper == Character.class;
}
if (primitive == byte.class) {
return potentialWrapper == Byte.class;
}
if (primitive == short.class) {
return potentialWrapper == Short.class;
}
if (primitive == int.class) {
return potentialWrapper == Integer.class;
}
if (primitive == long.class) {
return potentialWrapper == Long.class;
}
if (primitive == float.class) {
return potentialWrapper == Float.class;
}
if (primitive == double.class) {
return potentialWrapper == Double.class;
}
if (primitive == void.class) {
return potentialWrapper == Void.class;
}
return false;
}
public static <T> boolean setFieldValue(final Class<T> cls, final Object instance, final String fieldName, final String value) {
// if a setter is present, instance method will use it, otherwise it will
// directly try to set the field.
final Field field = getField(cls, fieldName);
if (field == null) {
return false;
}
// final fields cannot be set
if (Modifier.isFinal(field.getModifiers())) {
return false;
}
try {
if (field.getType().equals(boolean.class)) {
return setValue(cls, instance, fieldName, Boolean.parseBoolean(value));
} else if (field.getType().equals(int.class)) {
return setValue(cls, instance, fieldName, Integer.parseInt(value));
} else if (field.getType().equals(float.class)) {
return setValue(cls, instance, fieldName, Float.parseFloat(value));
} else if (field.getType().equals(double.class)) {
return setValue(cls, instance, fieldName, Double.parseDouble(value));
} else if (field.getType().equals(short.class)) {
return setValue(cls, instance, fieldName, Short.parseShort(value));
} else if (field.getType().equals(byte.class)) {
return setValue(cls, instance, fieldName, Byte.parseByte(value));
} else if (field.getType().equals(long.class)) {
return setValue(cls, instance, fieldName, Long.parseLong(value));
} else if (field.getType().equals(String.class)) {
return setValue(cls, instance, fieldName, value);
} else if (field.getType().equals(String[].class)) {
return setValue(cls, instance, fieldName, value.split(","));
} else if (field.getType() instanceof Class && field.getType().isEnum()) {
return setEnumPropertyValue(cls, instance, field, fieldName, value);
} else if (field.getType().equals(Material.class)) {
return setValue(cls, instance, fieldName, Material.get(value));
}
// TODO: implement support for Attribute and RangeAttribute fields
} catch (final NumberFormatException e) {
log.log(Level.SEVERE, e.getMessage(), e);
}
return false;
}
public static List<Method> getMethodsAnnotatedWith(final Class<?> type, final Class<? extends Annotation> annotation) {
final List<Method> methods = new ArrayList<>();
Class<?> clazz = type;
while (clazz != Object.class) { // need to iterated thought hierarchy in order to retrieve methods from above the current instance
// iterate though the list of methods declared in the class represented by class variable, and add those annotated with the specified annotation
final List<Method> allMethods = new ArrayList<>(Arrays.asList(clazz.getDeclaredMethods()));
for (final Method method : allMethods) {
if (method.isAnnotationPresent(annotation)) {
methods.add(method);
}
}
// move to the upper class in the hierarchy in search for more methods
clazz = clazz.getSuperclass();
}
return methods;
}
/**
* Gets the events for the specified type.
* <p>
* This will search for all methods that have a parameter of type {@code EventListener} and match the LITIENGINE's naming conventions
* for event subscription (i.e. the method name starts with one of the prefixes "add" or "on".
* </p>
*
* @param type The type to inspect the events on.
* @return All methods on the specified type that are considered to be events.
* @see EventListener
*/
public static Collection<Method> getEvents(final Class<?> type) {
final String eventAddPrefix = "add";
final String eventOnPrefix = "on";
final List<Method> events = new ArrayList<>();
Class<?> clazz = type;
while (clazz != Object.class) { // need to iterated thought hierarchy in order to retrieve methods from above the current instance
// iterate though the list of methods declared in the class represented by class variable, and add those annotated with the specified annotation
final List<Method> allMethods = new ArrayList<>(Arrays.asList(clazz.getDeclaredMethods()));
for (final Method method : allMethods) {
for (Class<?> paramtype : method.getParameterTypes()) {
if (EventListener.class.isAssignableFrom(paramtype) && (method.getName().startsWith(eventAddPrefix) || method.getName().startsWith(eventOnPrefix))) {
events.add(method);
}
}
}
// move to the upper class in the hierarchy in search for more methods
clazz = clazz.getSuperclass();
}
return events;
}
@SuppressWarnings("unchecked")
public static <T> T getDefaultValue(Class<T> clazz) {
return (T) Array.get(Array.newInstance(clazz, 1), 0);
}
}
|
package com.exedio.cope.instrument;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.reflect.Modifier;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import com.exedio.cope.AttributeValue;
import com.exedio.cope.LengthViolationException;
import com.exedio.cope.MandatoryViolationException;
import com.exedio.cope.ReadOnlyViolationException;
import com.exedio.cope.Type;
import com.exedio.cope.UniqueViolationException;
import com.exedio.cope.util.ClassComparator;
import com.exedio.cope.util.ReactivationConstructorDummy;
final class Generator
{
private static final String THROWS_NULL = "if {0} is null.";
private static final String THROWS_UNIQUE = "if {0} is not unique.";
private static final String THROWS_LENGTH = "if {0} violates its length constraint.";
private static final String CONSTRUCTOR_INITIAL = "Creates a new {0} with all the attributes initially needed.";
private static final String CONSTRUCTOR_INITIAL_PARAMETER = "the initial value for attribute {0}.";
private static final String CONSTRUCTOR_INITIAL_CUSTOMIZE = "It can be customized with the tags " +
"<code>@"+Instrumentor.CLASS_INITIAL_CONSTRUCTOR+" public|package|protected|private|none</code> " +
"in the class comment and " +
"<code>@"+Instrumentor.ATTRIBUTE_INITIAL+"</code> in the comment of attributes.";
private static final String CONSTRUCTOR_GENERIC = "Creates a new {0} and sets the given attributes initially.";
private static final String CONSTRUCTOR_GENERIC_CALLED = "This constructor is called by {0}.";
private static final String CONSTRUCTOR_GENERIC_CUSTOMIZE = "It can be customized with the tag " +
"<code>@"+Instrumentor.CLASS_GENERIC_CONSTRUCTOR+" public|package|protected|private|none</code> " +
"in the class comment.";
private static final String CONSTRUCTOR_REACTIVATION = "Reactivation constructor. Used for internal purposes only.";
private static final String GETTER = "Returns the value of the persistent attribute {0}.";
private static final String GETTER_CUSTOMIZE = "It can be customized with the tag " +
"<code>@"+Instrumentor.ATTRIBUTE_GETTER+" public|package|protected|private|none|non-final|boolean-as-is</code> " +
"in the comment of the attribute.";
private static final String CHECKER = "Returns whether the given value corresponds to the hash in {0}.";
private static final String SETTER = "Sets a new value for the persistent attribute {0}.";
private static final String SETTER_CUSTOMIZE = "It can be customized with the tag " +
"<code>@"+Instrumentor.ATTRIBUTE_SETTER+" public|package|protected|private|none|non-final</code> " +
"in the comment of the attribute.";
private static final String SETTER_MEDIA = "Sets the new data for the media {0}.";
private static final String SETTER_MEDIA_IOEXCEPTION = "if accessing {0} throws an IOException.";
private static final String GETTER_MEDIA_IS_NULL = "Returns whether this media {0} has data available.";
private static final String GETTER_MEDIA_URL = "Returns a URL the data of the media {0} is available under.";
private static final String GETTER_MEDIA_MAJOR = "Returns the major mime type of the media {0}.";
private static final String GETTER_MEDIA_MINOR = "Returns the minor mime type of the media {0}.";
private static final String GETTER_MEDIA_CONTENT_TYPE = "Returns the content type of the media {0}.";
private static final String GETTER_MEDIA_LENGTH_TYPE = "Returns the data length of the media {0}.";
private static final String GETTER_MEDIA_LASTMODIFIED_TYPE = "Returns the last modification date of the media {0}.";
private static final String GETTER_MEDIA_DATA = "Returns the data of the media {0}.";
private static final String GETTER_MEDIA_DATA_FILE = "Reads data of media {0}, and writes it into the given file.";
private static final String GETTER_MEDIA_DATA_FILE2 = "Does nothing, if there is no data for the media.";
private static final String GETTER_STREAM_WARNING = "<b>You are responsible for closing the stream, when you are finished!</b>";
private static final String TOUCHER = "Sets the current date for the date attribute {0}.";
private static final String FINDER_UNIQUE = "Finds a {0} by it''s unique attributes.";
private static final String FINDER_UNIQUE_PARAMETER = "shall be equal to attribute {0}.";
private static final String FINDER_UNIQUE_RETURN = "null if there is no matching item.";
private static final String QUALIFIER = "Returns the qualifier.";
private static final String QUALIFIER_GETTER = "Returns the qualifier.";
private static final String QUALIFIER_SETTER = "Sets the qualifier.";
private static final String VECTOR_GETTER = "Returns the value of the vector.";
private static final String VECTOR_SETTER = "Sets the vector.";
private static final String TYPE = "The persistent type information for {0}.";
private static final String TYPE_CUSTOMIZE = "It can be customized with the tag " +
"<code>@"+Instrumentor.CLASS_TYPE+" public|package|protected|private|none</code> " +
"in the class comment.";
private static final String GENERATED = "This feature has been generated by the cope instrumentor and will be overwritten by the build process.";
private final JavaFile javaFile;
private final Writer o;
private final CRC32 outputCRC = new CRC32();
private final String lineSeparator;
Generator(final JavaFile javaFile, final File outputFile) throws FileNotFoundException
{
this.javaFile = javaFile;
this.o = new OutputStreamWriter(new CheckedOutputStream(new FileOutputStream(outputFile), outputCRC));
final String systemLineSeparator = System.getProperty("line.separator");
if(systemLineSeparator==null)
{
System.out.println("warning: property \"line.separator\" is null, using LF (unix style).");
lineSeparator = "\n";
}
else
lineSeparator = systemLineSeparator;
}
void close() throws IOException
{
if(o!=null)
o.close();
}
long getCRC()
{
return outputCRC.getValue();
}
private static final String toCamelCase(final String name)
{
final char first = name.charAt(0);
if (Character.isUpperCase(first))
return name;
else
return Character.toUpperCase(first) + name.substring(1);
}
private static final String lowerCamelCase(final String s)
{
final char first = s.charAt(0);
if(Character.isLowerCase(first))
return s;
else
return Character.toLowerCase(first) + s.substring(1);
}
private static final String getShortName(final Class aClass)
{
final String name = aClass.getName();
final int pos = name.lastIndexOf('.');
return name.substring(pos+1);
}
private void writeThrowsClause(final Collection exceptions)
throws IOException
{
if(!exceptions.isEmpty())
{
o.write("\t\t\tthrows");
boolean first = true;
for(final Iterator i = exceptions.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
o.write(',');
o.write(lineSeparator);
o.write("\t\t\t\t");
o.write(((Class)i.next()).getName());
}
o.write(lineSeparator);
}
}
private final void writeCommentHeader()
throws IOException
{
o.write("/**");
o.write(lineSeparator);
o.write(lineSeparator);
o.write("\t **");
o.write(lineSeparator);
}
private final void writeCommentFooter()
throws IOException
{
writeCommentFooter(null);
}
private final void writeCommentFooter(final String extraComment)
throws IOException
{
o.write("\t * @"+Instrumentor.GENERATED+' ');
o.write(GENERATED);
o.write(lineSeparator);
if(extraComment!=null)
{
o.write("\t * ");
o.write(extraComment);
o.write(lineSeparator);
}
o.write("\t *");
o.write(lineSeparator);
o.write(" */");
}
private static final String link(final String target)
{
return "{@link #" + target + '}';
}
private static final String link(final String target, final String name)
{
return "{@link #" + target + ' ' + name + '}';
}
private static final String format(final String pattern, final String parameter1)
{
return MessageFormat.format(pattern, new Object[]{ parameter1 });
}
private static final String format(final String pattern, final String parameter1, final String parameter2)
{
return MessageFormat.format(pattern, new Object[]{ parameter1, parameter2 });
}
private void writeInitialConstructor(final CopeType type)
throws IOException
{
if(!type.hasInitialConstructor())
return;
final List initialAttributes = type.getInitialAttributes();
final SortedSet constructorExceptions = type.getConstructorExceptions();
writeCommentHeader();
o.write("\t * ");
o.write(format(CONSTRUCTOR_INITIAL, type.getName()));
o.write(lineSeparator);
for(Iterator i = initialAttributes.iterator(); i.hasNext(); )
{
final CopeAttribute initialAttribute = (CopeAttribute)i.next();
o.write("\t * @param ");
o.write(initialAttribute.getName());
o.write(' ');
o.write(format(CONSTRUCTOR_INITIAL_PARAMETER, link(initialAttribute.getName())));
o.write(lineSeparator);
}
for(Iterator i = constructorExceptions.iterator(); i.hasNext(); )
{
final Class constructorException = (Class)i.next();
o.write("\t * @throws ");
o.write(constructorException.getName());
o.write(' ');
boolean first = true;
final StringBuffer initialAttributesBuf = new StringBuffer();
for(Iterator j = initialAttributes.iterator(); j.hasNext(); )
{
final CopeAttribute initialAttribute = (CopeAttribute)j.next();
if(!initialAttribute.getSetterExceptions().contains(constructorException))
continue;
if(first)
first = false;
else
initialAttributesBuf.append(", ");
initialAttributesBuf.append(initialAttribute.getName());
}
final String pattern;
if(MandatoryViolationException.class.equals(constructorException))
pattern = THROWS_NULL;
else if(UniqueViolationException.class.equals(constructorException))
pattern = THROWS_UNIQUE;
else if(LengthViolationException.class.equals(constructorException))
pattern = THROWS_LENGTH;
else
throw new RuntimeException(constructorException.getName());
o.write(format(pattern, initialAttributesBuf.toString()));
o.write(lineSeparator);
}
writeCommentFooter(CONSTRUCTOR_INITIAL_CUSTOMIZE);
final String modifier = Modifier.toString(type.getInitialConstructorModifier());
if(modifier.length()>0)
{
o.write(modifier);
o.write(' ');
}
o.write(type.getName());
o.write('(');
boolean first = true;
for(Iterator i = initialAttributes.iterator(); i.hasNext(); )
{
if(first)
first = false;
else
o.write(',');
final CopeAttribute initialAttribute = (CopeAttribute)i.next();
o.write(lineSeparator);
o.write("\t\t\t\tfinal ");
o.write(initialAttribute.getBoxedType());
o.write(' ');
o.write(initialAttribute.getName());
}
o.write(')');
o.write(lineSeparator);
writeThrowsClause(constructorExceptions);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\tthis(new "+AttributeValue.class.getName()+"[]{");
o.write(lineSeparator);
for(Iterator i = initialAttributes.iterator(); i.hasNext(); )
{
final CopeAttribute initialAttribute = (CopeAttribute)i.next();
o.write("\t\t\tnew "+AttributeValue.class.getName()+"(");
o.write(type.getName());
o.write('.');
o.write(initialAttribute.getName());
o.write(',');
writeAttribute(initialAttribute);
o.write("),");
o.write(lineSeparator);
}
o.write("\t\t});");
o.write(lineSeparator);
for(Iterator i = type.getConstructorExceptions().iterator(); i.hasNext(); )
{
final Class exception = (Class)i.next();
o.write("\t\tthrowInitial");
o.write(getShortName(exception));
o.write("();");
o.write(lineSeparator);
}
o.write("\t}");
}
private void writeGenericConstructor(final CopeType type)
throws IOException
{
final Option option = type.genericConstructorOption;
if(!option.exists)
return;
writeCommentHeader();
o.write("\t * ");
o.write(format(CONSTRUCTOR_GENERIC, type.getName()));
o.write(lineSeparator);
o.write("\t * ");
o.write(format(CONSTRUCTOR_GENERIC_CALLED, "{@link " + Type.class.getName() + "#newItem Type.newItem}"));
o.write(lineSeparator);
writeCommentFooter(CONSTRUCTOR_GENERIC_CUSTOMIZE);
o.write( Modifier.toString( option.getModifier(type.isAbstract() ? Modifier.PROTECTED : Modifier.PRIVATE) ) );
o.write(' ');
o.write(type.getName());
o.write("(final "+AttributeValue.class.getName()+"[] initialAttributes)");
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\tsuper(initialAttributes);");
o.write(lineSeparator);
o.write("\t}");
}
private void writeReactivationConstructor(final CopeType type)
throws IOException
{
writeCommentHeader();
o.write("\t * ");
o.write(CONSTRUCTOR_REACTIVATION);
o.write(lineSeparator);
o.write("\t * @see Item#Item("
+ ReactivationConstructorDummy.class.getName() + ",int)");
o.write(lineSeparator);
writeCommentFooter();
o.write( type.isAbstract() ? "protected " : "private " );
o.write(type.getName());
o.write("("+ReactivationConstructorDummy.class.getName()+" d,final int pk)");
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\tsuper(d,pk);");
o.write(lineSeparator);
o.write("\t}");
}
private void writeAccessMethods(final CopeAttribute attribute)
throws IOException
{
final String type = attribute.getBoxedType();
// getter
if(attribute.getterOption.exists)
{
writeCommentHeader();
o.write("\t * ");
o.write(format(GETTER, link(attribute.getName())));
o.write(lineSeparator);
writeStreamWarning(type);
writeCommentFooter(GETTER_CUSTOMIZE);
attribute.writeGeneratedGetterModifier(o);
o.write(type);
if(attribute.hasIsGetter())
o.write(" is");
else
o.write(" get");
o.write(toCamelCase(attribute.getName()));
o.write(attribute.getterOption.suffix);
o.write("()");
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
writeGetterBody(attribute);
o.write("\t}");
}
// setter
if(attribute.hasGeneratedSetter())
{
writeCommentHeader();
o.write("\t * ");
o.write(format(SETTER, link(attribute.getName())));
o.write(lineSeparator);
writeCommentFooter(SETTER_CUSTOMIZE);
attribute.writeGeneratedSetterModifier(o);
o.write("void set");
o.write(toCamelCase(attribute.getName()));
o.write(attribute.setterOption.suffix);
o.write("(final ");
o.write(type);
o.write(' ');
o.write(attribute.getName());
o.write(')');
o.write(lineSeparator);
writeThrowsClause(attribute.getSetterExceptions());
o.write("\t{");
o.write(lineSeparator);
writeSetterBody(attribute);
o.write("\t}");
// touch for date attributes
if(attribute.isTouchable())
{
writeCommentHeader();
o.write("\t * ");
o.write(format(TOUCHER, link(attribute.getName())));
o.write(lineSeparator);
writeCommentFooter();
attribute.writeGeneratedSetterModifier(o);
o.write("void touch");
o.write(toCamelCase(attribute.getName()));
o.write("()");
o.write(lineSeparator);
writeThrowsClause(attribute.getToucherExceptions());
o.write("\t{");
o.write(lineSeparator);
writeToucherBody(attribute);
o.write("\t}");
}
}
}
private void writeHash(final CopeHash hash)
throws IOException, InjectorParseException
{
// checker
writeCommentHeader();
o.write("\t * ");
o.write(format(CHECKER, link(hash.name)));
o.write(lineSeparator);
writeCommentFooter();
o.write(Modifier.toString(hash.getGeneratedCheckerModifier()));
o.write(" boolean check");
o.write(toCamelCase(hash.name));
o.write("(final ");
o.write(String.class.getName());
o.write(' ');
o.write(hash.name);
o.write(')');
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
writeCheckerBody(hash);
o.write("\t}");
// setter
writeCommentHeader();
o.write("\t * ");
o.write(format(SETTER, link(hash.name)));
o.write(lineSeparator);
writeCommentFooter();
o.write(Modifier.toString(hash.getGeneratedSetterModifier()));
o.write(" void set");
o.write(toCamelCase(hash.name));
o.write("(final ");
o.write(String.class.getName());
o.write(' ');
o.write(hash.name);
o.write(')');
o.write(lineSeparator);
writeThrowsClause(hash.getStorageAttribute().getSetterExceptions());
o.write("\t{");
o.write(lineSeparator);
writeSetterBody(hash);
o.write("\t}");
}
private void writeDataGetterMethod(final CopeMedia media,
final Class returnType,
final String part,
final String commentPattern,
final int getterModifier)
throws IOException
{
final String prefix = (boolean.class==returnType) ? "is" : "get";
writeCommentHeader();
o.write("\t * ");
o.write(format(commentPattern, link(media.getName())));
o.write(lineSeparator);
writeStreamWarning(returnType.getName());
writeCommentFooter();
o.write(Modifier.toString(getterModifier|Modifier.FINAL));
o.write(' ');
o.write(returnType.getName());
o.write(' ');
o.write(prefix);
o.write(toCamelCase(media.getName()));
o.write(part);
o.write("()");
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\treturn ");
o.write(media.type.getName());
o.write('.');
o.write(media.getName());
o.write('.');
o.write(prefix);
o.write(part);
o.write("(this);");
o.write(lineSeparator);
o.write("\t}");
}
private void writeDataSetterMethod(final CopeMedia media, final Class dataType)
throws IOException
{
final String mimeMajor = media.mimeMajor;
final String mimeMinor = media.mimeMinor;
writeCommentHeader();
o.write("\t * ");
o.write(format(SETTER_MEDIA, link(media.getName())));
o.write(lineSeparator);
o.write("\t * @throws ");
o.write(IOException.class.getName());
o.write(' ');
o.write(format(SETTER_MEDIA_IOEXCEPTION, "<code>data</code>"));
o.write(lineSeparator);
writeCommentFooter();
o.write(Modifier.toString(media.getGeneratedSetterModifier()));
o.write(" void set");
o.write(toCamelCase(media.getName()));
o.write("(final " + dataType.getName() + " data");
if(mimeMajor==null)
o.write(",final "+String.class.getName()+" mimeMajor");
if(mimeMinor==null)
o.write(",final "+String.class.getName()+" mimeMinor");
o.write(')');
final SortedSet setterExceptions = new TreeSet();
setterExceptions.addAll(Arrays.asList(new Class[]{IOException.class})); // TODO
o.write(lineSeparator);
writeThrowsClause(setterExceptions);
o.write("\t{");
o.write(lineSeparator);
final SortedSet exceptionsToCatch = new TreeSet(ClassComparator.getInstance());
exceptionsToCatch.addAll(setterExceptions); // TODO
exceptionsToCatch.remove(IOException.class);
writeTryCatchClausePrefix(exceptionsToCatch);
o.write("\t\t");
o.write(media.type.getName());
o.write('.');
o.write(media.getName());
o.write(".set(this,data");
o.write(mimeMajor==null ? ",mimeMajor" : ",null");
o.write(mimeMinor==null ? ",mimeMinor" : ",null");
o.write(");");
o.write(lineSeparator);
writeTryCatchClausePostfix(exceptionsToCatch);
o.write("\t}");
}
private void writeDataAccessMethods(final CopeMedia media)
throws IOException
{
// getters
final int getterModifier = media.getGeneratedGetterModifier();
writeDataGetterMethod(media, boolean.class, "Null", GETTER_MEDIA_IS_NULL, getterModifier);
writeDataGetterMethod(media, String.class, "URL", GETTER_MEDIA_URL, getterModifier);
writeDataGetterMethod(media, String.class, "MimeMajor", GETTER_MEDIA_MAJOR, getterModifier);
writeDataGetterMethod(media, String.class, "MimeMinor", GETTER_MEDIA_MINOR, getterModifier);
writeDataGetterMethod(media, String.class, "ContentType", GETTER_MEDIA_CONTENT_TYPE, getterModifier);
writeDataGetterMethod(media, long.class, "Length", GETTER_MEDIA_LENGTH_TYPE, getterModifier);
writeDataGetterMethod(media, long.class, "LastModified",GETTER_MEDIA_LASTMODIFIED_TYPE, getterModifier);
writeDataGetterMethod(media, InputStream.class, "Data", GETTER_MEDIA_DATA, getterModifier);
// file getter
{
writeCommentHeader();
o.write("\t * ");
o.write(format(GETTER_MEDIA_DATA_FILE, link(media.getName())));
o.write(lineSeparator);
o.write("\t * ");
o.write(GETTER_MEDIA_DATA_FILE2);
o.write(lineSeparator);
o.write("\t * @throws ");
o.write(IOException.class.getName());
o.write(' ');
o.write(format(SETTER_MEDIA_IOEXCEPTION, "<code>data</code>"));
o.write(lineSeparator);
writeCommentFooter();
o.write(Modifier.toString(media.getGeneratedGetterModifier()|Modifier.FINAL));
o.write(" void get");
o.write(toCamelCase(media.getName()));
o.write("Data(final " + File.class.getName() + " data)");
o.write(lineSeparator);
final SortedSet setterExceptions = new TreeSet();
setterExceptions.addAll(Arrays.asList(new Class[]{IOException.class})); // TODO
writeThrowsClause(setterExceptions);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\t");
o.write(media.type.getName());
o.write('.');
o.write(media.getName());
o.write(".getData(this,data);");
o.write(lineSeparator);
o.write("\t}");
}
// setters
if(media.setterOption.exists)
{
writeDataSetterMethod(media, InputStream.class);
writeDataSetterMethod(media, File.class);
}
}
private void writeUniqueFinder(final CopeUniqueConstraint constraint)
throws IOException, InjectorParseException
{
final CopeAttribute[] attributes = constraint.getAttributes();
final String className = attributes[0].getParent().name;
writeCommentHeader();
o.write("\t * ");
o.write(format(FINDER_UNIQUE, lowerCamelCase(className)));
o.write(lineSeparator);
for(int i=0; i<attributes.length; i++)
{
o.write("\t * @param ");
o.write(attributes[i].getName());
o.write(' ');
o.write(format(FINDER_UNIQUE_PARAMETER, link(attributes[i].getName())));
o.write(lineSeparator);
}
o.write("\t * @return ");
o.write(FINDER_UNIQUE_RETURN);
o.write(lineSeparator);
writeCommentFooter();
o.write(Modifier.toString((constraint.modifier & (Modifier.PRIVATE|Modifier.PROTECTED|Modifier.PUBLIC)) | (Modifier.STATIC|Modifier.FINAL) ));
o.write(' ');
o.write(className);
o.write(" findBy");
o.write(toCamelCase(constraint.nameForOutput));
o.write('(');
for(int i=0; i<attributes.length; i++)
{
if(i>0)
o.write(',');
final CopeAttribute attribute = attributes[i];
o.write("final ");
o.write(attribute.getBoxedType());
o.write(' ');
o.write(attribute.getName());
}
o.write(')');
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\treturn (");
o.write(className);
o.write(')');
if(attributes.length==1)
{
o.write(attributes[0].type.getName());
o.write('.');
o.write(attributes[0].getName());
o.write(".searchUnique(");
writeAttribute(attributes[0]);
}
else
{
o.write(attributes[0].type.getName());
o.write('.');
o.write(constraint.name);
o.write(".searchUnique(new Object[]{");
writeAttribute(attributes[0]);
for(int i = 1; i<attributes.length; i++)
{
o.write(',');
writeAttribute(attributes[i]);
}
o.write('}');
}
o.write(");");
o.write(lineSeparator);
o.write("\t}");
}
private void writeAttribute(final CopeAttribute attribute)
throws IOException
{
if(attribute.isBoxed())
o.write(attribute.getBoxingPrefix());
o.write(attribute.getName());
if(attribute.isBoxed())
o.write(attribute.getBoxingPostfix());
}
private void writeQualifierParameters(final CopeQualifier qualifier)
throws IOException, InjectorParseException
{
final CopeAttribute[] keys = qualifier.getKeyAttributes();
for(int i = 0; i<keys.length; i++)
{
if(i>0)
o.write(',');
o.write("final ");
o.write(keys[i].persistentType);
o.write(' ');
o.write(keys[i].name);
}
}
private void writeQualifierCall(final CopeQualifier qualifier)
throws IOException, InjectorParseException
{
final CopeAttribute[] keys = qualifier.getKeyAttributes();
for(int i = 0; i<keys.length; i++)
{
o.write(',');
o.write(keys[i].name);
}
}
private void writeQualifier(final CopeQualifier qualifier)
throws IOException, InjectorParseException
{
writeCommentHeader();
o.write("\t * ");
o.write(QUALIFIER);
o.write(lineSeparator);
writeCommentFooter();
o.write("public final "); // TODO: obey attribute visibility
o.write(qualifier.qualifierClassString);
o.write(" get");
o.write(toCamelCase(qualifier.name));
o.write('(');
writeQualifierParameters(qualifier);
o.write(')');
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\treturn (");
o.write(qualifier.qualifierClassString);
o.write(")");
o.write(qualifier.name);
o.write(".getQualifier(new Object[]{this");
writeQualifierCall(qualifier);
o.write("});");
o.write(lineSeparator);
o.write("\t}");
final List qualifierAttributes = Arrays.asList(qualifier.getUniqueConstraint().getAttributes());
for(Iterator i = qualifier.getQualifierClass().getFeatures().iterator(); i.hasNext(); )
{
final CopeFeature feature = (CopeFeature)i.next();
if(feature instanceof CopeAttribute)
{
final CopeAttribute attribute = (CopeAttribute)feature;
if(qualifierAttributes.contains(attribute))
continue;
writeQualifierGetter(qualifier, attribute);
writeQualifierSetter(qualifier, attribute);
}
}
}
private void writeQualifierGetter(final CopeQualifier qualifier, final CopeAttribute attribute)
throws IOException, InjectorParseException
{
if(attribute.getterOption.exists)
{
writeCommentHeader();
o.write("\t * ");
o.write(QUALIFIER_GETTER);
o.write(lineSeparator);
writeCommentFooter();
final String resultType = attribute.persistentType;
attribute.writeGeneratedGetterModifier(o);
o.write(resultType);
o.write(" get");
o.write(toCamelCase(attribute.getName()));
o.write(attribute.getterOption.suffix);
o.write('(');
writeQualifierParameters(qualifier);
o.write(')');
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\treturn (");
o.write(resultType);
o.write(')');
o.write(qualifier.name);
o.write(".get(new Object[]{this");
writeQualifierCall(qualifier);
o.write("},");
o.write(qualifier.qualifierClassString);
o.write('.');
o.write(attribute.getName());
o.write(");");
o.write(lineSeparator);
o.write("\t}");
}
}
private void writeQualifierSetter(final CopeQualifier qualifier, final CopeAttribute attribute)
throws IOException, InjectorParseException
{
if(attribute.setterOption.exists)
{
writeCommentHeader();
o.write("\t * ");
o.write(QUALIFIER_SETTER);
o.write(lineSeparator);
writeCommentFooter();
attribute.writeGeneratedSetterModifier(o);
o.write("void set");
o.write(toCamelCase(attribute.getName()));
o.write(attribute.setterOption.suffix);
o.write('(');
writeQualifierParameters(qualifier);
o.write(",final ");
o.write(attribute.getBoxedType());
o.write(' ');
o.write(attribute.getName());
o.write(')');
o.write(lineSeparator);
writeThrowsClause(attribute.getSetterExceptions());
o.write("\t{");
o.write(lineSeparator);
final SortedSet exceptionsToCatch = attribute.getExceptionsToCatchInSetter();
writeTryCatchClausePrefix(exceptionsToCatch);
o.write("\t\t");
o.write(qualifier.qualifierClassString);
o.write('.');
o.write(attribute.getName());
o.write(".set(");
o.write(qualifier.name);
o.write(".getForSet(new Object[]{this");
writeQualifierCall(qualifier);
o.write("}),");
o.write(attribute.getName());
o.write(");");
o.write(lineSeparator);
writeTryCatchClausePostfix(exceptionsToCatch);
o.write("\t}");
}
}
private void writeVector(final CopeVector vector)
throws IOException
{
writeCommentHeader();
o.write("\t * ");
o.write(VECTOR_GETTER);
o.write(lineSeparator);
writeCommentFooter();
o.write("public final "); // TODO: obey attribute visibility
o.write(List.class.getName());
o.write(" get");
o.write(toCamelCase(vector.name));
o.write("()");
o.write(lineSeparator);
o.write("\t{");
o.write(lineSeparator);
o.write("\t\treturn ");
o.write(vector.type.getName());
o.write('.');
o.write(vector.name);
o.write(".get(this);");
o.write(lineSeparator);
o.write("\t}");
writeCommentHeader();
o.write("\t * ");
o.write(VECTOR_SETTER);
o.write(lineSeparator);
writeCommentFooter();
o.write("public final void set"); // TODO: obey attribute visibility
o.write(toCamelCase(vector.name));
o.write("(final ");
o.write(Collection.class.getName());
o.write(' ');
o.write(vector.name);
o.write(')');
o.write(lineSeparator);
writeThrowsClause(Arrays.asList(new Class[]{
UniqueViolationException.class,
MandatoryViolationException.class,
LengthViolationException.class,
ReadOnlyViolationException.class,
ClassCastException.class}));
o.write("\t{");
o.write(lineSeparator);
o.write("\t\t");
o.write(vector.type.getName());
o.write('.');
o.write(vector.name);
o.write(".set(this,");
o.write(vector.name);
o.write(");");
o.write(lineSeparator);
o.write("\t}");
}
private final void writeType(final CopeType type)
throws IOException
{
final Option option = type.typeOption;
if(option.exists)
{
writeCommentHeader();
o.write("\t * ");
o.write(format(TYPE, lowerCamelCase(type.getName())));
o.write(lineSeparator);
writeCommentFooter(TYPE_CUSTOMIZE);
o.write(Modifier.toString(option.getModifier(Modifier.PUBLIC) | Modifier.STATIC | Modifier.FINAL)); // TODO obey class visibility
o.write(" "+Type.class.getName()+" TYPE =");
o.write(lineSeparator);
o.write("\t\tnew "+Type.class.getName()+"(");
o.write(type.getName());
o.write(".class)");
o.write(lineSeparator);
o.write(";");
}
}
void write() throws IOException, InjectorParseException
{
final String buffer = javaFile.buffer.getBuffer().toString();
int previousClassEndPosition = 0;
for(Iterator i = javaFile.getClasses().iterator(); i.hasNext(); )
{
final JavaClass javaClass = (JavaClass)i.next();
final CopeType type = CopeType.getCopeType(javaClass);
final int classEndPosition = javaClass.getClassEndPosition();
if(type!=null)
{
assert previousClassEndPosition<=classEndPosition;
if(previousClassEndPosition<classEndPosition)
o.write(buffer, previousClassEndPosition, classEndPosition-previousClassEndPosition);
writeClassFeatures(type);
previousClassEndPosition = classEndPosition;
}
}
o.write(buffer, previousClassEndPosition, buffer.length()-previousClassEndPosition);
}
private void writeClassFeatures(final CopeType type)
throws IOException, InjectorParseException
{
if(!type.isInterface())
{
writeInitialConstructor(type);
writeGenericConstructor(type);
writeReactivationConstructor(type);
for(final Iterator i = type.getFeatures().iterator(); i.hasNext(); )
{
final CopeFeature feature = (CopeFeature)i.next();
if(feature instanceof CopeAttribute)
writeAccessMethods((CopeAttribute)feature);
else if(feature instanceof CopeUniqueConstraint)
writeUniqueFinder((CopeUniqueConstraint)feature);
else if(feature instanceof CopeQualifier)
writeQualifier((CopeQualifier)feature);
else if(feature instanceof CopeVector)
writeVector((CopeVector)feature);
else if(feature instanceof CopeMedia)
writeDataAccessMethods((CopeMedia)feature);
else if(feature instanceof CopeHash)
writeHash((CopeHash)feature);
else
throw new RuntimeException(feature.getClass().getName());
}
writeType(type);
}
}
/**
* Identation contract:
* This methods is called, when o stream is immediately after a line break,
* and it should return the o stream after immediately after a line break.
* This means, doing nothing fullfils the contract.
*/
private void writeGetterBody(final CopeAttribute attribute)
throws IOException
{
o.write("\t\treturn ");
if(attribute instanceof CopeObjectAttribute)
{
o.write('(');
o.write(attribute.persistentType);
o.write(')');
}
o.write(attribute.type.getName());
o.write('.');
o.write(attribute.getName());
o.write(".get");
if(attribute.isBoxed())
o.write("Mandatory");
o.write("(this)");
o.write(';');
o.write(lineSeparator);
}
/**
* Identation contract:
* This methods is called, when o stream is immediately after a line break,
* and it should return the o stream after immediately after a line break.
* This means, doing nothing fullfils the contract.
*/
private void writeSetterBody(final CopeAttribute attribute)
throws IOException
{
final SortedSet exceptionsToCatch = attribute.getExceptionsToCatchInSetter();
writeTryCatchClausePrefix(exceptionsToCatch);
o.write("\t\t");
o.write(attribute.type.getName());
o.write('.');
o.write(attribute.getName());
o.write(".set(this,");
o.write(attribute.getName());
o.write(");");
o.write(lineSeparator);
writeTryCatchClausePostfix(exceptionsToCatch);
}
/**
* Identation contract:
* This methods is called, when o stream is immediately after a line break,
* and it should return the o stream after immediately after a line break.
* This means, doing nothing fullfils the contract.
*/
private void writeToucherBody(final CopeAttribute attribute)
throws IOException
{
final SortedSet exceptionsToCatch = attribute.getExceptionsToCatchInToucher();
writeTryCatchClausePrefix(exceptionsToCatch);
o.write("\t\t");
o.write(attribute.type.getName());
o.write('.');
o.write(attribute.getName());
o.write(".touch(this);");
o.write(lineSeparator);
writeTryCatchClausePostfix(exceptionsToCatch);
}
/**
* Identation contract:
* This methods is called, when o stream is immediately after a line break,
* and it should return the o stream after immediately after a line break.
* This means, doing nothing fullfils the contract.
*/
private void writeCheckerBody(final CopeHash hash)
throws IOException
{
o.write("\t\treturn ");
o.write(hash.type.getName());
o.write('.');
o.write(hash.name);
o.write(".check(this,");
o.write(hash.name);
o.write(");");
o.write(lineSeparator);
}
/**
* Identation contract:
* This methods is called, when o stream is immediately after a line break,
* and it should return the o stream after immediately after a line break.
* This means, doing nothing fullfils the contract.
*/
private void writeSetterBody(final CopeHash hash)
throws IOException, InjectorParseException
{
final CopeAttribute storage = hash.getStorageAttribute();
final SortedSet exceptionsToCatch = storage.getExceptionsToCatchInSetter();
writeTryCatchClausePrefix(exceptionsToCatch);
o.write("\t\t");
o.write(hash.type.getName());
o.write('.');
o.write(hash.name);
o.write(".set(this,");
o.write(hash.name);
o.write(");");
o.write(lineSeparator);
writeTryCatchClausePostfix(exceptionsToCatch);
}
private void writeTryCatchClausePrefix(final SortedSet exceptionsToCatch)
throws IOException
{
if(!exceptionsToCatch.isEmpty())
{
o.write("\t\ttry");
o.write(lineSeparator);
o.write("\t\t{");
o.write(lineSeparator);
o.write('\t');
}
}
private void writeTryCatchClausePostfix(final SortedSet exceptionsToCatch)
throws IOException
{
if(!exceptionsToCatch.isEmpty())
{
o.write("\t\t}");
o.write(lineSeparator);
for(Iterator i = exceptionsToCatch.iterator(); i.hasNext(); )
{
final Class exceptionClass = (Class)i.next();
o.write("\t\tcatch("+exceptionClass.getName()+" e)");
o.write(lineSeparator);
o.write("\t\t{");
o.write(lineSeparator);
o.write("\t\t\tthrow new "+RuntimeException.class.getName()+"(e);");
o.write(lineSeparator);
o.write("\t\t}");
o.write(lineSeparator);
}
}
}
private void writeStreamWarning(final String type) throws IOException
{
if(InputStream.class.getName().equals(type))
{
o.write("\t * ");
o.write(GETTER_STREAM_WARNING);
o.write(lineSeparator);
}
}
}
|
package de.lmu.ifi.dbs.elki.database;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import de.lmu.ifi.dbs.elki.data.FeatureVector;
import de.lmu.ifi.dbs.elki.distance.Distance;
import de.lmu.ifi.dbs.elki.distance.distancefunction.DistanceFunction;
import de.lmu.ifi.dbs.elki.distance.distancefunction.subspace.DimensionSelectingDistanceFunction;
import de.lmu.ifi.dbs.elki.utilities.UnableToComplyException;
import de.lmu.ifi.dbs.elki.utilities.pairs.Pair;
/**
* Database implemented by inverted lists that supports range queries on a specific dimension.
*
* @author Elke Achtert
* @param <O> the type of FeatureVector as element of the database
* @param <N> the type of the real vector space of the FeatureVector
*/
public class InvertedListDatabase<N extends Number, O extends FeatureVector<O, N>> extends SequentialDatabase<O> {
/**
* Map to hold the inverted lists for each dimension.
*/
private Map<Integer, SortedMap<Double, List<Integer>>> invertedLists = new HashMap<Integer, SortedMap<Double, List<Integer>>>();
/**
* @throws de.lmu.ifi.dbs.elki.utilities.UnableToComplyException
* if database reached limit of storage capacity
*/
@Override
public Integer insert(Pair<O, Associations> objectAndAssociations) throws UnableToComplyException {
Integer id = super.insert(objectAndAssociations);
O object = objectAndAssociations.getFirst();
for (int d = 1; d <= object.getDimensionality(); d++) {
SortedMap<Double, List<Integer>> invertedList = invertedLists.get(d);
if (invertedList == null) {
invertedList = new TreeMap<Double, List<Integer>>();
invertedLists.put(d, invertedList);
}
double value = object.getValue(d).doubleValue();
List<Integer> idList = invertedList.get(value);
if (idList == null) {
idList = new ArrayList<Integer>();
invertedList.put(value, idList);
}
idList.add(id);
}
return id;
}
@Override
public O delete(Integer id) {
O object = get(id);
for (int d = 1; d <= object.getDimensionality(); d++) {
SortedMap<Double, List<Integer>> invertedList = invertedLists.get(d);
if (invertedList == null) break;
double value = object.getValue(d).doubleValue();
List<Integer> idList = invertedList.get(value);
if (idList == null) break;
idList.remove(object.getID());
}
return super.delete(id);
}
/**
* Performs a range query for the given object ID with the given epsilon
* range and the according distance function. The query result is in
* ascending order to the distance to the query object.
*
* @param id the ID of the query object
* @param epsilon the string representation of the query range
* @param distanceFunction the distance function that computes the distances between the
* objects
* @return a List of the query results
*/
@SuppressWarnings("unchecked")
@Override
public <D extends Distance<D>> List<DistanceResultPair<D>> rangeQuery(Integer id, String epsilon, DistanceFunction<O, D> distanceFunction) {
List<DistanceResultPair<D>> result = new ArrayList<DistanceResultPair<D>>();
if (distanceFunction instanceof DimensionSelectingDistanceFunction) {
DimensionSelectingDistanceFunction<N,O> df = (DimensionSelectingDistanceFunction<N,O>) distanceFunction;
double eps = df.valueOf(epsilon).getValue();
int dim = df.getSelectedDimension();
SortedMap<Double, List<Integer>> invertedList = invertedLists.get(dim);
O object = get(id);
double value = object.getValue(dim).doubleValue();
double from = value - eps;
double to = value + eps + Double.MIN_VALUE;
SortedMap<Double, List<Integer>> epsMap = invertedList.subMap(from, to);
for (Double key : epsMap.keySet()) {
List<Integer> ids = epsMap.get(key);
for (Integer currentID : ids) {
// noinspection unchecked
// todo: this casting and parameterizing of this method appears questionable (since the returned distance is a DoubleDistance)
// perhaps get rid of dimensionselectingdistancefunction and revert anything related to the projectionDatabase?
D currentDistance = (D) df.distance(currentID, id);
result.add(new DistanceResultPair<D>(currentDistance, currentID));
}
}
Collections.sort(result);
return result;
}
else {
return super.rangeQuery(id, epsilon, distanceFunction);
}
}
/**
* Performs a k-nearest neighbor query for the given object ID. The query
* result is in ascending order to the distance to the query object.
*
* @param id the ID of the query object
* @param k the number of nearest neighbors to be returned
* @param distanceFunction the distance function that computes the distances between the
* objects
* @return a List of the query results
*/
@Override
public <D extends Distance<D>> List<DistanceResultPair<D>> kNNQueryForID(Integer id, int k, DistanceFunction<O, D> distanceFunction) {
return super.kNNQueryForID(id, k, distanceFunction);
}
/**
* Performs a k-nearest neighbor query for the given object. The query
* result is in ascending order to the distance to the query object.
*
* @param queryObject the query object
* @param k the number of nearest neighbors to be returned
* @param distanceFunction the distance function that computes the distances between the
* objects
* @return a List of the query results
*/
@Override
public <D extends Distance<D>> List<DistanceResultPair<D>> kNNQueryForObject(O queryObject, int k, DistanceFunction<O, D> distanceFunction) {
return super.kNNQueryForObject(queryObject, k, distanceFunction);
}
/**
* Performs k-nearest neighbor queries for the given object IDs. The query
* result is in ascending order to the distance to the query object.
*
* @param ids the IDs of the query objects
* @param k the number of nearest neighbors to be returned
* @param distanceFunction the distance function that computes the distances between the
* objects
* @return a List of List of the query results
*/
@Override
public <D extends Distance<D>> List<List<DistanceResultPair<D>>> bulkKNNQueryForID(List<Integer> ids, int k, DistanceFunction<O, D> distanceFunction) {
return super.bulkKNNQueryForID(ids, k, distanceFunction);
}
/**
* Performs a reverse k-nearest neighbor query for the given object ID. The
* query result is in ascending order to the distance to the query object.
*
* @param id the ID of the query object
* @param k the number of nearest neighbors to be returned
* @param distanceFunction the distance function that computes the distances between the
* objects
* @return a List of the query results
*/
@Override
public <D extends Distance<D>> List<DistanceResultPair<D>> reverseKNNQuery(Integer id, int k, DistanceFunction<O, D> distanceFunction) {
return super.reverseKNNQuery(id, k, distanceFunction);
}
}
|
package kafkastore;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import weibo4j.StatusSerDer;
import weibo4j.model.Status;
/**
*
*
* @author xiafan
*
*/
public class TweetConsumer {
private static final Logger logger = Logger.getLogger(TweetConsumer.class);
KafkaConsumer<byte[], byte[]> consumer;
List<String> topics;
String group;
String servers;
public TweetConsumer() {
}
/**
* used for test
*
* @param topics
* @param group
* @param servers
* @param reset
*/
public void open(List<String> topics, String group, String servers, boolean reset) {
this.topics = topics;
this.group = group;
this.servers = servers;
Properties props = new Properties();
props.put("bootstrap.servers", servers);
props.put("group.id", group);
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "1000");
props.put("session.timeout.ms", "30000");
props.put("key.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer");
consumer = new KafkaConsumer<byte[], byte[]>(props);
if (reset) {
for (String topic : topics)
for (PartitionInfo info : consumer.partitionsFor(topic)) {
TopicPartition part = new TopicPartition(info.topic(), info.partition());
consumer.assign(Arrays.asList(part));
consumer.seekToBeginning(part);
}
} else {
consumer.subscribe(topics);
}
}
public void open(List<String> topics, String group, String servers) {
Properties props = new Properties();
props.put("bootstrap.servers", servers);
props.put("group.id", group);
props.put("enable.auto.commit", "true");
props.put("auto.commit.interval.ms", "1000");
props.put("session.timeout.ms", "30000");
props.put("key.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer");
props.put("value.deserializer", "org.apache.kafka.common.serialization.ByteArrayDeserializer");
consumer = new KafkaConsumer<byte[], byte[]>(props);
consumer.subscribe(topics);
/*
* for (String topic : topics) for (PartitionInfo info :
* consumer.partitionsFor(topic)) { TopicPartition part = new
* TopicPartition(info.topic(), info.partition());
* consumer.assign(Arrays.asList(part)); consumer.seekToBeginning(part);
* }
*/
}
public void close() {
if (consumer != null) {
consumer.close();
consumer = null;
}
}
@Override
public void finalize() {
close();
}
private static Object readObject(byte[] data) {
// ret.add(kryos.get().readObject(new Input(record.value()),
// UserCrawlState.class));
ObjectInputStream input;
try {
input = new ObjectInputStream(new ByteArrayInputStream(data));
return input.readObject();
} catch (IOException e) {
logger.error(e);
} catch (ClassNotFoundException e) {
logger.error(e);
}
return null;
}
public Map<String, List<Object>> nextStates() {
Map<String, List<Object>> ret = new HashMap<String, List<Object>>();
ConsumerRecords<byte[], byte[]> records = null;
int count = 0;
do {
try {
count++;
records = consumer.poll(1000);
if (count % 100 == 0) {
logger.info("looping " + count + " times, no results fetched!!!");
consumer.commitSync();
}
} catch (Exception ex) {
logger.error(ex.getMessage());
ex.printStackTrace();
}
} while ((records == null || records.count() == 0) && count < 100);
try {
if (count >= 100) {
consumer.close();
open(topics, group, servers, false);
count = 0;
}
} catch (Exception ex) {
ex.printStackTrace();
}
for (ConsumerRecord<byte[], byte[]> record : records) {
if (!ret.containsKey(record.topic())) {
ret.put(record.topic(), new ArrayList<Object>());
}
try {
Object data = readObject(record.value());
if (data != null)
ret.get(record.topic()).add(data);
} catch (Exception ex) {
ex.printStackTrace();
logger.error(ex.getMessage());
}
}
return ret;
}
public List<UserCrawlState> nextCrawlerStates() {
List<UserCrawlState> ret = new ArrayList<UserCrawlState>();
for (Entry<String, List<Object>> entry : nextStates().entrySet()) {
assert entry.getKey().equals(KafkaTopics.VIP_UID_TOPIC);
for (Object data : entry.getValue())
ret.add((UserCrawlState) data);
}
return ret;
}
public List<TimeSeriesUpdateState> nextTSUpdateStates() {
List<TimeSeriesUpdateState> ret = new ArrayList<TimeSeriesUpdateState>();
for (Entry<String, List<Object>> entry : nextStates().entrySet()) {
assert entry.getKey().equals(KafkaTopics.RTSERIES_STATE_TOPIC);
for (Object data : entry.getValue())
ret.add((TimeSeriesUpdateState) data);
}
return ret;
}
public List<RepostCrawlState> nextRepostStates() {
List<RepostCrawlState> ret = new ArrayList<RepostCrawlState>();
for (Entry<String, List<Object>> entry : nextStates().entrySet()) {
assert entry.getKey().equals(KafkaTopics.RTCRALW_STATE_TOPIC);
for (Object data : entry.getValue())
ret.add((RepostCrawlState) data);
}
return ret;
}
public Map<String, List<Status>> nextStatus() {
Map<String, List<Status>> ret = new HashMap<String, List<Status>>();
ConsumerRecords<byte[], byte[]> records = null;
do {
try {
records = consumer.poll(500);
} catch (Exception ex) {
ex.printStackTrace();
}
} while (records == null || records.count() == 0);
for (ConsumerRecord<byte[], byte[]> record : records) {
if (!ret.containsKey(record.topic())) {
ret.put(record.topic(), new ArrayList<Status>());
}
try {
Status cur = StatusSerDer.fromJSON(new String(record.value(), TweetKafkaProducer.ENCODING));
if (cur != null) {
ret.get(record.topic()).add(cur);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
return ret;
}
public static void main(String[] args) {
PropertyConfigurator.configure("conf/log4j.properties");
TweetConsumer consumer = new TweetConsumer();
consumer.open(Arrays.asList(KafkaTopics.VIP_UID_TOPIC, KafkaTopics.RTCRALW_STATE_TOPIC),
KafkaTopics.TWEET_STORE_GROUP, "10.11.1.212:9092", true);
for (UserCrawlState state : consumer.nextCrawlerStates()) {
System.out.println(state);
}
for (RepostCrawlState state : consumer.nextRepostStates()) {
System.out.println(state);
}
}
}
|
package de.ptb.epics.eve.editor.graphical;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.log4j.Logger;
import org.eclipse.core.filesystem.EFS;
import org.eclipse.core.filesystem.IFileStore;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.draw2d.ColorConstants;
import org.eclipse.draw2d.XYLayout;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.gef.EditDomain;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.editparts.ScalableRootEditPart;
import org.eclipse.gef.ui.parts.ScrollingGraphicalViewer;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.ide.FileStoreEditorInput;
import org.eclipse.ui.part.EditorPart;
import org.xml.sax.SAXException;
import de.ptb.epics.eve.data.SaveAxisPositionsTypes;
import de.ptb.epics.eve.data.measuringstation.filter.ExcludeFilter;
import de.ptb.epics.eve.data.scandescription.Chain;
import de.ptb.epics.eve.data.scandescription.Connector;
import de.ptb.epics.eve.data.scandescription.ScanDescription;
import de.ptb.epics.eve.data.scandescription.ScanModule;
import de.ptb.epics.eve.data.scandescription.StartEvent;
import de.ptb.epics.eve.data.scandescription.processors.ScanDescriptionLoader;
import de.ptb.epics.eve.data.scandescription.processors.ScanDescriptionSaverToXMLusingXerces;
import de.ptb.epics.eve.data.scandescription.updatenotification.IModelUpdateListener;
import de.ptb.epics.eve.data.scandescription.updatenotification.ModelUpdateEvent;
import de.ptb.epics.eve.editor.Activator;
import de.ptb.epics.eve.editor.dialogs.LostDevicesDialog;
import de.ptb.epics.eve.editor.graphical.editparts.ChainEditPart;
import de.ptb.epics.eve.editor.graphical.editparts.EventEditPart;
import de.ptb.epics.eve.editor.graphical.editparts.ScanModuleEditPart;
import de.ptb.epics.eve.editor.views.ErrorView;
import de.ptb.epics.eve.editor.views.scanmoduleview.ScanModuleView;
import de.ptb.epics.eve.editor.views.scanview.ScanView;
/**
* <code>GraphicalEditor</code> is the central element of the EveEditor Plug In.
* It allows creating and editing of scan descriptions.
*
* @author ?
* @author Marcus Michalsky
*/
public class GraphicalEditor extends EditorPart implements IModelUpdateListener {
// logging
private static Logger logger = Logger.getLogger(GraphicalEditor.class);
// a graphical view of the model (hosts the figures)
private ScrollingGraphicalViewer viewer;
/*
* the currently loaded scan description
*/
private ScanDescription scanDescription;
/*
* reminder of the currently selected scan module
* decides what is shown in the scan module view
*/
private ScanModule selectedScanModule = null;
/*
* reminder of the currently selected edit part
* if it is a scan module, it is selected (colored)
*/
private EditPart selectedEditPart;
/*
* reminder of the recently right-clicked edit part
* used by the actions of the context menu
*/
private EditPart rightClickEditPart;
private EditDomain editDomain = new EditDomain();
// the context menu of the editor (right-click)
private Menu menu;
// context menu actions to add appended/nested, delete or rename modules
private MenuItem addAppendedScanModulMenuItem;
private MenuItem addNestedScanModulMenuItem;
private MenuItem deleteScanModulMenuItem;
private MenuItem renameScanModulMenuItem;
// dirty flag indicating whether the editor has unsaved changes
private boolean dirty;
/**
* {@inheritDoc}
*/
@Override
public void createPartControl(final Composite parent) {
logger.debug("create part control");
this.viewer = new ScrollingGraphicalViewer();
this.viewer.createControl(parent);
this.editDomain.addViewer(this.viewer);
this.viewer.getControl().addMouseListener(new ViewerMouseListener());
// configure GraphicalViewer
this.viewer.getControl().setBackground(ColorConstants.listBackground);
((ScalableRootEditPart)this.viewer.getRootEditPart()).
getLayer(ScalableRootEditPart.PRIMARY_LAYER).
setLayoutManager(new XYLayout());
this.viewer.setEditPartFactory(new GraphicalEditorEditPartFactory());
this.viewer.setContents(this.scanDescription);
menu = createContextMenu();
updateViews();
}
private Menu createContextMenu()
{
menu = new Menu(this.viewer.getControl());
this.addAppendedScanModulMenuItem = new MenuItem(menu, SWT.NONE);
this.addAppendedScanModulMenuItem.setText("Add appended Scan Modul");
this.addAppendedScanModulMenuItem.addSelectionListener(
new AddAppendedScanModuleMenuItemSelectionListener());
this.addNestedScanModulMenuItem = new MenuItem(menu, SWT.NONE);
this.addNestedScanModulMenuItem.setText("Add nested Scan Modul");
this.addNestedScanModulMenuItem.addSelectionListener(
new AddNestedScanModuleMenuItemSelectionListener());
this.deleteScanModulMenuItem = new MenuItem(menu, SWT.NONE);
this.deleteScanModulMenuItem.setText("Delete");
this.deleteScanModulMenuItem.addSelectionListener(
new DeleteScanModuleMenuItemSelectionListener());
this.renameScanModulMenuItem = new MenuItem(menu, SWT.NONE);
this.renameScanModulMenuItem.setText("Rename");
this.renameScanModulMenuItem.addSelectionListener(
new RenameScanModuleMenuItemSelectionListener());
this.viewer.getControl().setMenu(menu);
return menu;
}
/*
* called by setFocus()
*/
private void updateErrorView()
{
// get all views
IViewReference[] ref = getSite().getPage().getViewReferences();
// inform the error view about the current scan description
ErrorView errorView = null;
for(int i = 0; i < ref.length; ++i) {
if(ref[i].getId().equals(ErrorView.ID)) {
errorView = (ErrorView)ref[i].getPart(false);
}
}
if(errorView != null) {
errorView.setCurrentScanDescription(this.scanDescription);
}
}
private void updateScanView()
{
// get all views
IViewReference[] ref = getSite().getPage().getViewReferences();
// try to get the scan view
ScanView scanView = null;
for(int i = 0; i < ref.length; ++i) {
if(ref[i].getId().equals(ScanView.ID)) {
scanView = (ScanView)ref[i].getPart(false);
}
}
// scan view found ?
if(scanView != null) {
// tell the view about the currently selected scan module
if(selectedScanModule != null)
{
scanView.setCurrentChain(selectedScanModule.getChain());
logger.debug("currentChain: " + selectedScanModule.getChain());
}
else {
scanView.setCurrentChain(null);
logger.debug("currentChain: " + null);
}
}
}
/*
* called by setFocus() & the mouse listener
*/
private void updateScanModuleView()
{
// get all views
IViewReference[] ref = getSite().getPage().getViewReferences();
// try to get the scan module view
ScanModuleView scanModuleView = null;
for(int i = 0; i < ref.length; ++i) {
if(ref[i].getId().equals(ScanModuleView.ID)) {
scanModuleView = (ScanModuleView)ref[i].getPart(false);
}
}
// scan module view found ?
if(scanModuleView != null) {
// tell the view about the currently selected scan module
scanModuleView.setCurrentScanModule(selectedScanModule);
}
logger.debug("selectedScanModule: " + selectedScanModule);
}
/*
* wrapper to update all views
*/
private void updateViews()
{
updateErrorView();
updateScanView();
updateScanModuleView();
}
/*
* used to select a scan module (and deselect the old one) by
* updating all necessary references
*
* @param part the corresponding edit part of the scan module that should
* be selected
*/
private void selectScanModule(ScanModuleEditPart part)
{
// if a scan module was previously selected -> deselect it
if(selectedEditPart instanceof ScanModuleEditPart) {
((ScanModuleEditPart)selectedEditPart).setFocus(false);
}
if(part != null)
{
// remember the selected scan module
selectedEditPart = part;
// update the model to the currently selected module
selectedScanModule = (ScanModule)selectedEditPart.getModel();
// set the focus (to select/color it)
((ScanModuleEditPart)selectedEditPart).setFocus(true);
} else {
// reset selection
selectedEditPart = null;
// reset model
selectedScanModule = null;
}
// tell the views about the changes
updateViews();
}
/**
* {@inheritDoc}
*/
@Override
public void updateEvent(final ModelUpdateEvent modelUpdateEvent) {
logger.debug("update event");
this.dirty = true;
this.firePropertyChange(PROP_DIRTY);
refreshAllEditParts(viewer.getRootEditPart());
}
@SuppressWarnings("unchecked")
private void refreshAllEditParts(EditPart part)
{
scanDescription.removeModelUpdateListener(this);
part.refresh();
List<EditPart> children = part.getChildren();
for (EditPart child : children) {
refreshAllEditParts(child);
}
scanDescription.addModelUpdateListener(this);
}
/**
* {@inheritDoc}
*/
@Override
public void setFocus() {
logger.debug("Focus gained");
updateViews();
}
/**
* {@inheritDoc}
*/
@Override
public void init(final IEditorSite site, final IEditorInput input)
throws PartInitException {
logger.debug("Init");
this.selectedScanModule = null;
this.setSite(site);
this.setInput(input);
this.setPartName(input.getName());
final FileStoreEditorInput fileStoreEditorInput =
(FileStoreEditorInput)input;
final File scanDescriptionFile = new File(fileStoreEditorInput.getURI());
if (scanDescriptionFile.isFile() == true) {
if (scanDescriptionFile.length() == 0) {
// file exists but is empty -> do not read
return;
}
}
else {
// file does not exist -> do not read
return;
}
final ScanDescriptionLoader scanDescriptionLoader =
new ScanDescriptionLoader(Activator.getDefault().
getMeasuringStation(),
Activator.getDefault().
getSchemaFile());
this.dirty = false;
try {
scanDescriptionLoader.load(scanDescriptionFile);
this.scanDescription = scanDescriptionLoader.getScanDescription();
if (scanDescriptionLoader.getLostDevices() != null) {
Shell shell = getSite().getShell();
LostDevicesDialog dialog =
new LostDevicesDialog(shell, scanDescriptionLoader);
dialog.open();
this.dirty = true;
}
this.scanDescription.addModelUpdateListener(this);
} catch(final ParserConfigurationException e) {
logger.error(e.getMessage(), e);
} catch(final SAXException e) {
logger.error(e.getMessage(), e);
} catch(final IOException e) {
logger.error(e.getMessage(), e);
}
this.firePropertyChange(PROP_DIRTY);
}
/**
* {@inheritDoc}
*/
@Override
public void doSave(final IProgressMonitor monitor) {
// check for errors in the model
// if present -> inform the user and cancel save
if(scanDescription.getModelErrors().size() > 0)
{
MessageDialog.openError(
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
"Save Error",
"Scandescription could not be saved! " +
"Consult the Errors View for more Information.");
return;
}
// no errors present -> save
// tell the progress monitor the name of the task and the number of
// subtasks it depends on
monitor.beginTask("save scandescription", 4);
// 1: create files
// 2: save whole file
// 3: save filtered file
// 4: calculate and log difference
final FileStoreEditorInput fileStoreEditorInput =
(FileStoreEditorInput)this.getEditorInput();
final File scanDescriptionFile = new File(fileStoreEditorInput.getURI());
File tempFile = null;
try {
tempFile = new File(new URL(fileStoreEditorInput.getURI().
toString() + ".temp").toURI());
} catch (MalformedURLException e1) {
logger.error(e1.getMessage(), e1);
} catch (URISyntaxException e1) {
logger.error(e1.getMessage(), e1);
}
monitor.worked(1);
try {
final FileOutputStream os = new FileOutputStream(scanDescriptionFile);
final FileOutputStream os_temp = new FileOutputStream(tempFile);
// save the whole file without filtering first
final ScanDescriptionSaverToXMLusingXerces scanDescriptionSaverFull =
new ScanDescriptionSaverToXMLusingXerces(os_temp,
scanDescription.getMeasuringStation(), this.scanDescription);
scanDescriptionSaverFull.save();
// get the size of the unfiltered file
long full = tempFile.length();
monitor.worked(1);
// do the filtering
ExcludeFilter measuringStation = new ExcludeFilter();
measuringStation.setSource(scanDescription.getMeasuringStation());
// comment out following line to deactivate filtering
measuringStation.excludeUnusedDevices(scanDescription);
// now save the "real" / filtered file
final ScanDescriptionSaverToXMLusingXerces scanDescriptionSaver =
new ScanDescriptionSaverToXMLusingXerces(
os, measuringStation, this.scanDescription);
scanDescriptionSaver.save();
// determine filtered file size
long filtered = scanDescriptionFile.length();
monitor.worked(1);
// format to percent
NumberFormat form =
NumberFormat.getPercentInstance(new Locale("de-DE"));
// log the result
logger.info("File size reduced due to filtering: " +
(form.format(new Double(((double)(full - filtered))/full))) +
" (" + new DecimalFormat("#.##").format((float)filtered/1024) +
"kB of " + new DecimalFormat("#.##").format((float)full/1024) +
"kB remain)");
// delete the temp file
tempFile.delete();
monitor.worked(1);
this.dirty = false;
this.firePropertyChange(PROP_DIRTY);
} catch(final FileNotFoundException e) {
logger.error(e.getMessage(), e);
}
// tell the progress monitor that the task is finished
monitor.done();
}
/**
* {@inheritDoc}
*/
@Override
public void doSaveAs() {
// als filePath wird das Verzeichnis des aktuellen Scans gesetzt
final FileStoreEditorInput fileStoreEditorInput2 =
(FileStoreEditorInput)this.getEditorInput();
int lastSeperatorIndex =
fileStoreEditorInput2.getURI().getRawPath().lastIndexOf("/");
final String filePath = fileStoreEditorInput2.getURI().getRawPath().
substring(0, lastSeperatorIndex + 1);
final FileDialog dialog =
new FileDialog(this.getEditorSite().getShell(), SWT.SAVE);
dialog.setFilterPath(filePath);
final String fileName = dialog.open();
String fileNameLang = fileName;
if(fileName != null) {
// eventuel vorhandener Datentyp wird weggenommen
final int lastPoint = fileName.lastIndexOf(".");
final int lastSep = fileName.lastIndexOf("/");
if ((lastPoint > 0) && (lastPoint > lastSep))
fileNameLang = fileName.substring(0, lastPoint) + ".scml";
else
fileNameLang = fileName + ".scml";
}
final File scanDescriptionFile = new File(fileNameLang);
try {
final FileOutputStream os =
new FileOutputStream(scanDescriptionFile);
ExcludeFilter measuringStation = new ExcludeFilter();
measuringStation.setSource(scanDescription.getMeasuringStation());
// comment out following line to deactivate filtering
measuringStation.excludeUnusedDevices(scanDescription);
final ScanDescriptionSaverToXMLusingXerces scanDescriptionSaver =
new ScanDescriptionSaverToXMLusingXerces(os,
measuringStation,
this.scanDescription);
scanDescriptionSaver.save();
final IFileStore fileStore =
EFS.getLocalFileSystem().getStore(new Path(fileNameLang));
final FileStoreEditorInput fileStoreEditorInput =
new FileStoreEditorInput(fileStore);
this.setInput(fileStoreEditorInput);
this.dirty = false;
this.firePropertyChange(PROP_DIRTY);
this.setPartName(fileStoreEditorInput.getName());
} catch(final FileNotFoundException e) {
logger.error(e.getMessage(), e);
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean isDirty() {
return this.dirty;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isSaveAsAllowed() {
return true;
}
/**
* <code>MouseListener</code> of viewer.
*/
class ViewerMouseListener implements MouseListener {
/**
* {@inheritDoc}
*/
@Override
public void mouseDoubleClick(MouseEvent e) {
}
/**
* {@inheritDoc}<br><br>
* Updates available context menu entries depending on where the user
* (right-)clicked.
*/
@Override
public void mouseDown(MouseEvent e) {
if(e.button == 1) return;
// get the object (part) the user clicked on
EditPart part = viewer.findObjectAt(new Point(e.x, e.y));
//part.refresh();
// check on what object the user clicked at
if(part instanceof ScanModuleEditPart) {
// user clicked on a scan module
final ScanModule scanModule = (ScanModule)part.getModel();
// enable/disable context menu entries depending on the
// selected scan module
if(scanModule.getAppended() == null) {
// no appended module present -> add appended allowed
addAppendedScanModulMenuItem.setEnabled(true);
} else {
// appended already present -> add appended not allowed
addAppendedScanModulMenuItem.setEnabled(false);
}
if(scanModule.getNested() == null) {
// no nested scan module present -> add nested allowed
addNestedScanModulMenuItem.setEnabled(true);
} else {
// nested already present -> add nested not allowed
addNestedScanModulMenuItem.setEnabled(false);
}
// delete and rename is always allowed
deleteScanModulMenuItem.setEnabled(true);
renameScanModulMenuItem.setEnabled(true);
} else if(part instanceof EventEditPart) {
// user clicked on an event
EventEditPart eventEditPart = (EventEditPart)part;
if(((StartEvent)eventEditPart.getModel()).getConnector() == null) {
// no appended module present -> add appended allowed
addAppendedScanModulMenuItem.setEnabled(true);
} else {
// appended already present -> add appended not allowed
addAppendedScanModulMenuItem.setEnabled(false);
}
// add nested and delete module never allowed for events
addNestedScanModulMenuItem.setEnabled(false);
deleteScanModulMenuItem.setEnabled(false);
} else {
// user clicked anywhere else -> disable all actions
addAppendedScanModulMenuItem.setEnabled(false);
addNestedScanModulMenuItem.setEnabled(false);
deleteScanModulMenuItem.setEnabled(false);
renameScanModulMenuItem.setEnabled(false);
}
// save the edit part the user recently (right-)clicked on
rightClickEditPart = part;
}
/**
* {@inheritDoc}<br><br>
* Updates the coloring depending on the selected scan module and
* tells the scan module view about it.
*/
@Override
public void mouseUp(MouseEvent e) {
logger.debug("Mouse " + e.button);
if(e.button == 2) return;
// find the object the user clicked on
EditPart part = viewer.findObjectAt(new Point(e.x, e.y));
if(part instanceof ScanModuleEditPart) {
// user clicked on a scan module
selectScanModule((ScanModuleEditPart)part);
}
else
{
// user clicked anywhere else -> deselect scan module
selectScanModule(null);
}
}
}
/**
* <code>SelectionListener</code> of
* <code>addAppendedScanModulMenuItem</code>.
*/
class AddAppendedScanModuleMenuItemSelectionListener
implements SelectionListener {
/**
* {@inheritDoc}
*/
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
/**
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
public void widgetSelected(SelectionEvent e) {
// TODO !!!!! split try catch in smaller parts ?
try {
if(rightClickEditPart instanceof ScanModuleEditPart) {
// get the edit part the user right-clicked on
// (before choosing add nested scan module)
ScanModuleEditPart scanModuleEditPart =
(ScanModuleEditPart)rightClickEditPart;
// get the model of the edit part the user clicked on
ScanModule scanModule =
(ScanModule)rightClickEditPart.getModel();
// find the next free id which can be used for the new module
// create a new array of all available chains
Chain[] chains = scanModule.getChain().getScanDescription().
getChains().toArray(new Chain[0]);
int newId = 1;
do {
boolean repeat = false;
for(int i = 0; i < chains.length; ++i) {
ScanModule[] scanModules = chains[i].getScanModuls().
toArray(new ScanModule[0]);
for(int j = 0; j < scanModules.length; ++j) {
if(scanModules[j].getId() == newId) {
newId++;
repeat = true;
}
}
}
if(!repeat)
break;
} while(true);
// end of: find new id
ScanModule newScanModule = new ScanModule(newId);
newScanModule.setName("SM " + newId + " append");
newScanModule.setX(scanModule.getX() + 130);
newScanModule.setY(scanModule.getY());
newScanModule.setTriggerdelay(0);
newScanModule.setSettletime(0);
newScanModule.setSaveAxisPositions(SaveAxisPositionsTypes.NEVER);
Connector connector = new Connector();
connector.setParentScanModul(scanModule);
connector.setChildScanModul(newScanModule);
scanModule.setAppended(connector);
newScanModule.setParent(connector);
scanModule.getChain().add(newScanModule);
scanModuleEditPart.refresh();
scanModuleEditPart.getParent().refresh();
// select the newly created module
EditPart part = viewer.findObjectAt(
new Point(newScanModule.getX()+2,
newScanModule.getY()+2));
if(part instanceof ScanModuleEditPart)
selectScanModule((ScanModuleEditPart)part);
} else if(rightClickEditPart instanceof EventEditPart) {
EventEditPart eventEditPart =
(EventEditPart)rightClickEditPart;
StartEvent startEvent =
(StartEvent)rightClickEditPart.getModel();
Chain[] chains = ((ScanDescription)eventEditPart.getParent().
getModel()).getChains().toArray(new Chain[0]);
int newId = 1;
do {
boolean repeat = false;
for(int i = 0; i < chains.length; ++i) {
ScanModule[] scanModules = chains[i].getScanModuls().
toArray(new ScanModule[0]);
for(int j = 0; j < scanModules.length; ++j) {
if(scanModules[j].getId() == newId) {
newId++;
repeat = true;
}
}
}
if(!repeat)
break;
} while(true);
ScanModule newScanModule = new ScanModule(newId);
newScanModule.setName("SM " + newId);
newScanModule.setX(100);
newScanModule.setY(20);
newScanModule.setTriggerdelay(0);
newScanModule.setSettletime(0);
newScanModule.setSaveAxisPositions(SaveAxisPositionsTypes.NEVER);
Connector connector = new Connector();
connector.setParentEvent(startEvent);
connector.setChildScanModul(newScanModule);
startEvent.setConnector(connector);
newScanModule.setParent(connector);
Iterator<Chain> it = scanDescription.getChains().iterator();
while(it.hasNext()) {
Chain currentChain = it.next();
if(currentChain.getStartEvent() == startEvent) {
currentChain.add(newScanModule);
break;
}
}
eventEditPart.refresh();
eventEditPart.getParent().refresh();
Iterator<EditPart> it2 = eventEditPart.getParent().getChildren().iterator();
while(it2.hasNext()) {
EditPart editPart = (EditPart)it2.next();
if(editPart instanceof ChainEditPart) {
ChainEditPart chainEditPart = (ChainEditPart)editPart;
final Chain chain = (Chain)editPart.getModel();
if(chain.getStartEvent() == startEvent) {
chainEditPart.refresh();
}
}
}
// select the newly created module
EditPart part = viewer.findObjectAt(
new Point(newScanModule.getX()+2,
newScanModule.getY()+2));
if(part instanceof ScanModuleEditPart)
selectScanModule((ScanModuleEditPart)part);
}
} catch(Exception ex) {
// TODO: remove and replace with smaller blocks
logger.error(ex.getMessage(), ex);
}
}
}
/**
* <code>SelectionListener</code> of <code>addNestedScanModulMenuItem</code>.
*/
class AddNestedScanModuleMenuItemSelectionListener implements SelectionListener {
/**
* {@inheritDoc}
*/
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
/**
* {@inheritDoc}
*/
@Override
public void widgetSelected(SelectionEvent e) {
ScanModuleEditPart scanModuleEditPart =
(ScanModuleEditPart)rightClickEditPart;
ScanModule scanModule = (ScanModule)rightClickEditPart.getModel();
Chain[] chains = scanModule.getChain().getScanDescription().
getChains().toArray(new Chain[0]);
// get the next available id
int newId = 1;
do {
boolean repeat = false;
for(int i = 0; i < chains.length; ++i) {
ScanModule[] scanModules =
chains[i].getScanModuls().toArray(new ScanModule[0]);
for(int j=0; j<scanModules.length; ++j) {
if(scanModules[j].getId() == newId) {
newId++;
repeat = true;
}
}
}
if(!repeat)
break;
} while(true);
// end of: get free id
ScanModule newScanModule = new ScanModule(newId);
newScanModule.setName("SM " + newId + " nested");
newScanModule.setX(scanModule.getX() + 130);
newScanModule.setY(scanModule.getY() + 100);
newScanModule.setTriggerdelay(0);
newScanModule.setSettletime(0);
newScanModule.setSaveAxisPositions(SaveAxisPositionsTypes.NEVER);
Connector connector = new Connector();
connector.setParentScanModul(scanModule);
connector.setChildScanModul(newScanModule);
scanModule.setNested(connector);
newScanModule.setParent(connector);
scanModule.getChain().add(newScanModule);
scanModuleEditPart.refresh();
scanModuleEditPart.getParent().refresh();
// select the newly created module
EditPart part = viewer.findObjectAt(
new Point(newScanModule.getX()+2, newScanModule.getY()+2));
if(part instanceof ScanModuleEditPart)
selectScanModule((ScanModuleEditPart)part);
}
}
/**
* <code>SelectionListener</code> of <code>deleteScanModulMenuItem</code>.
*/
class DeleteScanModuleMenuItemSelectionListener implements SelectionListener {
/**
* {@inheritDoc}
*/
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
/**
* {@inheritDoc}
*/
@Override
public void widgetSelected(SelectionEvent e) {
// get the scan module the user right-clicked
ScanModuleEditPart scanModuleEditPart =
(ScanModuleEditPart)rightClickEditPart;
// deselect currently selected scan module (if existing)
if(selectedEditPart instanceof ScanModuleEditPart) {
((ScanModuleEditPart)selectedEditPart).setFocus(false);
}
// try to find parent scan module
EditPart newPart = null;
ScanModule scanModule = (ScanModule)scanModuleEditPart.getModel();
ScanModule parentModule = scanModule.getParent().getParentScanModule();
if (parentModule != null) {
int x = parentModule.getX();
int y = parentModule.getY();
newPart = viewer.findObjectAt(new Point(x, y));
}
scanModuleEditPart.removeYourSelf();
if (newPart != null){ // && newPart instanceof ScanModuleEditPart) {
// parent scan module exists -> select it
selectScanModule((ScanModuleEditPart)newPart);
} else {
// no parent scan module -> select nothing
selectedEditPart = null;
selectedScanModule = null;
}
// tell the other views about the change
updateViews();
}
}
/**
* <code>SelectionListener</code> of <code>renameScanModuleMenuItem</code>.
*/
class RenameScanModuleMenuItemSelectionListener implements SelectionListener {
/**
* {@inheritDoc}
*/
@Override
public void widgetDefaultSelected(SelectionEvent e) {
}
/**
* {@inheritDoc}<br><br>
* Shows a dialog to enter a new name for the scan module.
* If OK is pressed, the name is changed.
*/
@Override
public void widgetSelected(SelectionEvent e) {
// get the scan module the user right-clicked
ScanModuleEditPart scanModuleEditPart =
(ScanModuleEditPart)rightClickEditPart;
ScanModule scanModule = (ScanModule)rightClickEditPart.getModel();
// show dialog to input new name
Shell shell = getSite().getShell();
InputDialog dialog = new InputDialog(shell,
"Renaming ScanModule:" + scanModule.getId(),
"Please enter a new name for the Scan Module:",
scanModule.getName(), null);
// if user acknowledges (OK Button) -> change name,
// do nothing if not (Cancel Button)
if(InputDialog.OK == dialog.open()) {
scanModule.setName(dialog.getValue());
scanModuleEditPart.refresh();
scanModuleEditPart.getFigure().repaint();
}
}
}
}
|
package dr.app.beauti.siteModelsPanel;
import dr.app.beauti.BeautiApp;
import dr.app.beauti.options.PartitionSubstitutionModel;
import dr.app.beauti.types.BinaryModelType;
import dr.app.beauti.types.DiscreteSubstModelType;
import dr.app.beauti.types.FrequencyPolicyType;
import dr.app.beauti.types.MicroSatModelType;
import dr.app.beauti.util.PanelUtils;
import dr.app.gui.components.WholeNumberField;
import dr.app.util.OSType;
import dr.evolution.datatype.DataType;
import dr.evolution.datatype.Microsatellite;
import dr.evomodel.substmodel.AminoAcidModelType;
import dr.evomodel.substmodel.NucModelType;
import jam.panels.OptionsPanel;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.event.*;
import java.util.EnumSet;
import java.util.logging.Logger;
/**
* @author Alexei Drummond
* @author Walter Xie
*/
public class PartitionModelPanel extends OptionsPanel {
// Components
private static final long serialVersionUID = -1645661616353099424L;
private JComboBox nucSubstCombo = new JComboBox(EnumSet.range(
NucModelType.HKY, NucModelType.TN93).toArray());
private JComboBox aaSubstCombo = new JComboBox(AminoAcidModelType.values());
private JComboBox binarySubstCombo = new JComboBox(BinaryModelType.values());
private JCheckBox useAmbiguitiesTreeLikelihoodCheck = new JCheckBox(
"Use ambiguities in the tree likelihood associated with this model");
private JComboBox frequencyCombo = new JComboBox(FrequencyPolicyType
.values());
private JComboBox heteroCombo = new JComboBox(new String[] { "None",
"Gamma", "Invariant Sites", "Gamma + Invariant Sites" });
private JComboBox gammaCatCombo = new JComboBox(new String[] { "4", "5",
"6", "7", "8", "9", "10" });
private JLabel gammaCatLabel;
private JComboBox codingCombo = new JComboBox(new String[] { "Off",
"2 partitions: positions (1 + 2), 3",
"3 partitions: positions 1, 2, 3" });
private JCheckBox substUnlinkCheck = new JCheckBox(
"Unlink substitution rate parameters across codon positions");
private JCheckBox heteroUnlinkCheck = new JCheckBox(
"Unlink rate heterogeneity model across codon positions");
private JCheckBox freqsUnlinkCheck = new JCheckBox(
"Unlink base frequencies across codon positions");
private JButton setSRD06Button;
public static final boolean ENABLE_ROBUST_COUNTING = false;
private JButton setDndsButton;
private JCheckBox dolloCheck = new JCheckBox("Use Stochastic Dollo Model");
// private JComboBox dolloCombo = new JComboBox(new String[]{"Analytical",
// "Sample"});
private JComboBox discreteTraitSiteModelCombo = new JComboBox(
DiscreteSubstModelType.values());
private JCheckBox activateBSSVS = new JCheckBox(
// "Activate BSSVS"
"Infer social network with BSSVS");
private JTextField microsatName = new JTextField();
private WholeNumberField microsatMax = new WholeNumberField(2,
Integer.MAX_VALUE);
private WholeNumberField microsatMin = new WholeNumberField(1,
Integer.MAX_VALUE);
private JComboBox rateProportionCombo = new JComboBox(
MicroSatModelType.RateProportionality.values());
private JComboBox mutationBiasCombo = new JComboBox(
MicroSatModelType.MutationalBias.values());
private JComboBox phaseCombo = new JComboBox(MicroSatModelType.Phase
.values());
JCheckBox shareMicroSatCheck = new JCheckBox(
"Share one microsatellite among all substitution model(s)");
protected final PartitionSubstitutionModel model;
public PartitionModelPanel(final PartitionSubstitutionModel partitionModel) {
super(12, (OSType.isMac() ? 6 : 24));
this.model = partitionModel;
initCodonPartitionComponents();
PanelUtils.setupComponent(nucSubstCombo);
nucSubstCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
model.setNucSubstitutionModel((NucModelType) nucSubstCombo
.getSelectedItem());
}
});
nucSubstCombo
.setToolTipText("<html>Select the type of nucleotide substitution model.</html>");
PanelUtils.setupComponent(aaSubstCombo);
aaSubstCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
model.setAaSubstitutionModel((AminoAcidModelType) aaSubstCombo
.getSelectedItem());
}
});
aaSubstCombo
.setToolTipText("<html>Select the type of amino acid substitution model.</html>");
PanelUtils.setupComponent(binarySubstCombo);
binarySubstCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
model
.setBinarySubstitutionModel((BinaryModelType) binarySubstCombo
.getSelectedItem());
useAmbiguitiesTreeLikelihoodCheck.setSelected(binarySubstCombo
.getSelectedItem() == BinaryModelType.BIN_COVARION);
useAmbiguitiesTreeLikelihoodCheck.setEnabled(binarySubstCombo
.getSelectedItem() != BinaryModelType.BIN_COVARION);
}
});
binarySubstCombo
.setToolTipText("<html>Select the type of binary substitution model.</html>");
PanelUtils.setupComponent(useAmbiguitiesTreeLikelihoodCheck);
useAmbiguitiesTreeLikelihoodCheck.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
model
.setUseAmbiguitiesTreeLikelihood(useAmbiguitiesTreeLikelihoodCheck
.isSelected());
}
});
useAmbiguitiesTreeLikelihoodCheck
.setToolTipText("<html>Detemine useAmbiguities in < treeLikelihood > .</html>");
PanelUtils.setupComponent(frequencyCombo);
frequencyCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
model.setFrequencyPolicy((FrequencyPolicyType) frequencyCombo
.getSelectedItem());
}
});
frequencyCombo
.setToolTipText("<html>Select the policy for determining the base frequencies.</html>");
PanelUtils.setupComponent(heteroCombo);
heteroCombo
.setToolTipText("<html>Select the type of site-specific rate<br>heterogeneity model.</html>");
heteroCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
boolean gammaHetero = heteroCombo.getSelectedIndex() == 1
|| heteroCombo.getSelectedIndex() == 3;
model.setGammaHetero(gammaHetero);
model.setInvarHetero(heteroCombo.getSelectedIndex() == 2
|| heteroCombo.getSelectedIndex() == 3);
if (gammaHetero) {
gammaCatLabel.setEnabled(true);
gammaCatCombo.setEnabled(true);
} else {
gammaCatLabel.setEnabled(false);
gammaCatCombo.setEnabled(false);
}
if (codingCombo.getSelectedIndex() != 0) {
heteroUnlinkCheck
.setEnabled(heteroCombo.getSelectedIndex() != 0);
heteroUnlinkCheck.setSelected(heteroCombo
.getSelectedIndex() != 0);
}
}
});
PanelUtils.setupComponent(gammaCatCombo);
gammaCatCombo
.setToolTipText("<html>Select the number of categories to use for<br>the discrete gamma rate heterogeneity model.</html>");
gammaCatCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
model.setGammaCategories(gammaCatCombo.getSelectedIndex() + 4);
}
});
Action setSRD06Action = new AbstractAction("Use SRD06 Model") {
public void actionPerformed(ActionEvent actionEvent) {
setSRD06Model();
}
};
setSRD06Button = new JButton(setSRD06Action);
PanelUtils.setupComponent(setSRD06Button);
setSRD06Button
.setToolTipText("<html>Sets the SRD06 model as described in<br>"
+ "Shapiro, Rambaut & Drummond (2006) <i>MBE</i> <b>23</b>: 7-9.</html>");
Action setDndsAction = new AbstractAction("dNdS counting") {
public void actionPerformed(ActionEvent e) {
setDndsCounting();
}
};
setDndsButton = new JButton(setDndsAction);
PanelUtils.setupComponent(setDndsButton);
setDndsButton.setToolTipText("<html>TODO</html>");
PanelUtils.setupComponent(dolloCheck);
dolloCheck.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
model.setDolloModel(true);
}
});
dolloCheck.setEnabled(true);
dolloCheck
.setToolTipText("<html>Activates a Stochastic Dollo model as described in<br>"
+ "Alekseyenko, Lee & Suchard (2008) <i>Syst Biol</i> <b>57</b>: 772-784.</html>");
PanelUtils.setupComponent(discreteTraitSiteModelCombo);
discreteTraitSiteModelCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
model
.setDiscreteSubstType((DiscreteSubstModelType) discreteTraitSiteModelCombo
.getSelectedItem());
}
});
PanelUtils.setupComponent(activateBSSVS);
activateBSSVS.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
model.setActivateBSSVS(activateBSSVS.isSelected());
}
});
activateBSSVS
.setToolTipText("<html>Actives Bayesian stochastic search variable selection on the rates as decribed in<br>"
+ "Lemey, Rambaut, Drummond & Suchard (2009) <i>PLoS Computational Biology</i> <b>5</b>: e1000520</html>");
microsatName.setColumns(30);
microsatName.addKeyListener(new java.awt.event.KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
model.getMicrosatellite().setName(microsatName.getText());
}
});
microsatMax.setColumns(10);
microsatMax.addKeyListener(new java.awt.event.KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
model.getMicrosatellite().setMax(
Integer.parseInt(microsatMax.getText()));
}
});
microsatMin.setColumns(10);
microsatMin.addKeyListener(new java.awt.event.KeyListener() {
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
model.getMicrosatellite().setMin(
Integer.parseInt(microsatMin.getText()));
}
});
PanelUtils.setupComponent(shareMicroSatCheck);
shareMicroSatCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
model.getOptions().shareMicroSat = shareMicroSatCheck
.isSelected();
if (shareMicroSatCheck.isSelected()) {
model.getOptions().shareMicroSat();
} else {
model.getOptions().unshareMicroSat();
}
setOptions();
}
});
PanelUtils.setupComponent(rateProportionCombo);
rateProportionCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
model
.setRatePorportion((MicroSatModelType.RateProportionality) rateProportionCombo
.getSelectedItem());
}
});
// rateProportionCombo.setToolTipText("<html>Select the type of microsatellite substitution model.</html>");
PanelUtils.setupComponent(mutationBiasCombo);
mutationBiasCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
model
.setMutationBias((MicroSatModelType.MutationalBias) mutationBiasCombo
.getSelectedItem());
}
});
PanelUtils.setupComponent(phaseCombo);
phaseCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
model.setPhase((MicroSatModelType.Phase) phaseCombo
.getSelectedItem());
}
});
setupPanel();
setOpaque(false);
}
/**
* Sets the components up according to the partition model - but does not
* layout the top level options panel.
*/
public void setOptions() {
if (SiteModelsPanel.DEBUG) {
String modelName = (model == null) ? "null" : model.getName();
Logger.getLogger("dr.app.beauti").info(
"ModelsPanel.setModelOptions(" + modelName + ")");
}
if (model == null) {
return;
}
int dataType = model.getDataType().getType();
switch (dataType) {
case DataType.NUCLEOTIDES:
nucSubstCombo.setSelectedItem(model.getNucSubstitutionModel());
frequencyCombo.setSelectedItem(model.getFrequencyPolicy());
break;
case DataType.AMINO_ACIDS:
aaSubstCombo.setSelectedItem(model.getAaSubstitutionModel());
break;
case DataType.TWO_STATES:
case DataType.COVARION:
binarySubstCombo
.setSelectedItem(model.getBinarySubstitutionModel());
useAmbiguitiesTreeLikelihoodCheck.setSelected(model
.isUseAmbiguitiesTreeLikelihood());
break;
case DataType.GENERAL:
discreteTraitSiteModelCombo.setSelectedItem(model
.getDiscreteSubstType());
activateBSSVS.setSelected(model.isActivateBSSVS());
break;
case DataType.MICRO_SAT:
microsatName.setText(model.getMicrosatellite().getName());
microsatMax.setText(Integer.toString(model.getMicrosatellite()
.getMax()));
microsatMin.setText(Integer.toString(model.getMicrosatellite()
.getMin()));
shareMicroSatCheck.setSelected(model.getOptions().shareMicroSat);
rateProportionCombo.setSelectedItem(model.getRatePorportion());
mutationBiasCombo.setSelectedItem(model.getMutationBias());
phaseCombo.setSelectedItem(model.getPhase());
shareMicroSatCheck.setEnabled(model.getOptions()
.getPartitionSubstitutionModels(Microsatellite.INSTANCE)
.size() > 1);
break;
default:
throw new IllegalArgumentException("Unknown data type");
}
if (model.isGammaHetero() && !model.isInvarHetero()) {
heteroCombo.setSelectedIndex(1);
} else if (!model.isGammaHetero() && model.isInvarHetero()) {
heteroCombo.setSelectedIndex(2);
} else if (model.isGammaHetero() && model.isInvarHetero()) {
heteroCombo.setSelectedIndex(3);
} else {
heteroCombo.setSelectedIndex(0);
}
gammaCatCombo.setSelectedIndex(model.getGammaCategories() - 4);
if (model.getCodonHeteroPattern() == null) {
codingCombo.setSelectedIndex(0);
} else if (model.getCodonHeteroPattern().equals("112")) {
codingCombo.setSelectedIndex(1);
} else {
codingCombo.setSelectedIndex(2);
}
substUnlinkCheck.setSelected(model.isUnlinkedSubstitutionModel());
heteroUnlinkCheck.setSelected(model.isUnlinkedHeterogeneityModel());
freqsUnlinkCheck.setSelected(model.isUnlinkedFrequencyModel());
dolloCheck.setSelected(model.isDolloModel());
}
private void setDndsCounting() {
nucSubstCombo.setSelectedIndex(0);
frequencyCombo.setSelectedIndex(0);
heteroCombo.setSelectedIndex(0);
gammaCatCombo.setOpaque(true);
codingCombo.setSelectedIndex(2);
substUnlinkCheck.setSelected(true);
heteroUnlinkCheck.setSelected(false);
freqsUnlinkCheck.setSelected(true);
}
/**
* Configure this panel for the Shapiro, Rambaut and Drummond 2006 codon
* position model
*/
private void setSRD06Model() {
nucSubstCombo.setSelectedIndex(0);
heteroCombo.setSelectedIndex(1);
codingCombo.setSelectedIndex(1);
substUnlinkCheck.setSelected(true);
heteroUnlinkCheck.setSelected(true);
}
/**
* Lays out the appropriate components in the panel for this partition
* model.
*/
private void setupPanel() {
switch (model.getDataType().getType()) {
case DataType.NUCLEOTIDES:
addComponentWithLabel("Substitution Model:", nucSubstCombo);
addComponentWithLabel("Base frequencies:", frequencyCombo);
addComponentWithLabel("Site Heterogeneity Model:", heteroCombo);
heteroCombo.setSelectedIndex(0);
gammaCatLabel = addComponentWithLabel(
"Number of Gamma Categories:", gammaCatCombo);
gammaCatCombo.setEnabled(false);
addSeparator();
addComponentWithLabel("Partition into codon positions:",
codingCombo);
JPanel panel2 = new JPanel();
panel2.setOpaque(false);
panel2.setLayout(new BoxLayout(panel2, BoxLayout.PAGE_AXIS));
panel2.setBorder(BorderFactory
.createTitledBorder("Link/Unlink parameters:"));
panel2.add(substUnlinkCheck);
panel2.add(heteroUnlinkCheck);
panel2.add(freqsUnlinkCheck);
addComponent(panel2);
addComponent(setSRD06Button);
if (ENABLE_ROBUST_COUNTING) {
addComponent(setDndsButton);
}
break;
case DataType.AMINO_ACIDS:
addComponentWithLabel("Substitution Model:", aaSubstCombo);
addComponentWithLabel("Site Heterogeneity Model:", heteroCombo);
heteroCombo.setSelectedIndex(0);
gammaCatLabel = addComponentWithLabel(
"Number of Gamma Categories:", gammaCatCombo);
gammaCatCombo.setEnabled(false);
break;
case DataType.TWO_STATES:
case DataType.COVARION:
addComponentWithLabel("Substitution Model:", binarySubstCombo);
addComponentWithLabel("Base frequencies:", frequencyCombo);
addComponentWithLabel("Site Heterogeneity Model:", heteroCombo);
heteroCombo.setSelectedIndex(0);
gammaCatLabel = addComponentWithLabel(
"Number of Gamma Categories:", gammaCatCombo);
gammaCatCombo.setEnabled(false);
addSeparator();
addComponentWithLabel("", useAmbiguitiesTreeLikelihoodCheck);
break;
case DataType.GENERAL:
addComponentWithLabel("Discrete Trait Substitution Model:",
discreteTraitSiteModelCombo);
addComponent(activateBSSVS);
break;
case DataType.MICRO_SAT:
addComponentWithLabel("Microsatellite Name:", microsatName);
addComponentWithLabel("Max of Length:", microsatMax);
addComponentWithLabel("Min of Length:", microsatMin);
addComponent(shareMicroSatCheck);
addSeparator();
addComponentWithLabel("Rate Proportionality:", rateProportionCombo);
addComponentWithLabel("Mutational Bias:", mutationBiasCombo);
addComponentWithLabel("Phase:", phaseCombo);
break;
default:
throw new IllegalArgumentException("Unknown data type");
}
if (BeautiApp.advanced) {
addSeparator();
addComponent(dolloCheck);
}
setOptions();
}
/**
* Initializes and binds the components related to modeling codon positions.
*/
private void initCodonPartitionComponents() {
PanelUtils.setupComponent(substUnlinkCheck);
substUnlinkCheck.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
model.setUnlinkedSubstitutionModel(substUnlinkCheck
.isSelected());
}
});
substUnlinkCheck.setEnabled(false);
substUnlinkCheck.setToolTipText(""
+ "<html>Gives each codon position partition different<br>"
+ "substitution model parameters.</html>");
PanelUtils.setupComponent(heteroUnlinkCheck);
heteroUnlinkCheck.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
model.setUnlinkedHeterogeneityModel(heteroUnlinkCheck
.isSelected());
}
});
heteroUnlinkCheck.setEnabled(heteroCombo.getSelectedIndex() != 0);
heteroUnlinkCheck
.setToolTipText("<html>Gives each codon position partition different<br>rate heterogeneity model parameters.</html>");
PanelUtils.setupComponent(freqsUnlinkCheck);
freqsUnlinkCheck.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
model.setUnlinkedFrequencyModel(freqsUnlinkCheck.isSelected());
}
});
freqsUnlinkCheck.setEnabled(false);
freqsUnlinkCheck
.setToolTipText("<html>Gives each codon position partition different<br>nucleotide frequency parameters.</html>");
PanelUtils.setupComponent(codingCombo);
codingCombo
.setToolTipText("<html>Select how to partition the codon positions.</html>");
codingCombo.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent ev) {
switch (codingCombo.getSelectedIndex()) {
case 0:
model.setCodonHeteroPattern(null);
break;
case 1:
model.setCodonHeteroPattern("112");
break;
default:
model.setCodonHeteroPattern("123");
break;
}
if (codingCombo.getSelectedIndex() != 0) { // codon position
// partitioning
substUnlinkCheck.setEnabled(true);
heteroUnlinkCheck
.setEnabled(heteroCombo.getSelectedIndex() != 0);
freqsUnlinkCheck.setEnabled(true);
substUnlinkCheck.setSelected(true);
heteroUnlinkCheck.setSelected(heteroCombo
.getSelectedIndex() != 0);
freqsUnlinkCheck.setSelected(true);
} else {
substUnlinkCheck.setEnabled(false);
substUnlinkCheck.setSelected(false);
heteroUnlinkCheck.setEnabled(false);
heteroUnlinkCheck.setSelected(false);
freqsUnlinkCheck.setEnabled(false);
freqsUnlinkCheck.setSelected(false);
}
}
});
}
}
|
package com.dmdirc.addons.ui_swing.actions;
import com.dmdirc.logger.ErrorLevel;
import com.dmdirc.logger.Logger;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
import java.io.IOException;
import javax.swing.AbstractAction;
import javax.swing.text.JTextComponent;
/**
* Paste action that strips newlines from pastes.
*/
public final class NoNewlinesPasteAction extends AbstractAction {
/**
* A version number for this class. It should be changed whenever the class
* structure is changed (or anything else that would prevent serialized
* objects being unserialized with the new class).
*/
private static final long serialVersionUID = 1;
/**
* Creates a new instance of NoNewlinesPasteAction.
*/
public NoNewlinesPasteAction() {
super("TopicPasteAction");
}
/**
* {@inheritDoc}
*
* @param e Action event
*/
@Override
public void actionPerformed(final ActionEvent e) {
final JTextComponent comp;
if (e.getSource() instanceof JTextComponent) {
comp = (JTextComponent) e.getSource();
} else {
return;
}
String clipboard = null;
if (!Toolkit.getDefaultToolkit().getSystemClipboard().
isDataFlavorAvailable(DataFlavor.stringFlavor)) {
return;
}
try {
//get the contents of the clipboard
clipboard = (String) Toolkit.getDefaultToolkit().
getSystemClipboard().getData(DataFlavor.stringFlavor);
//remove newlines
clipboard = clipboard.replaceAll("(\r\n|\n|\r)", " ");
//insert the contents at the current cursor position
comp.replaceSelection(clipboard);
} catch (IOException ex) {
Logger.userError(ErrorLevel.LOW, "Unable to get clipboard contents: " + ex.getMessage());
} catch (UnsupportedFlavorException ex) {
Logger.appError(ErrorLevel.LOW, "Unable to get clipboard contents", ex);
}
}
}
|
package org.intermine.util;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.Map;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.intermine.api.profile.InterMineBag;
/**
* Mail utilities for the webapp.
*
* @author Kim Rutherford
* @author Matthew Wakeling
*/
public abstract class MailUtils
{
private MailUtils() {
// private constructor
}
/**
* Send a welcoming email to an email address
*
* @param to the address to send to
* @param webProperties properties such as the from address
* @throws Exception if there is a problem creating the email
*/
public static void email(String to, final Map webProperties) throws Exception {
String subject = (String) webProperties.get("mail.subject");
String text = (String) webProperties.get("mail.text");
email(to, subject, text, webProperties);
}
/**
* Send an email to an address, supplying the recipient, subject and body.
*
* @param to the address to send to
* @param subject The Subject of the email
* @param body The content of the email
* @param from the address to send from
* @param webProperties Common properties for all emails (such as from, authentication)
* @throws MessagingException if there is a problem creating the email
*/
public static void email(String to, String subject, String body, String from,
final Map webProperties) throws MessagingException {
final String user = (String) webProperties.get("mail.smtp.user");
String smtpPort = (String) webProperties.get("mail.smtp.port");
String authFlag = (String) webProperties.get("mail.smtp.auth");
String starttlsFlag = (String) webProperties.get("mail.smtp.starttls.enable");
Properties properties = System.getProperties();
properties.put("mail.smtp.host", webProperties.get("mail.host"));
properties.put("mail.smtp.user", user);
// Fix to "javax.mail.MessagingException: 501 Syntactically
// invalid HELO argument(s)" problem
properties.put("mail.smtp.localhost", "localhost");
if (smtpPort != null) {
properties.put("mail.smtp.port", smtpPort);
}
if (starttlsFlag != null) {
properties.put("mail.smtp.starttls.enable", starttlsFlag);
}
if (authFlag != null) {
properties.put("mail.smtp.auth", authFlag);
}
Session session;
if (authFlag != null && ("true".equals(authFlag) || "t".equals(authFlag))) {
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
String password = (String) webProperties.get("mail.server.password");
return new PasswordAuthentication(user, password);
}
};
session = Session.getDefaultInstance(properties, authenticator);
} else {
session = Session.getDefaultInstance(properties);
}
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, InternetAddress.parse(to, true)[0]);
message.setSubject(subject);
message.setContent(body, "text/plain");
Transport.send(message);
}
/**
* @param to the address to send to
* @param subject The Subject of the email
* @param body The content of the email
* @param webProperties Common properties for all emails (such as from, authentication)
* @throws MessagingException if there is a problem creating the email
*/
public static void email(String to, String subject, String body, final Map webProperties)
throws MessagingException {
String from = (String) webProperties.get("mail.from");
email(to, subject, body, from, webProperties);
}
/**
* Send a password change email to an email address
*
* @param to the address to send to
* @param url the URL to embed in the email
* @param webProperties properties such as the from address
* @throws Exception if there is a problem creating the email
*/
public static void emailPasswordToken(String to, String url, final Map webProperties)
throws Exception {
String projectTitle = (String) webProperties.get("project.title");
String baseSubject = (String) webProperties.get("mail.passwordSubject");
String mailSubject = MessageFormat.format(baseSubject, new Object[] {projectTitle});
String mailText = (String) webProperties.get("mail.passwordText");
String mailTextWithUrl = MessageFormat.format(mailText, new Object[] {url});
email(to, mailSubject, mailTextWithUrl, webProperties);
}
/**
* Subscribe the given email address to the mailing list specified in the
* mine config file
* @param email the email to subscribe
* @param webProperties the web properties
* @throws Exception when somethign goes wrong
*/
public static void subscribe(String email, final Map webProperties) throws Exception {
String to = (String) webProperties.get("mail.mailing-list");
String subject = "";
String body = "";
email(to, subject, body, email, webProperties);
}
/**
* Send a 'sharing list' message
*
* @param to the address to send to
* @param sharingUser the user sharing the list
* @param bag the list shared
* @param webProperties properties such as the from address
* @throws Exception if there is a problem creating the email
*/
public static void emailSharingList(String to, String sharingUser, InterMineBag bag,
final Map webProperties) throws Exception {
String applicationName = (String) webProperties.get("mail.application");
String subject = applicationName + " shared list (" + bag.getName() + ")";
String listUrl = webProperties.get("webapp.deploy.url") + "/"
+ webProperties.get("webapp.path") + "/"
+ "login.do?returnto=%2FbagDetails.do%3Fscope%3Dall%26bagName%3D"
+ URLEncoder.encode(bag.getName(), "UTF-8");
StringBuffer bodyMsg = new StringBuffer();
bodyMsg.append("User " + sharingUser + " has shared a list of " + bag.getType() + "s ");
bodyMsg.append("with you called \"" + bag.getName() + "\".\n\n");
bodyMsg.append("Click here to view the list: " + listUrl + ".\n\n");
bodyMsg.append("If " + sharingUser + " deletes or modifies this list, you will not be ");
bodyMsg.append("notified.\nYou may COPY this list to your own account by using the ");
bodyMsg.append(" list operations on the list page.\n\n");
bodyMsg.append("If you have any problems or questions, please don't hesitate ");
bodyMsg.append("to contact us. We can be reached by replying to this email or at the ");
bodyMsg.append("bottom of each page on " + applicationName + ".\n\n");
bodyMsg.append("Thank you.\nThe " + applicationName + " team");
email(to, subject, bodyMsg.toString(), webProperties);
}
}
|
package edu.ntnu.idi.goldfish.preprocessors;
import edu.ntnu.idi.goldfish.StopWatch;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.SequenceFile.Writer;
import org.apache.hadoop.io.Text;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.impl.common.FastByIDMap;
import org.apache.mahout.cf.taste.impl.model.GenericDataModel;
import org.apache.mahout.cf.taste.impl.model.GenericPreference;
import org.apache.mahout.cf.taste.impl.model.GenericUserPreferenceArray;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.model.Preference;
import org.apache.mahout.cf.taste.model.PreferenceArray;
import org.apache.mahout.clustering.classify.WeightedVectorWritable;
import org.apache.mahout.clustering.kmeans.KMeansDriver;
import org.apache.mahout.clustering.kmeans.Kluster;
import org.apache.mahout.common.HadoopUtil;
import org.apache.mahout.common.distance.DistanceMeasure;
import org.apache.mahout.math.NamedVector;
import org.apache.mahout.math.RandomAccessSparseVector;
import org.apache.mahout.math.Vector.Element;
import org.apache.mahout.math.VectorWritable;
import java.io.File;
import java.io.IOException;
import java.util.*;
public class KMeansWrapper {
public static Map<Long, Integer> getItemIndices(DataModel dataModel) throws TasteException {
Map<Long, Integer> map = new HashMap<Long, Integer>();
Iterator<Long> iter = dataModel.getItemIDs();
int i = 0;
while(iter.hasNext()) {
map.put(iter.next(), i);
}
return map;
}
/**
* Split the dataModel into a set of datamodels based on a kMeans clustering of the users
* @throws TasteException
*/
public static DataModel[] clusterUsers(DataModel dataModel, int N, DistanceMeasure measure, double convergenceDelta, int maxIterations, boolean runClustering, double clusterClassificationThreshold, boolean runSequential) throws IOException, InterruptedException, ClassNotFoundException, TasteException {
StopWatch.start("clustering");
File testData = new File("clusterdata/users/");
testData.mkdirs();
List<NamedVector> users = getUserVectors(dataModel);
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
// store users in sequence file
writeUsers(users, new Path("clusterdata/users/part-00000"), conf);
// write initial cluster centers
writeClusterCenters(users, fs, conf, N, measure);
Path output = new Path("clusterdata/output");
// clean
HadoopUtil.delete(conf, output);
// Run k-means algorithm
KMeansDriver.run(
conf, // configuration
new Path("clusterdata/users"), // the directory pathname for input points
new Path("clusterdata/clusters"), // the directory pathname for initial & computed clusters
output, // the directory pathname for output points
convergenceDelta, // the convergence delta value
maxIterations, // the maximum number of iterations
runClustering, // true if points are to be clustered after iterations are completed
clusterClassificationThreshold, // clustering strictness/ outlier removal parameter.
runSequential // if true execute sequental algorithm
);
DataModel[] dataModels = readClusters(new Path("clusterdata/output/clusteredPoints/part-m-0"), fs, conf, N);
int[] clusterSizes = new int[N];
for(int i=0; i<N; i++) {
clusterSizes[i] = dataModels[i].getNumUsers();
}
Arrays.sort(clusterSizes);
ArrayUtils.reverse(clusterSizes);
System.out.format("Delta: %.2f Threshold: %.2f %d clusters: %s \n", convergenceDelta, clusterClassificationThreshold, N, Arrays.toString(clusterSizes));
return dataModels;
}
/**
* Write all users to SequenceFile
* Since kMeans is distributed on Hadoop, it needs the set of users available in this format
*/
public static void writeUsers(List<NamedVector> users, Path path, Configuration conf) throws IOException {
FileSystem fs = FileSystem.get(path.toUri(), conf);
Writer writer = new Writer(fs, conf, path, Text.class, VectorWritable.class);
for (NamedVector user : users) {
writer.append(new Text(user.getName()), new VectorWritable(user));
}
writer.close();
}
/**
* Create N clusters, and use the first N users as cluster centers
*/
public static void writeClusterCenters(List<NamedVector>users, FileSystem fs, Configuration conf, int N, DistanceMeasure dm) throws IOException {
Path path = new Path("clusterdata/clusters/part-00000");
Writer writer = new Writer(fs, conf, path, Text.class, Kluster.class);
//Write initial cluster centers
for (int i = 0; i < N; i++) {
Kluster cluster = new Kluster(users.get(i), i, dm);
writer.append(new Text(cluster.getIdentifier()), cluster);
}
writer.close();
}
public static DataModel[] readClusters(Path path, FileSystem fs, Configuration conf, int N) throws IOException {
@SuppressWarnings("unchecked")
FastByIDMap<PreferenceArray>[] maps = new FastByIDMap[N];
for(int i = 0; i < N; i++) {
maps[i] = new FastByIDMap<PreferenceArray>();
}
// read clusters from Hadoop Sequence File
SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, conf);
// store objects
IntWritable clusterId = new IntWritable();
WeightedVectorWritable value = new WeightedVectorWritable();
NamedVector vector;
long userId;
while (reader.next(clusterId, value)) {
// Read output, print vector, cluster ID
vector = (NamedVector) value.getVector();
userId = Long.parseLong(vector.getName());
maps[clusterId.get()].put(userId, namedVecToPreferenceArr(vector));
}
reader.close();
DataModel[] models = new DataModel[N];
for(int i = 0; i < N; i++) {
models[i] = new GenericDataModel(maps[i]);
}
return models;
}
public static List<NamedVector> getUserVectors(DataModel dataModel) throws IOException, TasteException {
List<NamedVector> users = new ArrayList<NamedVector>();
Iterator<Long> userIterator = dataModel.getUserIDs();
int cardinality = dataModel.getNumItems();
PreferenceArray prefs;
while(userIterator.hasNext()) {
prefs = dataModel.getPreferencesFromUser(userIterator.next());
users.add(preferenceArrToNamedVec(prefs, cardinality));
}
return users;
}
public static NamedVector preferenceArrToNamedVec(PreferenceArray prefs, int cardinality) {
RandomAccessSparseVector ratings = new RandomAccessSparseVector((int)10e10);
for (Preference preference : prefs) {
ratings.set((int) preference.getItemID(), preference.getValue());
}
return new NamedVector(ratings, ""+prefs.getUserID(0));
}
public static PreferenceArray namedVecToPreferenceArr(NamedVector vector) {
long userId = Long.parseLong(vector.getName());
// help for iterating over the sparse named vector
RandomAccessSparseVector sparseVector = new RandomAccessSparseVector(vector);
Iterator<Element> iter = sparseVector.iterateNonZero();
// list for storing preferences
List<Preference> prefs = new ArrayList<Preference>();
Element next;
Preference pref;
while(iter.hasNext()) {
next = iter.next();
pref = new GenericPreference(userId, next.index(), (float) next.get());
prefs.add(pref);
}
return new GenericUserPreferenceArray(prefs);
}
}
|
package com.mebigfatguy.fbcontrib.detect;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.bcel.Constants;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.AnnotationEntry;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.CodeException;
import org.apache.bcel.classfile.ExceptionTable;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.LocalVariable;
import org.apache.bcel.classfile.LocalVariableTable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.classfile.ParameterAnnotationEntry;
import org.apache.bcel.generic.Type;
import com.mebigfatguy.fbcontrib.utils.BugType;
import com.mebigfatguy.fbcontrib.utils.OpcodeUtils;
import com.mebigfatguy.fbcontrib.utils.RegisterUtils;
import com.mebigfatguy.fbcontrib.utils.SignatureUtils;
import com.mebigfatguy.fbcontrib.utils.ToString;
import com.mebigfatguy.fbcontrib.utils.UnmodifiableSet;
import com.mebigfatguy.fbcontrib.utils.Values;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
import edu.umd.cs.findbugs.OpcodeStack;
import edu.umd.cs.findbugs.ba.ClassContext;
/**
* looks for parameters that are defined by classes, but only use methods defined by an implemented interface or super class. Relying on concrete classes in
* public signatures causes cohesion, and makes low impact changes more difficult.
*/
public class OverlyConcreteParameter extends BytecodeScanningDetector {
private static final Set<String> CONVERSION_ANNOTATIONS = UnmodifiableSet.create("Ljavax/persistence/Converter;", "Ljavax/ws/rs/Consumes;");
private static final Set<String> CONVERSION_SUPER_CLASSES = UnmodifiableSet.create("com.fasterxml.jackson.databind.JsonSerializer",
"com.fasterxml.jackson.databind.JsonDeserializer");
private final BugReporter bugReporter;
private JavaClass[] constrainingClasses;
private Map<Integer, Map<JavaClass, List<MethodInfo>>> parameterDefiners;
private BitSet usedParameters;
private JavaClass objectClass;
private JavaClass cls;
private OpcodeStack stack;
private int parmCount;
private boolean methodSignatureIsConstrained;
private boolean methodIsStatic;
/**
* constructs a OCP detector given the reporter to report bugs on
*
* @param bugReporter
* the sync of bug reports
*/
public OverlyConcreteParameter(final BugReporter bugReporter) {
this.bugReporter = bugReporter;
try {
objectClass = Repository.lookupClass("java/lang/Object");
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
objectClass = null;
}
}
/**
* implements the visitor to collect classes that constrains this class (super classes/interfaces) and to reset the opcode stack
*
* @param classContext
* the currently parse class
*/
@Override
public void visitClassContext(ClassContext classContext) {
try {
cls = classContext.getJavaClass();
if (!isaConversionClass(cls)) {
JavaClass[] infs = cls.getAllInterfaces();
JavaClass[] sups = cls.getSuperClasses();
constrainingClasses = new JavaClass[infs.length + sups.length];
System.arraycopy(infs, 0, constrainingClasses, 0, infs.length);
System.arraycopy(sups, 0, constrainingClasses, infs.length, sups.length);
parameterDefiners = new HashMap<Integer, Map<JavaClass, List<MethodInfo>>>();
usedParameters = new BitSet();
stack = new OpcodeStack();
super.visitClassContext(classContext);
}
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
} finally {
constrainingClasses = null;
parameterDefiners = null;
usedParameters = null;
stack = null;
}
}
/**
* implements the visitor to look to see if this method is constrained by a superclass or interface.
*
* @param obj
* the currently parsed method
*/
@Override
public void visitMethod(Method obj) {
methodSignatureIsConstrained = false;
String methodName = obj.getName();
if (!Values.CONSTRUCTOR.equals(methodName) && !Values.STATIC_INITIALIZER.equals(methodName)) {
String methodSig = obj.getSignature();
methodSignatureIsConstrained = methodIsSpecial(methodName, methodSig) || methodHasSyntheticTwin(methodName, methodSig);
if (!methodSignatureIsConstrained) {
for (AnnotationEntry entry : obj.getAnnotationEntries()) {
if (CONVERSION_ANNOTATIONS.contains(entry.getAnnotationType())) {
methodSignatureIsConstrained = true;
break;
}
}
}
if (!methodSignatureIsConstrained) {
String parms = methodSig.split("\\(|\\)")[1];
if (parms.indexOf(';') >= 0) {
outer: for (JavaClass cls : constrainingClasses) {
Method[] methods = cls.getMethods();
for (Method m : methods) {
if (methodName.equals(m.getName()) && methodSig.equals(m.getSignature())) {
methodSignatureIsConstrained = true;
break outer;
}
}
}
}
}
}
}
/**
* implements the visitor to collect information about the parameters of a this method
*
* @param obj
* the currently parsed code block
*/
@Override
public void visitCode(final Code obj) {
try {
if (methodSignatureIsConstrained) {
return;
}
if (obj.getCode() == null) {
return;
}
Method m = getMethod();
if (m.isSynthetic()) {
return;
}
if (m.getName().startsWith("access$")) {
return;
}
methodIsStatic = m.isStatic();
parmCount = m.getArgumentTypes().length;
if (parmCount == 0) {
return;
}
parameterDefiners.clear();
usedParameters.clear();
stack.resetForMethodEntry(this);
if (buildParameterDefiners()) {
super.visitCode(obj);
reportBugs();
}
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
}
}
/**
* implements the visitor to filter out parameter use where the actual defined type of the method declaration is needed. What remains could be more
* abstractly defined.
*
* @param seen
* the currently parsed opcode
*/
@Override
public void sawOpcode(final int seen) {
if (parameterDefiners.isEmpty()) {
return;
}
try {
stack.precomputation(this);
if (OpcodeUtils.isInvoke(seen)) {
String methodSig = getSigConstantOperand();
Type[] parmTypes = Type.getArgumentTypes(methodSig);
int stackDepth = stack.getStackDepth();
if (stackDepth >= parmTypes.length) {
for (int i = 0; i < parmTypes.length; i++) {
OpcodeStack.Item itm = stack.getStackItem(i);
int reg = itm.getRegisterNumber();
removeUselessDefiners(parmTypes[parmTypes.length - i - 1].getSignature(), reg);
}
}
if ((seen != INVOKESPECIAL) && (seen != INVOKESTATIC)) {
if (stackDepth > parmTypes.length) {
OpcodeStack.Item itm = stack.getStackItem(parmTypes.length);
int reg = itm.getRegisterNumber();
int parm = reg;
if (!methodIsStatic) {
parm
}
if ((parm >= 0) && (parm < parmCount)) {
removeUselessDefiners(reg);
}
} else {
parameterDefiners.clear();
}
}
} else if ((seen == ASTORE) || ((seen >= ASTORE_0) && (seen <= ASTORE_3)) || (seen == PUTFIELD) || (seen == GETFIELD) || (seen == PUTSTATIC)
|| (seen == GETSTATIC)) {
// Don't check parameters that are aliased
if (stack.getStackDepth() > 0) {
OpcodeStack.Item itm = stack.getStackItem(0);
int reg = itm.getRegisterNumber();
int parm = reg;
if (!methodIsStatic) {
parm
}
if ((parm >= 0) && (parm < parmCount)) {
parameterDefiners.remove(Integer.valueOf(reg));
}
} else {
parameterDefiners.clear();
}
if ((seen == GETFIELD) || (seen == PUTFIELD)) {
if (stack.getStackDepth() > 1) {
OpcodeStack.Item itm = stack.getStackItem(1);
int reg = itm.getRegisterNumber();
int parm = reg;
if (!methodIsStatic) {
parm
}
if ((parm >= 0) && (parm < parmCount)) {
parameterDefiners.remove(Integer.valueOf(reg));
}
} else {
parameterDefiners.clear();
}
}
} else if (OpcodeUtils.isALoad(seen)) {
int reg = RegisterUtils.getALoadReg(this, seen);
int parm = reg;
if (!methodIsStatic) {
parm
}
if ((parm >= 0) && (parm < parmCount)) {
usedParameters.set(reg);
}
} else if (seen == AASTORE) {
// Don't check parameters that are stored in
if (stack.getStackDepth() >= 3) {
OpcodeStack.Item itm = stack.getStackItem(0);
int reg = itm.getRegisterNumber();
int parm = reg;
if (!methodIsStatic) {
parm
}
if ((parm >= 0) && (parm < parmCount)) {
parameterDefiners.remove(Integer.valueOf(reg));
}
} else {
parameterDefiners.clear();
}
} else if (seen == ARETURN) {
if (stack.getStackDepth() >= 1) {
OpcodeStack.Item item = stack.getStackItem(0);
int reg = item.getRegisterNumber();
int parm = reg;
if (!methodIsStatic) {
parm
}
if ((parm >= 0) && (parm < parmCount)) {
parameterDefiners.remove(Integer.valueOf(reg));
}
} else {
parameterDefiners.clear();
}
}
} finally {
stack.sawOpcode(this, seen);
}
}
/**
* determines whether the method is a baked in special method of the jdk
*
* @param methodName
* the method name to check
* @param methodSig
* the parameter signature of the method to check
* @return if it is a well known baked in method
*/
private static boolean methodIsSpecial(String methodName, String methodSig) {
return ("readObject".equals(methodName) && "(Ljava/io/ObjectInputStream;)V".equals(methodSig));
}
/**
* returns whether this method has an equivalent method that is synthetic, which implies this method is constrained by some Generified interface. We could
* compare parameters but that is a bunch of work that probably doesn't make this test any more precise, so just return true if method name and synthetic is
* found.
*
* @param methodName
* @param methodSig
* @return if a synthetic twin is found
*/
private boolean methodHasSyntheticTwin(String methodName, String methodSig) {
for (Method m : cls.getMethods()) {
if (m.isSynthetic() && m.getName().equals(methodName) && !m.getSignature().equals(methodSig)) {
return true;
}
}
return false;
}
/**
* implements the post processing steps to report the remaining unremoved parameter definers, ie those, that can be defined more abstractly.
*/
private void reportBugs() {
Iterator<Map.Entry<Integer, Map<JavaClass, List<MethodInfo>>>> it = parameterDefiners.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, Map<JavaClass, List<MethodInfo>>> entry = it.next();
Integer reg = entry.getKey();
if (!usedParameters.get(reg.intValue())) {
it.remove();
continue;
}
Map<JavaClass, List<MethodInfo>> definers = entry.getValue();
definers.remove(objectClass);
if (definers.size() > 0) {
String name = "";
LocalVariableTable lvt = getMethod().getLocalVariableTable();
if (lvt != null) {
LocalVariable lv = lvt.getLocalVariable(reg.intValue(), 0);
if (lv != null) {
name = lv.getName();
}
}
int parm = reg.intValue();
if (!methodIsStatic) {
parm
}
parm++; // users expect 1 based parameters
String infName = definers.keySet().iterator().next().getClassName();
bugReporter.reportBug(new BugInstance(this, BugType.OCP_OVERLY_CONCRETE_PARAMETER.name(), NORMAL_PRIORITY).addClass(this).addMethod(this)
.addSourceLine(this, 0).addString(getCardinality(parm) + " parameter '" + name + "' could be declared as " + infName + " instead"));
}
}
}
/**
* returns a string defining what parameter in the signature a certain one is, for the bug report
*
* @param num
* the parameter number
* @return a string describing in english the parameter position
*/
private static String getCardinality(int num) {
if (num == 1) {
return "1st";
}
if (num == 2) {
return "2nd";
}
if (num == 3) {
return "3rd";
}
return num + "th";
}
/**
* builds a map of method information for each method of each interface that each parameter implements of this method
*
* @return a map by parameter id of all the method signatures that interfaces of that parameter implements
*
* @throws ClassNotFoundException
* if the class can't be loaded
*/
private boolean buildParameterDefiners() throws ClassNotFoundException {
Method m = getMethod();
Type[] parms = m.getArgumentTypes();
if (parms.length == 0) {
return false;
}
ParameterAnnotationEntry[] annotations = m.getParameterAnnotationEntries();
boolean hasPossiblyOverlyConcreteParm = false;
for (int i = 0; i < parms.length; i++) {
if ((annotations.length <= i) || (annotations[i] == null) || (annotations[i].getAnnotationEntries().length == 0)) {
String parm = parms[i].getSignature();
if (parm.startsWith("L")) {
String clsName = SignatureUtils.stripSignature(parm);
if (clsName.startsWith("java.lang.")) {
continue;
}
JavaClass cls = Repository.lookupClass(clsName);
if (cls.isClass() && (!cls.isAbstract())) {
Map<JavaClass, List<MethodInfo>> definers = getClassDefiners(cls);
if (definers.size() > 0) {
parameterDefiners.put(Integer.valueOf(i + (methodIsStatic ? 0 : 1)), definers);
hasPossiblyOverlyConcreteParm = true;
}
}
}
}
}
return hasPossiblyOverlyConcreteParm;
}
/**
* returns a map of method information for each public method for each interface this class implements
*
* @param cls
* the class whose interfaces to record
*
* @return a map of (method name)(method sig) by interface
* @throws ClassNotFoundException
* if unable to load the class
*/
private static Map<JavaClass, List<MethodInfo>> getClassDefiners(final JavaClass cls) throws ClassNotFoundException {
Map<JavaClass, List<MethodInfo>> definers = new HashMap<JavaClass, List<MethodInfo>>();
for (JavaClass ci : cls.getAllInterfaces()) {
if ("java.lang.Comparable".equals(ci.getClassName())) {
continue;
}
List<MethodInfo> methodInfos = getPublicMethodInfos(ci);
if (methodInfos.size() > 0) {
definers.put(ci, methodInfos);
}
}
return definers;
}
/**
* returns a list of method information of all public or protected methods in this class
*
* @param cls
* the class to look for methods
* @return a map of (method name)(method signature)
*/
private static List<MethodInfo> getPublicMethodInfos(final JavaClass cls) {
List<MethodInfo> methodInfos = new ArrayList<MethodInfo>();
Method[] methods = cls.getMethods();
for (Method m : methods) {
if ((m.getAccessFlags() & (Constants.ACC_PUBLIC | Constants.ACC_PROTECTED)) != 0) {
ExceptionTable et = m.getExceptionTable();
methodInfos.add(new MethodInfo(m.getName(), m.getSignature(), et == null ? null : et.getExceptionNames()));
}
}
return methodInfos;
}
/**
* parses through the interface that 'may' define a parameter defined by reg, and look to see if we can rule it out, because a method is called on the
* object that can't be satisfied by the interface, if so remove that candidate interface.
*
* @param reg
* the parameter register number to look at
*/
private void removeUselessDefiners(final int reg) {
Map<JavaClass, List<MethodInfo>> definers = parameterDefiners.get(Integer.valueOf(reg));
if ((definers != null) && (definers.size() > 0)) {
String methodSig = getSigConstantOperand();
String methodName = getNameConstantOperand();
MethodInfo methodInfo = new MethodInfo(methodName, methodSig, null);
Iterator<List<MethodInfo>> it = definers.values().iterator();
while (it.hasNext()) {
boolean methodDefined = false;
List<MethodInfo> methodSigs = it.next();
for (MethodInfo mi : methodSigs) {
if (methodInfo.equals(mi)) {
methodDefined = true;
String[] exceptions = mi.getMethodExceptions();
if (exceptions != null) {
for (String ex : exceptions) {
if (!isExceptionHandled(ex)) {
methodDefined = false;
break;
}
}
}
break;
}
}
if (!methodDefined) {
it.remove();
}
}
if (definers.isEmpty()) {
parameterDefiners.remove(Integer.valueOf(reg));
}
}
}
/**
* returns whether this exception is handled either in a try/catch or throws clause at this pc
*
* @param ex
* the name of the exception
*
* @return whether the exception is handled
*/
private boolean isExceptionHandled(String ex) {
try {
JavaClass thrownEx = Repository.lookupClass(ex);
// First look at the throws clause
ExceptionTable et = getMethod().getExceptionTable();
if (et != null) {
String[] throwClauseExNames = et.getExceptionNames();
for (String throwClauseExName : throwClauseExNames) {
JavaClass throwClauseEx = Repository.lookupClass(throwClauseExName);
if (thrownEx.instanceOf(throwClauseEx)) {
return true;
}
}
}
// Next look at the try catch blocks
CodeException[] catchExs = getCode().getExceptionTable();
if (catchExs != null) {
int pc = getPC();
for (CodeException catchEx : catchExs) {
if ((pc >= catchEx.getStartPC()) && (pc <= catchEx.getEndPC())) {
int type = catchEx.getCatchType();
if (type != 0) {
String catchExName = getConstantPool().getConstantString(type, Constants.CONSTANT_Class);
JavaClass catchException = Repository.lookupClass(catchExName);
if (thrownEx.instanceOf(catchException)) {
return true;
}
}
}
}
}
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
}
return false;
}
private void removeUselessDefiners(String parmSig, final int reg) {
if (parmSig.startsWith("L")) {
parmSig = SignatureUtils.stripSignature(parmSig);
if (Values.DOTTED_JAVA_LANG_OBJECT.equals(parmSig)) {
parameterDefiners.remove(Integer.valueOf(reg));
return;
}
Map<JavaClass, List<MethodInfo>> definers = parameterDefiners.get(Integer.valueOf(reg));
if ((definers != null) && (definers.size() > 0)) {
Iterator<JavaClass> it = definers.keySet().iterator();
while (it.hasNext()) {
JavaClass definer = it.next();
if (!definer.getClassName().equals(parmSig)) {
it.remove();
}
}
if (definers.isEmpty()) {
parameterDefiners.remove(Integer.valueOf(reg));
}
}
}
}
/**
* returns whether this class is used to convert types of some sort, such that you don't want to suggest reducing the class specified to be more generic
*
* @param cls
* the class to check
* @return whether this class is used in conversions
*/
private boolean isaConversionClass(JavaClass cls) {
for (AnnotationEntry entry : cls.getAnnotationEntries()) {
if (CONVERSION_ANNOTATIONS.contains(entry.getAnnotationType())) {
return true;
}
// this ignores the fact that this class might be a grand child, but meh
if (CONVERSION_SUPER_CLASSES.contains(cls.getSuperclassName())) {
return true;
}
}
return false;
}
/**
* an inner helper class that holds basic information about a method
*/
static class MethodInfo {
private final String methodName;
private final String methodSig;
private final String[] methodExceptions;
MethodInfo(String name, String sig, String[] excs) {
methodName = name;
methodSig = sig;
methodExceptions = excs;
}
String getMethodName() {
return methodName;
}
String getMethodSignature() {
return methodSig;
}
String[] getMethodExceptions() {
return methodExceptions;
}
@Override
public int hashCode() {
return methodName.hashCode() ^ methodSig.hashCode();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof MethodInfo)) {
return false;
}
MethodInfo that = (MethodInfo) o;
if (!methodName.equals(that.methodName)) {
return false;
}
if (!methodSig.equals(that.methodSig)) {
return false;
}
return true;
}
@Override
public String toString() {
return ToString.build(this);
}
}
}
|
package eu.visualize.ini.convnet;
import java.awt.Color;
import java.awt.Point;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import com.jogamp.opengl.GL2;
import com.jogamp.opengl.GLAutoDrawable;
import javax.swing.SwingUtilities;
import net.sf.jaer.Description;
import net.sf.jaer.DevelopmentStatus;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.graphics.MultilineAnnotationTextRenderer;
/**
* Extends DavisDeepLearnCnnProcessor to add annotation graphics to show
* steering decision.
*
* @author Tobi
*/
@Description("Displays Visualise steering ConvNet results; subclass of DavisDeepLearnCnnProcessor")
@DevelopmentStatus(DevelopmentStatus.Status.Experimental)
public class VisualiseSteeringConvNet extends DavisDeepLearnCnnProcessor implements PropertyChangeListener {
private boolean hideOutput = getBoolean("hideOutput", false);
private boolean showAnalogDecisionOutput = getBoolean("showAnalogDecisionOutput", false);
private TargetLabeler targetLabeler = null;
private int totalDecisions = 0, correct = 0, incorrect = 0;
public VisualiseSteeringConvNet(AEChip chip) {
super(chip);
setPropertyTooltip("showAnalogDecisionOutput", "shows output units as analog shading");
setPropertyTooltip("hideOutput", "hides output units");
FilterChain chain = new FilterChain(chip);
targetLabeler = new TargetLabeler(chip); // used to validate whether descisions are correct or not
chain.add(targetLabeler);
setEnclosedFilterChain(chain);
apsNet.getSupport().addPropertyChangeListener(DeepLearnCnnNetwork.EVENT_MADE_DECISION, this);
dvsNet.getSupport().addPropertyChangeListener(DeepLearnCnnNetwork.EVENT_MADE_DECISION, this);
}
@Override
public synchronized EventPacket<?> filterPacket(EventPacket<?> in) {
targetLabeler.filterPacket(in);
EventPacket out = super.filterPacket(in);
return out;
}
private Boolean correctDescisionFromTargetLabeler(TargetLabeler targetLabeler, DeepLearnCnnNetwork net) {
if (targetLabeler.getTargetLocation() == null) {
return null; // no location labeled for this time
}
Point p = targetLabeler.getTargetLocation().location;
if (p == null) {
if (net.outputLayer.maxActivatedUnit == 3) {
return true; // no target seen
}
} else {
int x = p.x;
int third = (x * 3) / chip.getSizeX();
if (third == net.outputLayer.maxActivatedUnit) {
return true;
}
}
return false;
}
@Override
public void resetFilter() {
super.resetFilter();
totalDecisions = 0;
correct = 0;
incorrect = 0;
}
@Override
public synchronized void setFilterEnabled(boolean yes) {
super.setFilterEnabled(yes);
if (yes && !targetLabeler.hasLocations()) {
Runnable r = new Runnable() {
@Override
public void run() {
targetLabeler.loadLastLocations();
}
};
SwingUtilities.invokeLater(r);
}
}
@Override
public void annotate(GLAutoDrawable drawable) {
super.annotate(drawable);
targetLabeler.annotate(drawable);
if (hideOutput) {
return;
}
GL2 gl = drawable.getGL().getGL2();
checkBlend(gl);
int third = chip.getSizeX() / 3;
int sy = chip.getSizeY();
if (apsNet != null && apsNet.outputLayer!=null && apsNet.outputLayer.activations != null && isProcessAPSFrames()) {
drawDecisionOutput(third, gl, sy, apsNet, Color.RED);
}
if (dvsNet != null && dvsNet.outputLayer!=null && dvsNet.outputLayer.activations != null && isProcessDVSTimeSlices()) {
drawDecisionOutput(third, gl, sy, dvsNet, Color.YELLOW);
}
if (totalDecisions > 0) {
float errorRate = (float) incorrect / totalDecisions;
String s = String.format("Error rate %.2f%% (total=%d correct=%d incorrect=%d)\n", errorRate * 100, totalDecisions, correct, incorrect);
MultilineAnnotationTextRenderer.renderMultilineString(s);
}
}
private void drawDecisionOutput(int third, GL2 gl, int sy, DeepLearnCnnNetwork net, Color color) {
// 0=left, 1=center, 2=right, 3=no target
int decision = net.outputLayer.maxActivatedUnit;
float r = color.getRed() / 255f, g = color.getGreen() / 255f, b = color.getBlue() / 255f;
float[] cv = color.getColorComponents(null);
if (showAnalogDecisionOutput) {
final float brightness = .3f; // brightness scale
for (int i = 0; i < 3; i++) {
int x0 = third * i;
int x1 = x0 + third;
float shade = brightness * net.outputLayer.activations[i];
gl.glColor3f((shade * r), (shade * g), (shade * b));
gl.glRecti(x0, 0, x1, sy);
gl.glRecti(x0, 0, x1, sy);
}
float shade = brightness * net.outputLayer.activations[3]; // no target
gl.glColor3f((shade * r), (shade * g), (shade * b));
gl.glRecti(0, 0, chip.getSizeX(), sy / 8);
} else if (decision < 3) {
int x0 = third * decision;
int x1 = x0 + third;
float shade = .5f;
gl.glColor3f((shade * r), (shade * g), (shade * b));
gl.glRecti(x0, 0, x1, sy);
}
}
/**
* @return the hideOutput
*/
public boolean isHideOutput() {
return hideOutput;
}
/**
* @param hideOutput the hideOutput to set
*/
public void setHideOutput(boolean hideOutput) {
this.hideOutput = hideOutput;
putBoolean("hideOutput", hideOutput);
}
/**
* @return the showAnalogDecisionOutput
*/
public boolean isShowAnalogDecisionOutput() {
return showAnalogDecisionOutput;
}
/**
* @param showAnalogDecisionOutput the showAnalogDecisionOutput to set
*/
public void setShowAnalogDecisionOutput(boolean showAnalogDecisionOutput) {
this.showAnalogDecisionOutput = showAnalogDecisionOutput;
putBoolean("showAnalogDecisionOutput", showAnalogDecisionOutput);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName() != DeepLearnCnnNetwork.EVENT_MADE_DECISION) {
super.propertyChange(evt);
} else {
DeepLearnCnnNetwork net = (DeepLearnCnnNetwork) evt.getNewValue();
Boolean correctDecision = correctDescisionFromTargetLabeler(targetLabeler, net);
if (correctDecision != null) {
totalDecisions++;
if (correctDecision) {
correct++;
} else {
incorrect++;
}
}
}
}
}
|
package com.mebigfatguy.fbcontrib.detect;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.bcel.Constants;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.AnnotationEntry;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.CodeException;
import org.apache.bcel.classfile.ExceptionTable;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.LocalVariable;
import org.apache.bcel.classfile.LocalVariableTable;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.classfile.ParameterAnnotationEntry;
import org.apache.bcel.generic.Type;
import com.mebigfatguy.fbcontrib.utils.BugType;
import com.mebigfatguy.fbcontrib.utils.OpcodeUtils;
import com.mebigfatguy.fbcontrib.utils.RegisterUtils;
import com.mebigfatguy.fbcontrib.utils.SignatureUtils;
import com.mebigfatguy.fbcontrib.utils.ToString;
import com.mebigfatguy.fbcontrib.utils.UnmodifiableSet;
import com.mebigfatguy.fbcontrib.utils.Values;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
import edu.umd.cs.findbugs.OpcodeStack;
import edu.umd.cs.findbugs.ba.ClassContext;
/**
* looks for parameters that are defined by classes, but only use methods defined by an implemented interface or super class. Relying on concrete classes in
* public signatures causes cohesion, and makes low impact changes more difficult.
*/
public class OverlyConcreteParameter extends BytecodeScanningDetector {
private static final Set<String> CONVERSION_ANNOTATIONS = UnmodifiableSet.create("Ljavax/persistence/Converter;", "Ljavax/ws/rs/Consumes;");
private static final Set<String> CONVERSION_SUPER_CLASSES = UnmodifiableSet.create("com.fasterxml.jackson.databind.JsonSerializer",
"com.fasterxml.jackson.databind.JsonDeserializer");
private final BugReporter bugReporter;
private JavaClass[] constrainingClasses;
private Map<Integer, Map<JavaClass, List<MethodInfo>>> parameterDefiners;
private BitSet usedParameters;
private JavaClass objectClass;
private JavaClass cls;
private OpcodeStack stack;
private int parmCount;
private boolean methodSignatureIsConstrained;
private boolean methodIsStatic;
/**
* constructs a OCP detector given the reporter to report bugs on
*
* @param bugReporter
* the sync of bug reports
*/
public OverlyConcreteParameter(final BugReporter bugReporter) {
this.bugReporter = bugReporter;
try {
objectClass = Repository.lookupClass("java/lang/Object");
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
objectClass = null;
}
}
/**
* implements the visitor to collect classes that constrains this class (super classes/interfaces) and to reset the opcode stack
*
* @param classContext
* the currently parse class
*/
@Override
public void visitClassContext(ClassContext classContext) {
try {
cls = classContext.getJavaClass();
if (!isaConversionClass(cls)) {
JavaClass[] infs = cls.getAllInterfaces();
JavaClass[] sups = cls.getSuperClasses();
constrainingClasses = new JavaClass[infs.length + sups.length];
System.arraycopy(infs, 0, constrainingClasses, 0, infs.length);
System.arraycopy(sups, 0, constrainingClasses, infs.length, sups.length);
parameterDefiners = new HashMap<Integer, Map<JavaClass, List<MethodInfo>>>();
usedParameters = new BitSet();
stack = new OpcodeStack();
super.visitClassContext(classContext);
}
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
} finally {
constrainingClasses = null;
parameterDefiners = null;
usedParameters = null;
stack = null;
}
}
/**
* implements the visitor to look to see if this method is constrained by a superclass or interface.
*
* @param obj
* the currently parsed method
*/
@Override
public void visitMethod(Method obj) {
methodSignatureIsConstrained = false;
String methodName = obj.getName();
if (!Values.CONSTRUCTOR.equals(methodName) && !Values.STATIC_INITIALIZER.equals(methodName)) {
String methodSig = obj.getSignature();
methodSignatureIsConstrained = methodIsSpecial(methodName, methodSig) || methodHasSyntheticTwin(methodName, methodSig);
if (!methodSignatureIsConstrained) {
for (AnnotationEntry entry : obj.getAnnotationEntries()) {
if (CONVERSION_ANNOTATIONS.contains(entry.getAnnotationType())) {
methodSignatureIsConstrained = true;
break;
}
}
}
if (!methodSignatureIsConstrained) {
String parms = methodSig.split("\\(|\\)")[1];
if (parms.indexOf(';') >= 0) {
outer: for (JavaClass cls : constrainingClasses) {
Method[] methods = cls.getMethods();
for (Method m : methods) {
if (methodName.equals(m.getName())) {
if (methodSig.equals(m.getSignature())) {
methodSignatureIsConstrained = true;
break outer;
}
}
}
}
}
}
}
}
/**
* implements the visitor to collect information about the parameters of a this method
*
* @param obj
* the currently parsed code block
*/
@Override
public void visitCode(final Code obj) {
try {
if (methodSignatureIsConstrained) {
return;
}
if (obj.getCode() == null) {
return;
}
Method m = getMethod();
if (m.isSynthetic()) {
return;
}
if (m.getName().startsWith("access$")) {
return;
}
methodIsStatic = m.isStatic();
parmCount = m.getArgumentTypes().length;
if (parmCount == 0) {
return;
}
parameterDefiners.clear();
usedParameters.clear();
stack.resetForMethodEntry(this);
if (buildParameterDefiners()) {
super.visitCode(obj);
reportBugs();
}
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
}
}
/**
* implements the visitor to filter out parameter use where the actual defined type of the method declaration is needed. What remains could be more
* abstractly defined.
*
* @param seen
* the currently parsed opcode
*/
@Override
public void sawOpcode(final int seen) {
if (parameterDefiners.isEmpty()) {
return;
}
try {
stack.precomputation(this);
if ((seen == INVOKEVIRTUAL) || (seen == INVOKESTATIC) || (seen == INVOKESPECIAL) || (seen == INVOKEINTERFACE) || (seen == INVOKEDYNAMIC)) {
String methodSig = getSigConstantOperand();
Type[] parmTypes = Type.getArgumentTypes(methodSig);
int stackDepth = stack.getStackDepth();
if (stackDepth >= parmTypes.length) {
for (int i = 0; i < parmTypes.length; i++) {
OpcodeStack.Item itm = stack.getStackItem(i);
int reg = itm.getRegisterNumber();
removeUselessDefiners(parmTypes[parmTypes.length - i - 1].getSignature(), reg);
}
}
if ((seen != INVOKESPECIAL) && (seen != INVOKESTATIC)) {
if (stackDepth > parmTypes.length) {
OpcodeStack.Item itm = stack.getStackItem(parmTypes.length);
int reg = itm.getRegisterNumber();
int parm = reg;
if (!methodIsStatic) {
parm
}
if ((parm >= 0) && (parm < parmCount)) {
removeUselessDefiners(reg);
}
} else {
parameterDefiners.clear();
}
}
} else if ((seen == ASTORE) || ((seen >= ASTORE_0) && (seen <= ASTORE_3)) || (seen == PUTFIELD) || (seen == GETFIELD) || (seen == PUTSTATIC)
|| (seen == GETSTATIC)) {
// Don't check parameters that are aliased
if (stack.getStackDepth() > 0) {
OpcodeStack.Item itm = stack.getStackItem(0);
int reg = itm.getRegisterNumber();
int parm = reg;
if (!methodIsStatic) {
parm
}
if ((parm >= 0) && (parm < parmCount)) {
parameterDefiners.remove(Integer.valueOf(reg));
}
} else {
parameterDefiners.clear();
}
if ((seen == GETFIELD) || (seen == PUTFIELD)) {
if (stack.getStackDepth() > 1) {
OpcodeStack.Item itm = stack.getStackItem(1);
int reg = itm.getRegisterNumber();
int parm = reg;
if (!methodIsStatic) {
parm
}
if ((parm >= 0) && (parm < parmCount)) {
parameterDefiners.remove(Integer.valueOf(reg));
}
} else {
parameterDefiners.clear();
}
}
} else if (OpcodeUtils.isALoad(seen)) {
int reg = RegisterUtils.getALoadReg(this, seen);
int parm = reg;
if (!methodIsStatic) {
parm
}
if ((parm >= 0) && (parm < parmCount)) {
usedParameters.set(reg);
}
} else if (seen == AASTORE) {
// Don't check parameters that are stored in
if (stack.getStackDepth() >= 3) {
OpcodeStack.Item itm = stack.getStackItem(0);
int reg = itm.getRegisterNumber();
int parm = reg;
if (!methodIsStatic) {
parm
}
if ((parm >= 0) && (parm < parmCount)) {
parameterDefiners.remove(Integer.valueOf(reg));
}
} else {
parameterDefiners.clear();
}
} else if (seen == ARETURN) {
if (stack.getStackDepth() >= 1) {
OpcodeStack.Item item = stack.getStackItem(0);
int reg = item.getRegisterNumber();
int parm = reg;
if (!methodIsStatic) {
parm
}
if ((parm >= 0) && (parm < parmCount)) {
parameterDefiners.remove(Integer.valueOf(reg));
}
} else {
parameterDefiners.clear();
}
}
} finally {
stack.sawOpcode(this, seen);
}
}
/**
* determines whether the method is a baked in special method of the jdk
*
* @param methodName
* the method name to check
* @param methodSig
* the parameter signature of the method to check
* @return if it is a well known baked in method
*/
private static boolean methodIsSpecial(String methodName, String methodSig) {
return ("readObject".equals(methodName) && "(Ljava/io/ObjectInputStream;)V".equals(methodSig));
}
/**
* returns whether this method has an equivalent method that is synthetic, which implies this method is constrained by some Generified interface. We could
* compare parameters but that is a bunch of work that probably doesn't make this test any more precise, so just return true if method name and synthetic is
* found.
*
* @param methodName
* @param methodSig
* @return if a synthetic twin is found
*/
private boolean methodHasSyntheticTwin(String methodName, String methodSig) {
for (Method m : cls.getMethods()) {
if (m.isSynthetic() && m.getName().equals(methodName) && !m.getSignature().equals(methodSig)) {
return true;
}
}
return false;
}
/**
* implements the post processing steps to report the remaining unremoved parameter definers, ie those, that can be defined more abstractly.
*/
private void reportBugs() {
Iterator<Map.Entry<Integer, Map<JavaClass, List<MethodInfo>>>> it = parameterDefiners.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Integer, Map<JavaClass, List<MethodInfo>>> entry = it.next();
Integer reg = entry.getKey();
if (!usedParameters.get(reg.intValue())) {
it.remove();
continue;
}
Map<JavaClass, List<MethodInfo>> definers = entry.getValue();
definers.remove(objectClass);
if (definers.size() > 0) {
String name = "";
LocalVariableTable lvt = getMethod().getLocalVariableTable();
if (lvt != null) {
LocalVariable lv = lvt.getLocalVariable(reg.intValue(), 0);
if (lv != null) {
name = lv.getName();
}
}
int parm = reg.intValue();
if (!methodIsStatic) {
parm
}
parm++; // users expect 1 based parameters
String infName = definers.keySet().iterator().next().getClassName();
bugReporter.reportBug(new BugInstance(this, BugType.OCP_OVERLY_CONCRETE_PARAMETER.name(), NORMAL_PRIORITY).addClass(this).addMethod(this)
.addSourceLine(this, 0).addString(getCardinality(parm) + " parameter '" + name + "' could be declared as " + infName + " instead"));
}
}
}
/**
* returns a string defining what parameter in the signature a certain one is, for the bug report
*
* @param num
* the parameter number
* @return a string describing in english the parameter position
*/
private static String getCardinality(int num) {
if (num == 1) {
return "1st";
}
if (num == 2) {
return "2nd";
}
if (num == 3) {
return "3rd";
}
return num + "th";
}
/**
* builds a map of method information for each method of each interface that each parameter implements of this method
*
* @return a map by parameter id of all the method signatures that interfaces of that parameter implements
*
* @throws ClassNotFoundException
* if the class can't be loaded
*/
private boolean buildParameterDefiners() throws ClassNotFoundException {
Method m = getMethod();
Type[] parms = m.getArgumentTypes();
if (parms.length == 0) {
return false;
}
ParameterAnnotationEntry[] annotations = m.getParameterAnnotationEntries();
boolean hasPossiblyOverlyConcreteParm = false;
for (int i = 0; i < parms.length; i++) {
if ((annotations.length <= i) || (annotations[i] == null) || (annotations[i].getNumAnnotations() == 0)) {
String parm = parms[i].getSignature();
if (parm.startsWith("L")) {
String clsName = SignatureUtils.stripSignature(parm);
if (clsName.startsWith("java.lang.")) {
continue;
}
JavaClass cls = Repository.lookupClass(clsName);
if (cls.isClass() && (!cls.isAbstract())) {
Map<JavaClass, List<MethodInfo>> definers = getClassDefiners(cls);
if (definers.size() > 0) {
parameterDefiners.put(Integer.valueOf(i + (methodIsStatic ? 0 : 1)), definers);
hasPossiblyOverlyConcreteParm = true;
}
}
}
}
}
return hasPossiblyOverlyConcreteParm;
}
/**
* returns a map of method information for each public method for each interface this class implements
*
* @param cls
* the class whose interfaces to record
*
* @return a map of (method name)(method sig) by interface
* @throws ClassNotFoundException
* if unable to load the class
*/
private static Map<JavaClass, List<MethodInfo>> getClassDefiners(final JavaClass cls) throws ClassNotFoundException {
Map<JavaClass, List<MethodInfo>> definers = new HashMap<JavaClass, List<MethodInfo>>();
for (JavaClass ci : cls.getAllInterfaces()) {
if ("java.lang.Comparable".equals(ci.getClassName())) {
continue;
}
List<MethodInfo> methodInfos = getPublicMethodInfos(ci);
if (methodInfos.size() > 0) {
definers.put(ci, methodInfos);
}
}
return definers;
}
/**
* returns a list of method information of all public or protected methods in this class
*
* @param cls
* the class to look for methods
* @return a map of (method name)(method signature)
*/
private static List<MethodInfo> getPublicMethodInfos(final JavaClass cls) {
List<MethodInfo> methodInfos = new ArrayList<MethodInfo>();
Method[] methods = cls.getMethods();
for (Method m : methods) {
if ((m.getAccessFlags() & (Constants.ACC_PUBLIC | Constants.ACC_PROTECTED)) != 0) {
ExceptionTable et = m.getExceptionTable();
methodInfos.add(new MethodInfo(m.getName(), m.getSignature(), et == null ? null : et.getExceptionNames()));
}
}
return methodInfos;
}
/**
* parses through the interface that 'may' define a parameter defined by reg, and look to see if we can rule it out, because a method is called on the
* object that can't be satisfied by the interface, if so remove that candidate interface.
*
* @param reg
* the parameter register number to look at
*/
private void removeUselessDefiners(final int reg) {
Map<JavaClass, List<MethodInfo>> definers = parameterDefiners.get(Integer.valueOf(reg));
if ((definers != null) && (definers.size() > 0)) {
String methodSig = getSigConstantOperand();
String methodName = getNameConstantOperand();
MethodInfo methodInfo = new MethodInfo(methodName, methodSig, null);
Iterator<List<MethodInfo>> it = definers.values().iterator();
while (it.hasNext()) {
boolean methodDefined = false;
List<MethodInfo> methodSigs = it.next();
for (MethodInfo mi : methodSigs) {
if (methodInfo.equals(mi)) {
methodDefined = true;
String[] exceptions = mi.getMethodExceptions();
if (exceptions != null) {
for (String ex : exceptions) {
if (!isExceptionHandled(ex)) {
methodDefined = false;
break;
}
}
}
break;
}
}
if (!methodDefined) {
it.remove();
}
}
if (definers.isEmpty()) {
parameterDefiners.remove(Integer.valueOf(reg));
}
}
}
/**
* returns whether this exception is handled either in a try/catch or throws clause at this pc
*
* @param ex
* the name of the exception
*
* @return whether the exception is handled
*/
private boolean isExceptionHandled(String ex) {
try {
JavaClass thrownEx = Repository.lookupClass(ex);
// First look at the throws clause
ExceptionTable et = getMethod().getExceptionTable();
if (et != null) {
String[] throwClauseExNames = et.getExceptionNames();
for (String throwClauseExName : throwClauseExNames) {
JavaClass throwClauseEx = Repository.lookupClass(throwClauseExName);
if (thrownEx.instanceOf(throwClauseEx)) {
return true;
}
}
}
// Next look at the try catch blocks
CodeException[] catchExs = getCode().getExceptionTable();
if (catchExs != null) {
int pc = getPC();
for (CodeException catchEx : catchExs) {
if ((pc >= catchEx.getStartPC()) && (pc <= catchEx.getEndPC())) {
int type = catchEx.getCatchType();
if (type != 0) {
String catchExName = getConstantPool().getConstantString(type, Constants.CONSTANT_Class);
JavaClass catchException = Repository.lookupClass(catchExName);
if (thrownEx.instanceOf(catchException)) {
return true;
}
}
}
}
}
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
}
return false;
}
private void removeUselessDefiners(String parmSig, final int reg) {
if (parmSig.startsWith("L")) {
parmSig = SignatureUtils.stripSignature(parmSig);
if (Values.DOTTED_JAVA_LANG_OBJECT.equals(parmSig)) {
parameterDefiners.remove(Integer.valueOf(reg));
return;
}
Map<JavaClass, List<MethodInfo>> definers = parameterDefiners.get(Integer.valueOf(reg));
if ((definers != null) && (definers.size() > 0)) {
Iterator<JavaClass> it = definers.keySet().iterator();
while (it.hasNext()) {
JavaClass definer = it.next();
if (!definer.getClassName().equals(parmSig)) {
it.remove();
}
}
if (definers.isEmpty()) {
parameterDefiners.remove(Integer.valueOf(reg));
}
}
}
}
/**
* returns whether this class is used to convert types of some sort, such that you don't want to suggest reducing the class specified to be more generic
*
* @param cls
* the class to check
* @return whether this class is used in conversions
*/
private boolean isaConversionClass(JavaClass cls) {
for (AnnotationEntry entry : cls.getAnnotationEntries()) {
if (CONVERSION_ANNOTATIONS.contains(entry.getAnnotationType())) {
return true;
}
// this ignores the fact that this class might be a grand child, but meh
if (CONVERSION_SUPER_CLASSES.contains(cls.getSuperclassName())) {
return true;
}
}
return false;
}
/**
* an inner helper class that holds basic information about a method
*/
static class MethodInfo {
private final String methodName;
private final String methodSig;
private final String[] methodExceptions;
MethodInfo(String name, String sig, String[] excs) {
methodName = name;
methodSig = sig;
methodExceptions = excs;
}
String getMethodName() {
return methodName;
}
String getMethodSignature() {
return methodSig;
}
String[] getMethodExceptions() {
return methodExceptions;
}
@Override
public int hashCode() {
return methodName.hashCode() ^ methodSig.hashCode();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof MethodInfo)) {
return false;
}
MethodInfo that = (MethodInfo) o;
if (!methodName.equals(that.methodName)) {
return false;
}
if (!methodSig.equals(that.methodSig)) {
return false;
}
return true;
}
@Override
public String toString() {
return ToString.build(this);
}
}
}
|
package eu.ydp.empiria.player.client.module;
public enum ModuleTagName {
DIV("div"), GROUP("group"), SPAN("span"), TEXT_INTERACTION("textInteraction"), IMG("img"),
CHOICE_INTERACTION("choiceInteraction"),
SELECTION_INTERACTION("selectionInteraction"), IDENTYFICATION_INTERACTION("identificationInteraction"),
TEXT_ENTRY_INTERACTION("textEntryInteraction"), INLINE_CHOICE_INTERACTION("inlineChoiceInteraction"),
SIMPLE_TEXT("simpleText"), AUDIO_PLAYER("audioPlayer"), MATH_TEXT("mathText"), MATH_INTERACTION("mathInteraction"),
OBJECT("object"), SLIDESHOW_PLAYER("slideshowPlayer"), PROMPT("prompt"), TABLE("table"),
PAGE_IN_PAGE("pageInPage"), SHAPE("shape"), INFO("info"), REPORT("report"), LINK("link"),
NEXT_ITEM_NAVIGATION("nextItemNavigation"), PREV_ITEM_NAVIGATION("prevItemNavigation"), PAGES_SWITCH_BOX("pagesSwitchBox"),
MARK_ALL_BUTTON("markAllButton"), SHOW_ANSWERS_BUTTON("showAnswersButton"), RESET_BUTTON("resetButton"), SUB("sub"), SUP("sup"), FLASH("flash"),
AUDIO_MUTE_BUTTON("feedbackAudioMuteButton"),MEDIA_PLAY_PAUSE_BUTTON("mediaPlayPauseButton"),MEDIA_STOP_BUTTON("mediaStopButton"),MEDIA_MUTE_BUTTON("mediaMuteButton"),
MEDIA_PROGRESS_BAR("mediaProgressBar"),MEDIA_VOLUME_BAR("mediaVolumeBar"),MEDIA_FULL_SCREEN_BUTTON("mediaFullScreenButton"),
MEDIA_POSITION_IN_STREAM("mediaPositinInStream"),MEDIA_CURRENT_TIME("mediaCurrentTime"),MEDIA_TOTAL_TIME("mediaTotalTime"),
MEDIA_TITLE("mediaTitle"), MEDIA_DESCRIPTION("mediaDescription"), MEDIA_SCREEN("mediaScreen"), SIMULATION_PLAYER("simulationPlayer"), MEDIA_TEXT_TRACK("mediaTextTrack"),
MATH_GAP_TEXT_ENTRY_TYPE("gap_text-entry"), MATH_GAP_INLINE_CHOICE_TYPE("gap_inline-choice"),MATCH_INTERACTION("matchInteraction"),
SOURCE_LIST("sourceList");
String name = null;
private ModuleTagName(String name){
this.name = name;
}
public String tagName(){
return name;
}
public static ModuleTagName getTag(String name){
ModuleTagName returnValue = null;
for(ModuleTagName tag : ModuleTagName.values()){
if(tag.name.equals(name)){
returnValue = tag;
break;
}
}
return returnValue;
}
public static String getTagNameWithType(String tagName, String type) {
String tagNameWithType = "";
if("gap".equals(tagName)){
if("text-entry".equals(type)){
tagNameWithType = MATH_GAP_TEXT_ENTRY_TYPE.toString();
}else if("inline-choice".equals(type)){
tagNameWithType = MATH_GAP_INLINE_CHOICE_TYPE.toString();
}
}
return tagNameWithType;
}
@Override
public String toString() {
return name;
}
}
|
package com.mebigfatguy.fbcontrib.detect;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.bcel.Constants;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
import edu.umd.cs.findbugs.ba.ClassContext;
public class SuspiciousJDKVersionUse extends BytecodeScanningDetector
{
private static final Map<Integer, String> verRegEx = new HashMap<Integer, String>();
static {
verRegEx.put(Integer.valueOf(Constants.MAJOR_1_1), "(jdk|j2?re)1.1");
verRegEx.put(Integer.valueOf(Constants.MAJOR_1_2), "(jdk|j2?re)1.2");
verRegEx.put(Integer.valueOf(Constants.MAJOR_1_3), "(jdk|j2?re)1.3");
verRegEx.put(Integer.valueOf(Constants.MAJOR_1_4), "(jdk|j2?re)1.4");
verRegEx.put(Integer.valueOf(Constants.MAJOR_1_5), "((jdk|j2?re)1.5)|(java-5)");
verRegEx.put(Integer.valueOf(Constants.MAJOR_1_6), "((jdk|j2?re)1.6)|(java-6)");
verRegEx.put(Integer.valueOf(Constants.MAJOR_1_7), "((jdk|j2?re)1.7)|(java-7)");
verRegEx.put(Integer.valueOf(Constants.MAJOR_1_8), "((jdk|j2?re)1.8)|(java-8)");
}
private static final Map<Integer, String> versionStrings = new HashMap<Integer, String>();
static {
versionStrings.put(Integer.valueOf(Constants.MAJOR_1_1), "JDK 1.1");
versionStrings.put(Integer.valueOf(Constants.MAJOR_1_2), "JDK 1.2");
versionStrings.put(Integer.valueOf(Constants.MAJOR_1_3), "JDK 1.3");
versionStrings.put(Integer.valueOf(Constants.MAJOR_1_4), "JDK 1.4");
versionStrings.put(Integer.valueOf(Constants.MAJOR_1_5), "JDK 1.5");
versionStrings.put(Integer.valueOf(Constants.MAJOR_1_6), "JDK 1.6");
versionStrings.put(Integer.valueOf(Constants.MAJOR_1_7), "JDK 1.7");
versionStrings.put(Integer.valueOf(Constants.MAJOR_1_8), "JDK 1.8");
}
|
package com.mebigfatguy.fbcontrib.detect;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.bcel.Constants;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import com.mebigfatguy.fbcontrib.utils.Values;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
import edu.umd.cs.findbugs.ba.ClassContext;
public class SuspiciousJDKVersionUse extends BytecodeScanningDetector
{
private static final Map<Integer, String> VER_REG_EX = new HashMap<Integer, String>();
static {
VER_REG_EX.put(Integer.valueOf(Constants.MAJOR_1_1), "(jdk|j2?re)1.1");
VER_REG_EX.put(Integer.valueOf(Constants.MAJOR_1_2), "(jdk|j2?re)1.2");
VER_REG_EX.put(Integer.valueOf(Constants.MAJOR_1_3), "(jdk|j2?re)1.3");
VER_REG_EX.put(Integer.valueOf(Constants.MAJOR_1_4), "(jdk|j2?re)1.4");
VER_REG_EX.put(Integer.valueOf(Constants.MAJOR_1_5), "((jdk|j2?re)1.5)|(java-5)");
VER_REG_EX.put(Integer.valueOf(Constants.MAJOR_1_6), "((jdk|j2?re)1.6)|(java-6)");
VER_REG_EX.put(Integer.valueOf(Constants.MAJOR_1_7), "((jdk|j2?re)1.7)|(java-7)");
VER_REG_EX.put(Integer.valueOf(Constants.MAJOR_1_8), "((jdk|j2?re)1.8)|(java-8)");
}
private static final Map<Integer, Integer> HUMAN_VERSIONS = new HashMap<Integer, Integer>();
static {
HUMAN_VERSIONS.put(Integer.valueOf(Constants.MAJOR_1_1), Values.ONE);
HUMAN_VERSIONS.put(Integer.valueOf(Constants.MAJOR_1_2), Values.TWO);
HUMAN_VERSIONS.put(Integer.valueOf(Constants.MAJOR_1_3), Values.THREE);
HUMAN_VERSIONS.put(Integer.valueOf(Constants.MAJOR_1_4), Values.FOUR);
HUMAN_VERSIONS.put(Integer.valueOf(Constants.MAJOR_1_5), Values.FIVE);
HUMAN_VERSIONS.put(Integer.valueOf(Constants.MAJOR_1_6), Values.SIX);
HUMAN_VERSIONS.put(Integer.valueOf(Constants.MAJOR_1_7), Values.SEVEN);
HUMAN_VERSIONS.put(Integer.valueOf(Constants.MAJOR_1_8), Values.EIGHT);
}
|
package com.redhat.ceylon.compiler.typechecker.model;
import static com.redhat.ceylon.compiler.typechecker.model.Util.contains;
import static com.redhat.ceylon.compiler.typechecker.model.Util.list;
import java.util.ArrayList;
import java.util.List;
/**
* Represents a named, annotated program element:
* a class, interface, type parameter, parameter,
* method, local, or attribute.
*
* @author Gavin King
*/
public abstract class Declaration extends Element {
String name;
boolean shared;
boolean formal;
boolean actual;
boolean def;
List<Annotation> annotations = new ArrayList<Annotation>();
Scope visibleScope;
Declaration refinedDeclaration = this;
public Scope getVisibleScope() {
return visibleScope;
}
public void setVisibleScope(Scope visibleScope) {
this.visibleScope = visibleScope;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isShared() {
return shared;
}
public void setShared(boolean shared) {
this.shared = shared;
}
public boolean isParameterized() {
return false;
}
public List<Annotation> getAnnotations() {
return annotations;
}
@Override
public String toString() {
return getClass().getSimpleName() +
"[" + getName() + "]";
}
@Override @Deprecated
public List<String> getQualifiedName() {
return list(getContainer().getQualifiedName(), getName());
}
@Override
public String getQualifiedNameString() {
String qualifier = getContainer().getQualifiedNameString();
return qualifier.isEmpty() ? getName() : qualifier + "." + getName();
}
public boolean isActual() {
return actual;
}
public void setActual(boolean actual) {
this.actual = actual;
}
public boolean isFormal() {
return formal;
}
public void setFormal(boolean formal) {
this.formal = formal;
}
public boolean isDefault() {
return def;
}
public void setDefault(boolean def) {
this.def = def;
}
public Declaration getRefinedDeclaration() {
return refinedDeclaration;
}
public void setRefinedDeclaration(Declaration refinedDeclaration) {
this.refinedDeclaration = refinedDeclaration;
}
/**
* Determine if this declaration is visible
* in the given scope, by considering if it
* is shared or directly defined in a
* containing scope.
*/
public boolean isVisible(Scope scope) {
if (getVisibleScope()==null) {
return true;
}
else {
return contains(getVisibleScope(), scope);
}
/*
* Note that this implementation is not quite
* right, since for a shared member
* declaration it does not check if the
* containing declaration is also visible in
* the given scope, but this is okay for now
* because of how this method is used.
*/
/*if (isShared()) {
return true;
}
else {
return isDefinedInScope(scope);
}*/
}
/**
* Determine if this declaration is directly
* defined in a containing scope of the given
* scope.
*/
public boolean isDefinedInScope(Scope scope) {
while (scope!=null) {
if (getContainer()==scope) {
return true;
}
scope = scope.getContainer();
}
return false;
}
public boolean isCaptured() {
return false;
}
public boolean isToplevel() {
return getContainer() instanceof Package;
}
public boolean isClassMember() {
return getContainer() instanceof Class;
}
public boolean isInterfaceMember() {
return getContainer() instanceof Interface;
}
public boolean isClassOrInterfaceMember() {
return getContainer() instanceof ClassOrInterface;
}
public boolean isMember() {
return false;
}
/**
* Get a produced reference for this declaration
* by binding explicit or inferred type arguments
* and type arguments of the type of which this
* declaration is a member, in the case that this
* is a member.
*
* @param outerType the qualifying produced
* type or null if this is not a
* nested type declaration
* @param typeArguments arguments to the type
* parameters of this declaration
*/
public abstract ProducedReference getProducedReference(ProducedType pt,
List<ProducedType> typeArguments);
@Override
public boolean equals(Object object) {
if (object instanceof Declaration) {
Declaration that = (Declaration) object;
return this==that || getName()!=null && that.getName()!=null &&
that.getName().equals(getName()) &&
that.getDeclarationKind()==getDeclarationKind() &&
(getContainer()==null && that.getContainer()==null ||
that.getContainer().equals(getContainer()));
}
else {
return false;
}
}
@Override
public int hashCode() {
return getName()==null ? 0 : getName().hashCode();
}
/**
* Does this declaration refine the given declaration?
*/
public boolean refines(Declaration other) {
if (equals(other)) {
return true;
}
else {
if (isClassOrInterfaceMember()) {
ClassOrInterface type = (ClassOrInterface) getContainer();
return other.getName()!=null && getName()!=null &&
other.getName().equals(getName()) &&
other.getDeclarationKind()==getDeclarationKind() &&
type.isMember(other);
}
else {
return false;
}
}
}
public abstract DeclarationKind getDeclarationKind();
}
|
package com.vinsol.sms_scheduler.activities;
import java.security.KeyStore.LoadStoreParameter;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnGroupCollapseListener;
import android.widget.ExpandableListView.OnGroupExpandListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import com.vinsol.sms_scheduler.Constants;
import com.vinsol.sms_scheduler.DBAdapter;
import com.vinsol.sms_scheduler.R;
import com.vinsol.sms_scheduler.models.GroupStructure;
import com.vinsol.sms_scheduler.models.MyContact;
import com.vinsol.sms_scheduler.models.SpannedEntity;
public class ContactsTabsActivity extends Activity {
TabHost tabHost;
TabHost mtabHost;
DBAdapter mdba = new DBAdapter(this);
Cursor cur;
LinearLayout listLayout;
LinearLayout blankLayout;
LinearLayout parentLayout;
Button blankListAddButton;
ListView nativeContactsList;
Button doneButton;
Button cancelButton;
ContactsAdapter contactsAdapter;
String origin;
ArrayList<MyContact> selectedIds = new ArrayList<MyContact>();
ArrayList<SpannedEntity> SpansTemp = new ArrayList<SpannedEntity>();
ArrayList<String> idsString = new ArrayList<String>();
ArrayList<Long> ids = new ArrayList<Long>();
ExpandableListView nativeGroupExplList;
ExpandableListView privateGroupExplList;
ArrayList<ArrayList<HashMap<String, Object>>> nativeChildDataTemp = new ArrayList<ArrayList<HashMap<String, Object>>>();
ArrayList<HashMap<String, Object>> nativeGroupDataTemp = new ArrayList<HashMap<String, Object>>();
ArrayList<ArrayList<HashMap<String, Object>>> privateChildDataTemp = new ArrayList<ArrayList<HashMap<String, Object>>>();
ArrayList<HashMap<String, Object>> privateGroupDataTemp = new ArrayList<HashMap<String, Object>>();
SimpleExpandableListAdapter nativeGroupAdapter;
SimpleExpandableListAdapter privateGroupAdapter;
ArrayList<Long> recentIds = new ArrayList<Long>();
ArrayList<Long> recentContactIds = new ArrayList<Long>();
ArrayList<String> recentContactNumbers = new ArrayList<String>();
ListView recentsList;
RecentsAdapter recentsAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contacts_tabs_layout);
TabHost tabHost=(TabHost)findViewById(R.id.tabHost);
tabHost.setup();
TabSpec spec1=tabHost.newTabSpec("Tab 1");
spec1.setContent(R.id.contacts_tabs_native_contacts_list);
spec1.setIndicator("Contacts", getResources().getDrawable(R.drawable.contacts_tab_states));
TabSpec spec2=tabHost.newTabSpec("Tab 2");
spec2.setIndicator("Groups", getResources().getDrawable(R.drawable.groups_tab_states));
spec2.setContent(R.id.group_tabs);
TabSpec spec3=tabHost.newTabSpec("Tab 3");
spec3.setIndicator("Recents", getResources().getDrawable(R.drawable.recent_tab_states));
spec3.setContent(R.id.contacts_tabs_recents_list);
tabHost.addTab(spec1);
tabHost.addTab(spec2);
tabHost.addTab(spec3);
Intent intent = getIntent();
origin = intent.getStringExtra("ORIGIN");
if(origin.equals("new")){
for(int i = 0; i < NewScheduleActivity.Spans.size(); i++){
SpansTemp.add(NewScheduleActivity.Spans.get(i));
}
for(int groupCount = 0; groupCount< NewScheduleActivity.nativeGroupData.size(); groupCount++){
HashMap<String, Object> group = new HashMap<String, Object>();
group.put(Constants.GROUP_ID, NewScheduleActivity.nativeGroupData.get(groupCount).get(Constants.GROUP_ID));
group.put(Constants.GROUP_NAME, NewScheduleActivity.nativeGroupData.get(groupCount).get(Constants.GROUP_NAME));
group.put(Constants.GROUP_IMAGE, NewScheduleActivity.nativeGroupData.get(groupCount).get(Constants.GROUP_IMAGE));
group.put(Constants.GROUP_TYPE, NewScheduleActivity.nativeGroupData.get(groupCount).get(Constants.GROUP_TYPE));
group.put(Constants.GROUP_CHECK, NewScheduleActivity.nativeGroupData.get(groupCount).get(Constants.GROUP_CHECK));
nativeGroupDataTemp.add(group);
ArrayList<HashMap<String, Object>> child = new ArrayList<HashMap<String, Object>>();
for(int childCount = 0; childCount< NewScheduleActivity.nativeChildData.get(groupCount).size(); childCount++){
HashMap<String, Object> childParams = new HashMap<String, Object>();
childParams.put(Constants.CHILD_CONTACT_ID, NewScheduleActivity.nativeChildData.get(groupCount).get(childCount).get(Constants.CHILD_CONTACT_ID));
childParams.put(Constants.CHILD_NAME, NewScheduleActivity.nativeChildData.get(groupCount).get(childCount).get(Constants.CHILD_NAME));
childParams.put(Constants.CHILD_NUMBER, NewScheduleActivity.nativeChildData.get(groupCount).get(childCount).get(Constants.CHILD_NUMBER));
childParams.put(Constants.CHILD_IMAGE, NewScheduleActivity.nativeChildData.get(groupCount).get(childCount).get(Constants.CHILD_IMAGE));
childParams.put(Constants.CHILD_CHECK, NewScheduleActivity.nativeChildData.get(groupCount).get(childCount).get(Constants.CHILD_CHECK));
child.add(childParams);
}
nativeChildDataTemp.add(child);
}
for(int groupCount = 0; groupCount< NewScheduleActivity.privateGroupData.size(); groupCount++){
HashMap<String, Object> group = new HashMap<String, Object>();
group.put(Constants.GROUP_ID, NewScheduleActivity.privateGroupData.get(groupCount).get(Constants.GROUP_ID));
group.put(Constants.GROUP_NAME, NewScheduleActivity.privateGroupData.get(groupCount).get(Constants.GROUP_NAME));
group.put(Constants.GROUP_IMAGE, NewScheduleActivity.privateGroupData.get(groupCount).get(Constants.GROUP_IMAGE));
group.put(Constants.GROUP_TYPE, NewScheduleActivity.privateGroupData.get(groupCount).get(Constants.GROUP_TYPE));
group.put(Constants.GROUP_CHECK, NewScheduleActivity.privateGroupData.get(groupCount).get(Constants.GROUP_CHECK));
privateGroupDataTemp.add(group);
ArrayList<HashMap<String, Object>> child = new ArrayList<HashMap<String, Object>>();
for(int childCount = 0; childCount< NewScheduleActivity.privateChildData.get(groupCount).size(); childCount++){
HashMap<String, Object> childParams = new HashMap<String, Object>();
childParams.put(Constants.CHILD_CONTACT_ID, NewScheduleActivity.privateChildData.get(groupCount).get(childCount).get(Constants.CHILD_CONTACT_ID));
childParams.put(Constants.CHILD_NAME, NewScheduleActivity.privateChildData.get(groupCount).get(childCount).get(Constants.CHILD_NAME));
childParams.put(Constants.CHILD_NUMBER, NewScheduleActivity.privateChildData.get(groupCount).get(childCount).get(Constants.CHILD_NUMBER));
childParams.put(Constants.CHILD_IMAGE, NewScheduleActivity.privateChildData.get(groupCount).get(childCount).get(Constants.CHILD_IMAGE));
childParams.put(Constants.CHILD_CHECK, NewScheduleActivity.privateChildData.get(groupCount).get(childCount).get(Constants.CHILD_CHECK));
child.add(childParams);
}
privateChildDataTemp.add(child);
}
}else if(origin.equals("edit")){
for(int i = 0; i < EditScheduledSmsActivity.Spans.size(); i++){
SpansTemp.add(EditScheduledSmsActivity.Spans.get(i));
}
Log.i("MSG", EditScheduledSmsActivity.nativeGroupData.size()+"group data size from edit activity");
for(int groupCount = 0; groupCount< EditScheduledSmsActivity.nativeGroupData.size(); groupCount++){
HashMap<String, Object> group = new HashMap<String, Object>();
group.put(Constants.GROUP_ID, EditScheduledSmsActivity.nativeGroupData.get(groupCount).get(Constants.GROUP_ID));
group.put(Constants.GROUP_NAME, EditScheduledSmsActivity.nativeGroupData.get(groupCount).get(Constants.GROUP_NAME));
group.put(Constants.GROUP_IMAGE, EditScheduledSmsActivity.nativeGroupData.get(groupCount).get(Constants.GROUP_IMAGE));
group.put(Constants.GROUP_TYPE, EditScheduledSmsActivity.nativeGroupData.get(groupCount).get(Constants.GROUP_TYPE));
group.put(Constants.GROUP_CHECK, EditScheduledSmsActivity.nativeGroupData.get(groupCount).get(Constants.GROUP_CHECK));
nativeGroupDataTemp.add(group);
ArrayList<HashMap<String, Object>> child = new ArrayList<HashMap<String, Object>>();
Log.i("MSG", EditScheduledSmsActivity.nativeChildData.get(groupCount).size()+"child data size from edit activity");
for(int childCount = 0; childCount < EditScheduledSmsActivity.nativeChildData.get(groupCount).size(); childCount++){
HashMap<String, Object> childParams = new HashMap<String, Object>();
childParams.put(Constants.CHILD_CONTACT_ID, EditScheduledSmsActivity.nativeChildData.get(groupCount).get(childCount).get(Constants.CHILD_CONTACT_ID));
childParams.put(Constants.CHILD_NAME, EditScheduledSmsActivity.nativeChildData.get(groupCount).get(childCount).get(Constants.CHILD_NAME));
childParams.put(Constants.CHILD_NUMBER, EditScheduledSmsActivity.nativeChildData.get(groupCount).get(childCount).get(Constants.CHILD_NUMBER));
childParams.put(Constants.CHILD_IMAGE, EditScheduledSmsActivity.nativeChildData.get(groupCount).get(childCount).get(Constants.CHILD_IMAGE));
childParams.put(Constants.CHILD_CHECK, EditScheduledSmsActivity.nativeChildData.get(groupCount).get(childCount).get(Constants.CHILD_CHECK));
child.add(childParams);
}
nativeChildDataTemp.add(child);
}
for(int i = 0; i < EditScheduledSmsActivity.Spans.size(); i++){
SpansTemp.add(EditScheduledSmsActivity.Spans.get(i));
}
Log.i("MSG", EditScheduledSmsActivity.privateGroupData.size()+"group data size from edit activity");
for(int groupCount = 0; groupCount< EditScheduledSmsActivity.privateGroupData.size(); groupCount++){
HashMap<String, Object> group = new HashMap<String, Object>();
group.put(Constants.GROUP_ID, EditScheduledSmsActivity.privateGroupData.get(groupCount).get(Constants.GROUP_ID));
group.put(Constants.GROUP_NAME, EditScheduledSmsActivity.privateGroupData.get(groupCount).get(Constants.GROUP_NAME));
group.put(Constants.GROUP_IMAGE, EditScheduledSmsActivity.privateGroupData.get(groupCount).get(Constants.GROUP_IMAGE));
group.put(Constants.GROUP_TYPE, EditScheduledSmsActivity.privateGroupData.get(groupCount).get(Constants.GROUP_TYPE));
group.put(Constants.GROUP_CHECK, EditScheduledSmsActivity.privateGroupData.get(groupCount).get(Constants.GROUP_CHECK));
privateGroupDataTemp.add(group);
ArrayList<HashMap<String, Object>> child = new ArrayList<HashMap<String, Object>>();
Log.i("MSG", EditScheduledSmsActivity.privateChildData.get(groupCount).size()+"child data size from edit activity");
for(int childCount = 0; childCount < EditScheduledSmsActivity.privateChildData.get(groupCount).size(); childCount++){
HashMap<String, Object> childParams = new HashMap<String, Object>();
childParams.put(Constants.CHILD_CONTACT_ID, EditScheduledSmsActivity.privateChildData.get(groupCount).get(childCount).get(Constants.CHILD_CONTACT_ID));
childParams.put(Constants.CHILD_NAME, EditScheduledSmsActivity.privateChildData.get(groupCount).get(childCount).get(Constants.CHILD_NAME));
childParams.put(Constants.CHILD_NUMBER, EditScheduledSmsActivity.privateChildData.get(groupCount).get(childCount).get(Constants.CHILD_NUMBER));
childParams.put(Constants.CHILD_IMAGE, EditScheduledSmsActivity.privateChildData.get(groupCount).get(childCount).get(Constants.CHILD_IMAGE));
childParams.put(Constants.CHILD_CHECK, EditScheduledSmsActivity.privateChildData.get(groupCount).get(childCount).get(Constants.CHILD_CHECK));
child.add(childParams);
}
privateChildDataTemp.add(child);
}
}
doneButton = (Button) findViewById(R.id.contacts_tab_done_button);
cancelButton = (Button) findViewById(R.id.contacts_tab_cancel_button);
doneButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
for(int i = 0; i< ids.size(); i++){
idsString.add(String.valueOf(ids.get(i)));
}
intent.putExtra("IDSARRAY", idsString);
if(origin.equals("new")){
NewScheduleActivity.nativeGroupData.clear();
NewScheduleActivity.nativeChildData.clear();
NewScheduleActivity.nativeGroupData = nativeGroupDataTemp;
NewScheduleActivity.nativeChildData = nativeChildDataTemp;
NewScheduleActivity.privateGroupData.clear();
NewScheduleActivity.privateChildData.clear();
NewScheduleActivity.privateGroupData = privateGroupDataTemp;
NewScheduleActivity.privateChildData = privateChildDataTemp;
NewScheduleActivity.Spans.clear();
for(int i = 0; i< SpansTemp.size(); i++){
NewScheduleActivity.Spans.add(SpansTemp.get(i));
}
}else if(origin.equals("edit")){
EditScheduledSmsActivity.nativeGroupData.clear();
EditScheduledSmsActivity.nativeChildData.clear();
EditScheduledSmsActivity.nativeGroupData = nativeGroupDataTemp;
EditScheduledSmsActivity.nativeChildData = nativeChildDataTemp;
EditScheduledSmsActivity.privateGroupData.clear();
EditScheduledSmsActivity.privateChildData.clear();
EditScheduledSmsActivity.privateGroupData = privateGroupDataTemp;
EditScheduledSmsActivity.privateChildData = privateChildDataTemp;
EditScheduledSmsActivity.Spans.clear();
for(int i = 0; i< SpansTemp.size(); i++){
EditScheduledSmsActivity.Spans.add(SpansTemp.get(i));
}
}
setResult(2, intent);
ContactsTabsActivity.this.finish();
}
});
cancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("IDSARRAY", idsString);
setResult(2, intent);
ContactsTabsActivity.this.finish();
}
});
nativeContactsList = (ListView) findViewById(R.id.contacts_tabs_native_contacts_list);
contactsAdapter = new ContactsAdapter();
nativeContactsList.setAdapter(contactsAdapter);
parentLayout = (LinearLayout) findViewById(R.id.private_list_parent_layout);
listLayout = (LinearLayout) findViewById(R.id.list_layout);
blankLayout = (LinearLayout) findViewById(R.id.blank_layout);
blankListAddButton = (Button) findViewById(R.id.blank_list_add_button);
blankListAddButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(ContactsTabsActivity.this, GroupEditActivity.class);
intent.putExtra("STATE", "new");
startActivity(intent);
}
});
mdba.open();
cur = mdba.fetchAllGroups();
if(cur.getCount()==0){
listLayout.setVisibility(LinearLayout.GONE);
blankLayout.setVisibility(LinearLayout.VISIBLE);
}else{
listLayout.setVisibility(LinearLayout.VISIBLE);
blankLayout.setVisibility(LinearLayout.GONE);
}
mdba.close();
LinearLayout groupTabs = (LinearLayout)findViewById( R.id.group_tabs );
mtabHost = (TabHost)groupTabs.findViewById( android.R.id.tabhost );
mtabHost.setup( );
mtabHost.getTabWidget().setDividerDrawable(R.drawable.vertical_seprator);
setupTab(new TextView(this), "Native");
setupTab(new TextView(this), "Private");
privateGroupExplList = (ExpandableListView) findViewById(R.id.private_list);
nativeGroupExplList = (ExpandableListView) groupTabs.findViewById(R.id.native_list);
nativeGroupsAdapterSetup();
privateGroupsAdapterSetup();
nativeGroupExplList.setAdapter(nativeGroupAdapter);
nativeGroupExplList.setOnGroupExpandListener(new OnGroupExpandListener() {
@Override
public void onGroupExpand(int groupPosition) {
}
});
nativeGroupExplList.setOnGroupCollapseListener(new OnGroupCollapseListener() {
@Override
public void onGroupCollapse(int groupPosition) {
}
});
privateGroupExplList.setAdapter(privateGroupAdapter);
privateGroupExplList.setOnGroupExpandListener(new OnGroupExpandListener() {
@Override
public void onGroupExpand(int groupPosition) {
}
});
privateGroupExplList.setOnGroupCollapseListener(new OnGroupCollapseListener() {
@Override
public void onGroupCollapse(int groupPosition) {
}
});
recentIds.clear();
recentContactIds.clear();
recentContactNumbers.clear();
recentsList = (ListView) findViewById(R.id.contacts_tabs_recents_list);
mdba.open();
Cursor cur = mdba.fetchAllRecents();
if(cur.moveToFirst()){
do{
recentIds.add(cur.getLong(cur.getColumnIndex(DBAdapter.KEY_RECENT_CONTACT_ID)));
recentContactIds.add(cur.getLong(cur.getColumnIndex(DBAdapter.KEY_RECENT_CONTACT_CONTACT_ID)));
recentContactNumbers.add(cur.getString(cur.getColumnIndex(DBAdapter.KEY_RECENT_CONTACT_NUMBER)));
}while(cur.moveToNext());
}
recentsAdapter = new RecentsAdapter();
recentsList.setAdapter(recentsAdapter);
mdba.close();
}
private void setupTab(final View view, final String tag) {
View tabview = createTabView(mtabHost.getContext(), tag);
TabSpec setContent = null;
if(tag.equals("Native")){
setContent = mtabHost.newTabSpec(tag).setIndicator(tabview).setContent(R.id.native_list);
}else if(tag.equals("Private")){
setContent = mtabHost.newTabSpec(tag).setIndicator(tabview).setContent(R.id.private_list_parent_layout);
}
mtabHost.addTab(setContent);
}
private static View createTabView(final Context context, final String text) {
View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
TextView tv = (TextView) view.findViewById(R.id.tabsText);
tv.setText(text);
return view;
}
@Override
protected void onResume() {
super.onResume();
mdba.open();
cur = mdba.fetchAllGroups();
if(cur.getCount()==0){
listLayout.setVisibility(LinearLayout.GONE);
blankLayout.setVisibility(LinearLayout.VISIBLE);
}else{
listLayout.setVisibility(LinearLayout.VISIBLE);
blankLayout.setVisibility(LinearLayout.GONE);
}
mdba.close();
reloadPrivateGroupData();
privateGroupAdapter.notifyDataSetChanged();
}
@Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent();
intent.putExtra("IDSARRAY", idsString);
setResult(2, intent);
ContactsTabsActivity.this.finish();
}
|
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Stack;
public class Graph {
class EdgeNode {
int index;
int weight;
EdgeNode next;
int degree;
}
EdgeNode[] edges;
static int max = 7;
int nedges;
boolean directed;
public Graph(boolean directed) {
edges = new EdgeNode[max];
nedges = 0;
this.directed = directed;
insertEdge(1, 2, false);
insertEdge(1, 5, false);
insertEdge(1, 6, false);
insertEdge(2, 5, false);
insertEdge(5, 4, false);
insertEdge(2, 3, false);
insertEdge(4, 3, false);
}
public void insertEdge(int xIndex, int yIndex, boolean directed) {
if (edges[xIndex] == null) {
EdgeNode node = new EdgeNode();
node.index = xIndex;
edges[xIndex] = node;
}
EdgeNode node = (EdgeNode)edges[xIndex];
node.degree++;
while (node.next != null) {
node = node.next;
}
EdgeNode nextNode = new EdgeNode();
nextNode.index = yIndex;
node.next = nextNode;
if (directed) {
nedges++;
} else {
insertEdge(yIndex, xIndex, true);
}
}
public void printGraph() {
for (int i = 0; i < max; i++) {
System.out.println();
EdgeNode node = edges[i];
if (node == null) {
continue;
}
System.out.print(node.index + ":");
while (node.next != null) {
node = node.next;
System.out.print(node.index + ",");
}
}
}
public void bfs(int start) {
Queue<Integer> queue = new LinkedList<Integer>();
boolean[] visited = new boolean[max];
boolean[] processed = new boolean[max];
System.out.println();
System.out.println("
queue.add(start);
System.out.print(edges[start].index + ",");
visited[start] = true;
while (!queue.isEmpty()) {
int index = queue.poll();
if (processed[index]) {
continue;
}
EdgeNode node = edges[index];
node = node.next;
while (node != null) {
if (!visited[node.index]) {
System.out.print(node.index + ",");
queue.add(node.index);
visited[node.index] = true;
}
node = node.next;
}
processed[index] = true;
}
}
static boolean[] dfs_discovered = new boolean[max];
static boolean[] dfs_processed = new boolean[max];
public void dfs(int start) {
EdgeNode node = edges[start];
if (!dfs_discovered[start]) {
System.out.print(node.index + ",");
dfs_discovered[start] = true;
EdgeNode next = node.next;
while (next != null) {
dfs(next.index);
next = next.next;
}
}
}
public static void main(String[] args) {
Graph graph = new Graph(false);
graph.printGraph();
graph.bfs(1);
System.out.println();
System.out.println("
graph.dfs(1);
}
}
|
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class Graph{
Node mainNode;
int[][] adjacency;//TODO: possibly change this to boolean[][] to save space?
ArrayList<Node> V= new ArrayList<Node>();
public Graph(){
}
public Graph(Node node){
mainNode= node;
}
public Graph(String name) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("Graphs/"+name+".txt"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append('\n');
line = br.readLine();
}
br.close();
String matrixStr = sb.toString();
int n= (matrixStr.indexOf("\n")+1)/2; //Number of nodes in the graph.
int[][] matrix= new int[n][n];
for (int i= 0; i < n; i++){
for (int j= 0; j < 2*n-1; j=j+2){
matrix[i][j/2]= Integer.parseInt(matrixStr.substring(i*(2*n-1+1)+j,i*(2*n-1+1)+j+1));
}
}
traverseMatrix(matrix);
}
public Graph(int n) throws IOException {
Random random= new Random();
//Make a random undirected (i.e. symmetric matrix) graph's adjacency matrix.
int[][] matrix= new int[n][n];
for (int i= 0; i < n; i++){
for (int j= i; j < n; j++){
if (i == j){
matrix[i][j]= 0;
}
else{
matrix[i][j]= random.nextInt(2);
matrix[j][i]= matrix[i][j];
}
}
}
//TODO: matrix might not be connected,yet.
//I think the probability of a graph being disconnected is (1/2)^n. For example, if n=5, then p=3%.
traverseMatrix(matrix);
}
public void traverseMatrix(int[][] matrix) throws IOException{
ArrayList<Node> nodes= new ArrayList<Node>();
for (int i= 0; i < matrix.length; i++){
nodes.add(new Node(String.valueOf(i)));
}
for (int i= 0; i < matrix.length; i++){
for (int j= 0; j < matrix.length; j++){
if (matrix[i][j] == 1){
nodes.get(i).addChild(nodes.get(j));
}
}
}
mainNode= nodes.get(0);
this.adjacency= matrix;
}
public void traverse(Node node){
//Breadth First Search to make a list of all nodes in the graph.
if (node.index != null){
return; //Already traversed.
}
int index= 0;
Queue queue= new Queue();
node.index= 0;
V.add(node);
index++;
queue.enqueue(node);
while (!queue.isEmpty()){
Node r= queue.dequeue();
for (int i= 0; i < r.children.size(); i++){
Node s= (Node)r.children.get(i);
if (V.indexOf(s) < 0){
s.index= index;
V.add(s);
index++;
queue.enqueue(s);
}
}
}
}
public static Tree BFS(Node node){
//Breadth First Search to make a spanning tree of a graph rooted at 'node'.
Queue queue= new Queue();
Queue treeQueue= new Queue();
ArrayList<Node> tempV= new ArrayList<Node>();
tempV.add(node);
queue.enqueue(node);
Node root= new Node(node.data, node.index);
treeQueue.enqueue(root);
while (!queue.isEmpty()){
Node r= queue.dequeue();
Node t= treeQueue.dequeue();
for (int i= 0; i < r.children.size(); i++){
Node s= (Node)r.children.get(i);
if (tempV.indexOf(s) < 0){
tempV.add(s);
Node child= new Node(s.data, s.index);
t.children.add(child);
queue.enqueue(s);
treeQueue.enqueue(child);
}
}
}
return (new Tree(root));
}
public static boolean areIsomorphic(Graph G1, Graph G2){
//Some initializations...
G1.traverse(G1.mainNode);
G2.traverse(G2.mainNode);
if (G1.V.size() != G2.V.size()) return false;
ArrayList<Tree> trees1= new ArrayList<Tree>();
for (int i= 0; i < G1.V.size(); i++){
trees1.add(G1.BFS(G1.V.get(i)));
}
ArrayList<Tree> trees2= new ArrayList<Tree>();
for (int i= 0; i < G2.V.size(); i++){
trees2.add(G2.BFS(G2.V.get(i)));
}
ArrayList<ArrayList<ArrayList<Node>>> tables1= new ArrayList<ArrayList<ArrayList<Node>>>();
for (int i= 0; i < G1.V.size(); i++){
tables1.add(trees1.get(i).makeTable());
}
ArrayList<ArrayList<ArrayList<Node>>> tables2= new ArrayList<ArrayList<ArrayList<Node>>>();
for (int i= 0; i < G2.V.size(); i++){
tables2.add(trees2.get(i).makeTable());
}
ArrayList<Map<Node, Node>> map= new ArrayList<Map<Node, Node>>();
int[] matched= new int[G2.V.size()];
for (int i= 0; i < G1.V.size(); i++){
int mapSize= map.size();
for (int j= 0; j < G2.V.size(); j++){
if (matched[j] != 1){
boolean match= true;
if (tables1.get(G1.V.get(i).index).size() != tables2.get(G2.V.get(j).index).size()){
//Distance to the farthest node must be the same in both spanning trees.
match= false;
}
else{
//Check that the number of nodes at each distance away is the same in both spanning trees.
for (int k= 0; k < tables1.get(G1.V.get(i).index).size(); k++){
if (tables1.get(G1.V.get(i).index).get(k).size() != tables2.get(G2.V.get(j).index).get(k).size()){
match= false;
break;
}
}
if (match == true){
//if match== true, we need to check the all the mappings up to this point hold true.
//by calculating distances between nodes or something.
for (int k= 0; k < map.size(); k++){
Set<Node> set= map.get(k).keySet();
Node node= set.iterator().next();
int nodeLevel= 0;
int mNodeLevel= 0;
//Search current spanning tables...
ArrayList<ArrayList<Node>> table1= tables1.get(G1.V.get(i).index);
ArrayList<ArrayList<Node>> table2= tables2.get(G2.V.get(j).index);
for (int l= 0; l < table1.size(); l++){
for (int m= 0; m < table1.get(l).size(); m++){
if (table1.get(l).get(m).index == node.index){ //We are comparing graph nodes with tree nodes.
nodeLevel= l;
break;
}
}
}
for (int l= 0; l < table2.size(); l++){
for (int m= 0; m < table2.get(l).size(); m++){
if (table2.get(l).get(m).index == map.get(k).get(node).index){
mNodeLevel= l;
break;
}
}
}
if (nodeLevel != mNodeLevel){
//System.out.println("Map mistmatch.");
match= false;
break;
}
}
}
}
if (match == true){
Map<Node, Node> newMap= new HashMap<Node, Node>();
newMap.put(G1.V.get(i), G2.V.get(j));
map.add(newMap);
matched[j]= 1;
break;//Break at first possible match <- this may not be right.
}
}
}
if (map.size() == mapSize){
//If this is the case, all we know for sure is that the last key-value pair is not correct
// for the proposed isomorphism.
System.out.println("Couldn't find a match for a node. Current map size is " + map.size());
return false; //Couldn't find a match for a node.
}
}
Map<Node, Node> mapmap= new HashMap<Node, Node>();
for (int i= 0; i < map.size(); i++){
mapmap.putAll(map.get(i));
}
if (checkMap(G1, G2, mapmap)){
return true;
}
else{
System.out.println("There was an error...");
return false;
}
}
public static boolean checkMap(Graph G1, Graph G2, Map map){
if (map.size() != G1.V.size() || map.size() != G2.V.size()){
return false;
}
//TODO: we may need to check that every point in the domain of 'map' is unique, but may need not since 'map' is a map.
//The following nested for-loop checks the forward direction of edge preservation,
//i.e., each edge in G1 is also found in G2.
if (missingEdge(G1, map)){
return false; //No edge connecting 'node' and 'child' exists in the second Graph.
}
//We need to check the edge preservation in the backward direction: we need to construct an inverse map.
Map<Node, Node> inverseMap= new HashMap<Node, Node>();
Set<Node> set= map.keySet();
for (Node node : set){
inverseMap.put((Node)map.get(node), node);
}
if (missingEdge(G2, inverseMap)){
return false; //Missing edge when using the inverse map.
}
return true;
}
private static boolean missingEdge(Graph G1, Map map) {
for (int i= 0; i < G1.V.size(); i++){
Node node= G1.V.get(i);
for (int j= 0; j < G1.V.get(i).children.size(); j++){
Node child= (Node)node.children.get(j);
//There exists an edge between 'node' and 'child.'
Node mNode= (Node)map.get(node);
Node mChild= (Node)map.get(child);
if (mNode.children.indexOf(mChild) < 0){
return true;
}
}
}
return false;
}
}
|
package gov.nih.nci.calab.service.util;
import gov.nih.nci.calab.domain.nano.characterization.Characterization;
import java.util.HashMap;
import java.util.Map;
public class CaNanoLabConstants {
public static final String DOMAIN_MODEL_NAME = "caNanoLab";
public static final String CSM_APP_NAME = "caNanoLab";
public static final String DATE_FORMAT = "MM/dd/yyyy";
public static final String ACCEPT_DATE_FORMAT = "MM/dd/yy";
// Storage element
public static final String STORAGE_BOX = "Box";
public static final String STORAGE_SHELF = "Shelf";
public static final String STORAGE_RACK = "Rack";
public static final String STORAGE_FREEZER = "Freezer";
public static final String STORAGE_ROOM = "Room";
public static final String STORAGE_LAB = "Lab";
// DataStatus
public static final String MASK_STATUS = "Masked";
public static final String ACTIVE_STATUS = "Active";
// for Container type
public static final String OTHER = "Other";
public static final String[] DEFAULT_CONTAINER_TYPES = new String[] {
"Tube", "Vial" };
// Sample Container type
public static final String ALIQUOT = "Aliquot";
public static final String SAMPLE_CONTAINER = "Sample_container";
// Run Name
public static final String RUN = "Run";
// File upload
public static final String FILEUPLOAD_PROPERTY = "fileupload.properties";
public static final String UNCOMPRESSED_FILE_DIRECTORY = "decompressedFiles";
public static final String EMPTY = "N/A";
// File input/output type
public static final String INPUT = "Input";
public static final String OUTPUT = "Output";
// zip file name
public static final String ALL_FILES = "ALL_FILES";
public static final String URI_SEPERATOR = "/";
// caNanoLab property file
public static final String CANANOLAB_PROPERTY = "caNanoLab.properties";
// caLAB Submission property file
public static final String SUBMISSION_PROPERTY = "exception.properties";
public static final String BOOLEAN_YES = "Yes";
public static final String BOOLEAN_NO = "No";
public static final String[] BOOLEAN_CHOICES = new String[] { BOOLEAN_YES,
BOOLEAN_NO };
public static final String DEFAULT_SAMPLE_PREFIX = "NANO-";
public static final String DEFAULT_APP_OWNER = "NCICB";
public static final String APP_OWNER;
static {
String appOwner = PropertyReader.getProperty(CANANOLAB_PROPERTY,
"applicationOwner");
if (appOwner == null || appOwner.length() == 0)
appOwner = DEFAULT_APP_OWNER;
APP_OWNER = appOwner;
}
public static final String SAMPLE_PREFIX;
static {
String samplePrefix = PropertyReader.getProperty(CANANOLAB_PROPERTY,
"samplePrefix");
if (samplePrefix == null || samplePrefix.length() == 0)
samplePrefix = DEFAULT_SAMPLE_PREFIX;
SAMPLE_PREFIX = samplePrefix;
}
public static final String GRID_INDEX_SERVICE_URL;
static {
String gridIndexServiceURL = PropertyReader.getProperty(
CANANOLAB_PROPERTY, "gridIndexServiceURL");
GRID_INDEX_SERVICE_URL = gridIndexServiceURL;
}
/*
* The following Strings are nano specific
*
*/
public static final String[] DEFAULT_CHARACTERIZATION_SOURCES = new String[] { APP_OWNER };
public static final String[] CARBON_NANOTUBE_WALLTYPES = new String[] {
"Single (SWNT)", "Double (DWMT)", "Multiple (MWNT)" };
public static final String REPORT = "Report";
public static final String ASSOCIATED_FILE = "Other Associated File";
public static final String PROTOCOL_FILE = "Protocol File";
public static final String FOLDER_WORKFLOW_DATA = "workflow_data";
public static final String FOLDER_PARTICLE = "particles";
public static final String FOLDER_REPORT = "reports";
public static final String FOLDER_PROTOCOL = "protocols";
public static final String[] DEFAULT_POLYMER_INITIATORS = new String[] {
"Free Radicals", "Peroxide" };
public static final String[] DEFAULT_DENDRIMER_BRANCHES = new String[] {
"1-2", "1-3" };
public static final String[] DEFAULT_DENDRIMER_GENERATIONS = new String[] {
"0", "0.5", "1.0", "1.5", "2.0", "2.5", "3.0", "3.5", "4.0", "4.5",
"5.0", "5.5", "6.0", "6.5", "7.0", "7.5", "8.0", "8.5", "9.0",
"9.5", "10.0" };
public static final String CHARACTERIZATION_FILE = "characterizationFile";
public static final String DNA = "DNA";
public static final String PEPTIDE = "Peptide";
public static final String SMALL_MOLECULE = "Small Molecule";
public static final String PROBE = "Probe";
public static final String ANTIBODY = "Antibody";
public static final String IMAGE_CONTRAST_AGENT = "Image Contrast Agent";
public static final String ATTACHMENT = "Attachment";
public static final String ENCAPSULATION = "Encapsulation";
public static final String[] FUNCTION_AGENT_TYPES = new String[] { DNA,
PEPTIDE, SMALL_MOLECULE, PROBE, ANTIBODY, IMAGE_CONTRAST_AGENT };
public static final String[] FUNCTION_LINKAGE_TYPES = new String[] {
ATTACHMENT, ENCAPSULATION };
public static final String RECEPTOR = "Receptor";
public static final String ANTIGEN = "Antigen";
public static final int MAX_VIEW_TITLE_LENGTH = 23;
public static final String[] SPECIES_SCIENTIFIC = { "Mus musculus",
"Homo sapiens", "Rattus rattus", "Sus scrofa",
"Meriones unguiculatus", "Mesocricetus auratus", "Cavia porcellus",
"Bos taurus", "Canis familiaris", "Capra hircus", "Equus Caballus",
"Ovis aries", "Felis catus", "Saccharomyces cerevisiae",
"Danio rerio" };
public static final String[] SPECIES_COMMON = { "Mouse", "Human", "Rat",
"Pig", "Mongolian Gerbil", "Hamster", "Guinea pig", "Cattle",
"Dog", "Goat", "Horse", "Sheep", "Cat", "Yeast", "Zebrafish" };
public static final String UNIT_PERCENT = "%";
public static final String UNIT_CFU = "CFU";
public static final String UNIT_RFU = "RFU";
public static final String UNIT_SECOND = "SECOND";
public static final String UNIT_MG_ML = "mg/ml";
public static final String UNIT_FOLD = "Fold";
public static final String ORGANIC_HYDROCARBON = "organic:hydrocarbon";
public static final String ORGANIC_CARBON = "organic:carbon";
public static final String ORGANIC = "organic";
public static final String INORGANIC = "inorganic";
public static final String COMPLEX = "complex";
public static final Map<String, String> PARTICLE_CLASSIFICATION_MAP;
static {
PARTICLE_CLASSIFICATION_MAP = new HashMap<String, String>();
PARTICLE_CLASSIFICATION_MAP.put(Characterization.DENDRIMER_TYPE,
ORGANIC_HYDROCARBON);
PARTICLE_CLASSIFICATION_MAP.put(Characterization.POLYMER_TYPE,
ORGANIC_HYDROCARBON);
PARTICLE_CLASSIFICATION_MAP.put(Characterization.FULLERENE_TYPE,
ORGANIC_CARBON);
PARTICLE_CLASSIFICATION_MAP.put(Characterization.CARBON_NANOTUBE_TYPE,
ORGANIC_CARBON);
PARTICLE_CLASSIFICATION_MAP
.put(Characterization.LIPOSOME_TYPE, ORGANIC);
PARTICLE_CLASSIFICATION_MAP
.put(Characterization.EMULSION_TYPE, ORGANIC);
PARTICLE_CLASSIFICATION_MAP.put(Characterization.METAL_PARTICLE_TYPE,
INORGANIC);
PARTICLE_CLASSIFICATION_MAP.put(Characterization.QUANTUM_DOT_TYPE,
INORGANIC);
PARTICLE_CLASSIFICATION_MAP.put(Characterization.COMPLEX_PARTICLE_TYPE,
COMPLEX);
}
public static final String CSM_PI = APP_OWNER + "_PI";
public static final String CSM_RESEARCHER = APP_OWNER + "_Researcher";
public static final String CSM_ADMIN = APP_OWNER + "_Administrator";
public static final String CSM_PUBLIC_GROUP = "Public";
public static final String[] VISIBLE_GROUPS = new String[] { CSM_PI,
CSM_RESEARCHER };
public static final String AUTO_COPY_CHARACTERIZATION_VIEW_TITLE_PREFIX = "copy_";
public static final String AUTO_COPY_CHARACTERIZATION_VIEW_COLOR = "red";
public static final String UNIT_TYPE_CONCENTRATION = "Concentration";
public static final String UNIT_TYPE_CHARGE = "Charge";
public static final String UNIT_TYPE_QUANTITY = "Quantity";
public static final String UNIT_TYPE_AREA = "Area";
public static final String UNIT_TYPE_SIZE = "Size";
public static final String UNIT_TYPE_VOLUME = "Volume";
public static final String UNIT_TYPE_MOLECULAR_WEIGHT = "Molecular Weight";
public static final String UNIT_TYPE_ZETA_POTENTIAL = "Zeta Potential";
public static final String CSM_READ_ROLE = "R";
public static final String CSM_DELETE_ROLE = "D";
public static final String CSM_EXECUTE_ROLE = "E";
public static final String CSM_CURD_ROLE = "CURD";
public static final String CSM_CUR_ROLE = "CUR";
public static final String CSM_READ_PRIVILEGE = "READ";
public static final String CSM_EXECUTE_PRIVILEGE = "EXECUTE";
public static final String CSM_DELETE_PRIVILEGE = "DELETE";
public static final String CSM_CREATE_PRIVILEGE = "CREATE";
public static final String CSM_PG_SAMPLE = "sample";
public static final String CSM_PG_PROTOCOL = "protocol";
public static final String CSM_PG_PARTICLE = "nanoparticle";
public static final String CSM_PG_REPORT = "report";
public static final String PHYSICAL_ASSAY_PROTOCOL = "Physical assay";
public static final String INVITRO_ASSAY_PROTOCOL = "In Vitro assay";
/* image file name extension */
public static final String[] IMAGE_FILE_EXTENSIONS = { "AVS", "BMP", "CIN",
"DCX", "DIB", "DPX", "FITS", "GIF", "ICO", "JFIF", "JIF", "JPE",
"JPEG", "JPG", "MIFF", "OTB", "P7", "PALM", "PAM", "PBM", "PCD",
"PCDS", "PCL", "PCX", "PGM", "PICT", "PNG", "PNM", "PPM", "PSD",
"RAS", "SGI", "SUN", "TGA", "TIF", "TIFF", "WMF", "XBM", "XPM",
"YUV", "CGM", "DXF", "EMF", "EPS", "MET", "MVG", "ODG", "OTG",
"STD", "SVG", "SXD", "WMF" };
public static final String[] PUBLIC_DISPATCHES = { "setupView",
"summaryView", "detailView", "printDetailView", "exportDetail",
"printSummaryView", "printFullSummaryView", "exportSummary",
"exportFullSummary", "download", "loadFile" };
}
|
package de.dhbw.mannheim.cloudraid.fs;
import java.io.File;
import java.nio.file.Files;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
public class RecursiveFileSystemWatcher extends Thread {
private File dir;
private final static String TMP = System.getProperty("os.name")
.toLowerCase().contains("windows") ? "C:\\temp\\cloudraid\\"
: "/tmp/cloudraid/";
private final static File TMP_FILE = new File(TMP);
/**
* A map containing all known files.
*/
private static ConcurrentHashMap<String, Long> fileMap = new ConcurrentHashMap<String, Long>();
private Vector<String> keySet = new Vector<String>();
private long sleepTime = 10000;
/**
* Creates a RecursiveFileSystemWatcher that runs every 10s.
*/
public RecursiveFileSystemWatcher() {
dir = new File(System.getProperty("user.home") + "/tmp/");
System.out.println("Watching directory " + dir.getAbsolutePath());
this.setPriority(MIN_PRIORITY);
}
/**
* Creates a RecursiveFileSystemWatcher that runs in the given interval.
*
* @param sleepTime
* The sleeping time in ms.
*/
public RecursiveFileSystemWatcher(long sleepTime) {
this();
this.sleepTime = sleepTime;
}
/**
* {@inheritDoc}
*/
public void run() {
while (!isInterrupted()) {
keySet = new Vector<String>(fileMap.keySet());
if (!this.dir.exists()) {
System.err.println("The watch directory does not exist");
break;
} else {
this.checkDir(this.dir);
}
// all files still in "keySet" were not found, this means they were
// deleted
for (String k : keySet) {
System.out.println(k + " was deleted.");
fileMap.remove(k);
}
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.err.println("The file system watcher is stopped");
}
/**
* Runs through the list of files in the given directory and handles the
* files according to their type.
*
* @param file
* The directory to be handled.
*/
private void checkDir(File dir) {
if (dir.isFile()) {
for (File f : dir.listFiles()) {
if (Files.isSymbolicLink(f.toPath())) {
System.err.println("I do not handle the symbolic link at "
+ f.getAbsolutePath());
} else if (f.isDirectory()) {
this.checkDir(f);
} else if (f.isFile()) {
this.checkFile(f);
} else {
System.err
.println("Whoops! I don't know how to handle the file "
+ f.getAbsolutePath());
}
}
}
}
/**
* Checks the given file and handles it according to the status.
*
* @param file
* The file to be handled.
*/
private void checkFile(File file) {
String name = file.getAbsolutePath();
if (fileMap.containsKey(name)) {
if (file.lastModified() == fileMap.get(name)) {
// nothing to do, file already indexed
// System.out.println(file.getAbsolutePath() +
// " already exists.");
} else {
// the file changed
System.out.println(file.getAbsolutePath() + " was changed.");
}
keySet.remove(name);
} else {
// a new file is found
System.out.println(file.getAbsolutePath() + " is a new file.");
fileMap.put(file.getAbsolutePath(), file.lastModified());
}
}
public static void main(String[] args) {
new RecursiveFileSystemWatcher(60000).start();
new RecursiveFileSystemWatcher(50000).start();
}
}
|
package de.gurkenlabs.litiengine.environment;
import java.lang.reflect.Field;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import de.gurkenlabs.litiengine.entities.IEntity;
import de.gurkenlabs.litiengine.environment.tilemap.IMapObject;
import de.gurkenlabs.litiengine.environment.tilemap.TmxProperty;
import de.gurkenlabs.litiengine.environment.tilemap.TmxType;
import de.gurkenlabs.litiengine.environment.tilemap.xml.DecimalFloatAdapter;
import de.gurkenlabs.litiengine.environment.tilemap.xml.MapObject;
import de.gurkenlabs.litiengine.util.ArrayUtilities;
public final class MapObjectSerializer {
private static final Logger log = Logger.getLogger(MapObjectSerializer.class.getName());
private MapObjectSerializer() {
}
public static MapObject serialize(IEntity entity) {
MapObject obj = new MapObject();
obj.setId(entity.getMapId());
obj.setX((float) entity.getX());
obj.setY((float) entity.getY());
obj.setWidth((float) entity.getWidth());
obj.setHeight((float) entity.getHeight());
obj.setName(entity.getName());
TmxType type = entity.getClass().getAnnotation(TmxType.class);
if (type != null) {
obj.setType(type.value().toString());
}
serialize(entity.getClass(), entity, obj);
return obj;
}
private static <T extends IEntity> void serialize(Class<?> clz, T entity, MapObject mapObject) {
for (final Field field : clz.getDeclaredFields()) {
serialize(field, entity, mapObject);
}
// recursively call all parent classes and serialize annotated fields
Class<?> parentClass = clz.getSuperclass();
if (parentClass != null) {
serialize(parentClass, entity, mapObject);
}
}
private static void serialize(Field field, Object entity, IMapObject mapObject) {
TmxProperty property = field.getAnnotation(TmxProperty.class);
if (property == null) {
return;
}
Object value;
try {
if (!field.isAccessible()) {
field.setAccessible(true);
}
value = field.get(entity);
if (value == null) {
return;
}
mapObject.setValue(property.name(), getPropertyValue(field, value));
} catch (IllegalAccessException e) {
log.log(Level.SEVERE, e.getMessage(), e);
}
}
private static String getPropertyValue(Field field, Object value) {
if (field.getType().equals(Float.class) || field.getType().equals(Double.class)) {
try {
return new DecimalFloatAdapter().marshal((Float) value);
} catch (Exception e) {
log.log(Level.SEVERE, e.getMessage(), e);
}
} else if (field.getType().equals(Integer.class)) {
return Integer.toString((int) value);
} else if (field.getType().equals(short.class)) {
return Short.toString((short) value);
} else if (field.getType().equals(byte.class)) {
return Byte.toString((byte) value);
} else if (field.getType().equals(long.class)) {
return Long.toString((long) value);
}
if (value instanceof List<?>) {
return ArrayUtilities.join((List<?>) value);
// special handling
}
if (value.getClass().isArray()) {
if (field.getType().getComponentType() == int.class) {
return ArrayUtilities.join((int[]) value);
} else if (field.getType().getComponentType() == double.class) {
return ArrayUtilities.join((double[]) value);
} else if (field.getType().getComponentType() == float.class) {
return ArrayUtilities.join((float[]) value);
} else if (field.getType().getComponentType() == short.class) {
return ArrayUtilities.join((short[]) value);
} else if (field.getType().getComponentType() == byte.class) {
return ArrayUtilities.join((byte[]) value);
} else if (field.getType().getComponentType() == long.class) {
return ArrayUtilities.join((long[]) value);
} else if (field.getType().getComponentType() == String.class) {
return ArrayUtilities.join((String[]) value);
} else if (field.getType().getComponentType() == boolean.class) {
return ArrayUtilities.join((boolean[]) value);
} else {
return ArrayUtilities.join((Object[]) value);
}
}
return value.toString();
}
}
|
// samskivert library - useful routines for java programs
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.jdbc.depot;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import com.samskivert.io.PersistenceException;
import com.samskivert.util.StringUtil;
import com.samskivert.jdbc.ConnectionProvider;
import com.samskivert.jdbc.DatabaseLiaison;
import com.samskivert.jdbc.DuplicateKeyException;
import com.samskivert.jdbc.LiaisonRegistry;
import com.samskivert.jdbc.MySQLLiaison;
import com.samskivert.jdbc.PostgreSQLLiaison;
import com.samskivert.jdbc.depot.annotation.TableGenerator;
import static com.samskivert.jdbc.depot.Log.log;
/**
* Defines a scope in which global annotations are shared.
*/
public class PersistenceContext
{
/** Map {@link TableGenerator} instances by name. */
public HashMap<String, TableGenerator> tableGenerators = new HashMap<String, TableGenerator>();
/**
* A cache listener is notified when cache entries change. Its purpose is typically to do
* further invalidation of dependent entries in other caches.
*/
public static interface CacheListener<T>
{
/**
* The given entry (which is never null) has just been evicted from the cache slot
* indicated by the given key.
*
* This method is most commonly used to trigger custom cache invalidation of records that
* depend on the one that was just invalidated.
*/
public void entryInvalidated (CacheKey key, T oldEntry);
/**
* The given entry, which may be an explicit null, has just been placed into the cache
* under the given key. The previous cache entry, if any, is also supplied.
*
* This method is most likely used by repositories to index entries by attribute for quick
* cache invalidation when brute force is unrealistically time consuming.
*/
public void entryCached (CacheKey key, T newEntry, T oldEntry);
}
/**
* The callback for {@link #cacheTraverse}; this is called for each entry in a given cache.
*/
public static interface CacheTraverser<T extends Serializable>
{
/**
* Performs whatever cache-related tasks need doing for this cache entry. This method
* is called for each cache entry in a full-cache enumeration.
*/
public void visitCacheEntry (
PersistenceContext ctx, String cacheId, Serializable key, T record);
}
/**
* A simple implementation of {@link CacheTraverser} that selectively deletes entries in
* a cache depending on the return value of {@link #testCacheEntry}.
*/
public static abstract class CacheEvictionFilter<T extends Serializable>
implements CacheTraverser<T>
{
// from CacheTraverser
public void visitCacheEntry (
PersistenceContext ctx, String cacheId, Serializable key, T record)
{
if (testForEviction(key, record)) {
ctx.cacheInvalidate(cacheId, key);
}
}
/**
* Decides whether or not this entry should be evicted and returns true if yes, false if
* no.
*/
protected abstract boolean testForEviction (Serializable key, T record);
}
/**
* Creates a persistence context that will use the supplied provider to obtain JDBC
* connections.
*
* @param ident the identifier to provide to the connection provider when requesting a
* connection.
*/
public PersistenceContext (String ident, ConnectionProvider conprov)
{
this(ident, conprov, null);
}
/**
* Creates a persistence context that will use the supplied provider to obtain JDBC
* connections.
*
* @param ident the identifier to provide to the connection provider when requesting a
* connection.
*/
public PersistenceContext (String ident, ConnectionProvider conprov, CacheAdapter adapter)
{
_ident = ident;
_conprov = conprov;
_liaison = LiaisonRegistry.getLiaison(conprov.getURL(ident));
_cache = adapter;
}
/**
* Shuts this persistence context down, shutting down any caching system in use and shutting
* down the JDBC connection pool.
*/
public void shutdown ()
{
try {
if (_cache != null) {
_cache.shutdown();
}
} catch (Throwable t) {
log.log(Level.WARNING, "Failure shutting down Depot cache.", t);
}
_conprov.shutdown();
}
/**
* Create and return a new {@link SQLBuilder} for the appropriate dialect.
*
* TODO: At some point perhaps use a more elegant way of discerning our dialect.
*/
public SQLBuilder getSQLBuilder (DepotTypes types)
{
if (_liaison instanceof PostgreSQLLiaison) {
return new PostgreSQLBuilder(types);
}
if (_liaison instanceof MySQLLiaison) {
return new MySQLBuilder(types);
}
throw new IllegalArgumentException("Unknown liaison type: " + _liaison.getClass());
}
/**
* Registers a migration for the specified entity class.
*
* <p> This method must be called <b>before</b> an Entity is used by any repository. Thus you
* should register all migrations immediately after creating your persistence context or if you
* are careful to ensure that your Entities are only used by a single repository, you can
* register your migrations in the constructor for that repository.
*
* <p> Note that the migration process is as follows:
*
* <ul><li> Note the difference between the entity's declared version and the version recorded
* in the database.
* <li> Run all registered pre-migrations
* <li> Perform all default migrations (column additions and removals)
* <li> Run all registered post-migrations </ul>
*
* Thus you must either be prepared for the entity to be at <b>any</b> version prior to your
* migration target version because we may start up, find the schema at version 1 and the
* Entity class at version 8 and do all "standard" migrations in one fell swoop. So if a column
* got added in version 2 and renamed in version 6 and your migration was registered for
* version 6 to do that migration, it must be prepared for the column not to exist at all.
*
* <p> If you want a completely predictable migration process, never use the default migrations
* and register a pre-migration for every single schema migration and they will then be
* guaranteed to be run in registration order and with predictable pre- and post-conditions.
*/
public <T extends PersistentRecord> void registerMigration (
Class<T> type, EntityMigration migration)
{
getRawMarshaller(type).registerMigration(migration);
}
/**
* Returns the marshaller for the specified persistent object class, creating and initializing
* it if necessary.
*/
public <T extends PersistentRecord> DepotMarshaller<T> getMarshaller (Class<T> type)
throws PersistenceException
{
DepotMarshaller<T> marshaller = getRawMarshaller(type);
if (!marshaller.isInitialized()) {
// initialize the marshaller which may create or migrate the table for its underlying
// persistent object
marshaller.init(this);
}
return marshaller;
}
/**
* Invokes a non-modifying query and returns its result.
*/
public <T> T invoke (Query<T> query)
throws PersistenceException
{
CacheKey key = query.getCacheKey();
// if there is a cache key, check the cache
if (key != null && _cache != null) {
CacheAdapter.CachedValue<T> cacheHit = cacheLookup(key);
if (cacheHit != null) {
log.fine("invoke: cache hit [hit=" + cacheHit + "]");
T value = cacheHit.getValue();
value = query.transformCacheHit(key, value);
if (value != null) {
return value;
}
log.fine("invoke: transformCacheHit returned null; rejecting cached value.");
}
log.fine("invoke: cache miss [key=" + key + "]");
}
// otherwise, perform the query
@SuppressWarnings("unchecked") T result = (T) invoke(query, null, true);
// and let the caller figure out if it wants to cache itself somehow
query.updateCache(this, result);
return result;
}
/**
* Invokes a modifying query and returns the number of rows modified.
*/
public int invoke (Modifier modifier)
throws PersistenceException
{
modifier.cacheInvalidation(this);
int rows = (Integer) invoke(null, modifier, true);
if (rows > 0) {
modifier.cacheUpdate(this);
}
return rows;
}
/**
* Returns true if there is a {@link CacheAdapter} configured, false otherwise.
*/
public boolean isUsingCache ()
{
return _cache != null;
}
/**
* Looks up an entry in the cache by the given key.
*/
public <T> CacheAdapter.CachedValue<T> cacheLookup (CacheKey key)
{
if (_cache == null) {
return null;
}
CacheAdapter.CacheBin<T> bin = _cache.getCache(key.getCacheId());
return bin.lookup(key.getCacheKey());
}
/**
* Stores a new entry indexed by the given key.
*/
public <T> void cacheStore (CacheKey key, T entry)
{
if (_cache == null) {
return;
}
if (key == null) {
log.warning("Cache key must not be null [entry=" + entry + "]");
Thread.dumpStack();
return;
}
log.fine("cacheStore: entry [key=" + key + ", value=" + entry + "]");
CacheAdapter.CacheBin<T> bin = _cache.getCache(key.getCacheId());
CacheAdapter.CachedValue element = bin.lookup(key.getCacheKey());
@SuppressWarnings("unchecked") T oldEntry =
(element != null ? (T) element.getValue() : null);
// update the cache
bin.store(key.getCacheKey(), entry);
// then do cache invalidations
Set<CacheListener<?>> listeners = _listenerSets.get(key.getCacheId());
if (listeners != null && listeners.size() > 0) {
for (CacheListener<?> listener : listeners) {
log.fine("cacheInvalidate: cascading [listener=" + listener + "]");
@SuppressWarnings("unchecked")
CacheListener<T> casted = (CacheListener<T>)listener;
casted.entryCached(key, entry, oldEntry);
}
}
}
/**
* Evicts the cache entry indexed under the given key, if there is one. The eviction may
* trigger further cache invalidations.
*/
public void cacheInvalidate (CacheKey key)
{
if (key == null) {
log.warning("Cache key to invalidate must not be null.");
Thread.dumpStack();
} else {
cacheInvalidate(key.getCacheId(), key.getCacheKey());
}
}
/**
* Evicts the cache entry indexed under the given class and cache key, if there is one. The
* eviction may trigger further cache invalidations.
*/
public void cacheInvalidate (Class pClass, Serializable cacheKey)
{
cacheInvalidate(pClass.getName(), cacheKey);
}
/**
* Evicts the cache entry indexed under the given cache id and cache key, if there is one. The
* eviction may trigger further cache invalidations.
*/
public <T extends Serializable> void cacheInvalidate (String cacheId, Serializable cacheKey)
{
if (_cache == null) {
return;
}
log.fine("cacheInvalidate: entry [cacheId=" + cacheId + ", cacheKey=" + cacheKey + "]");
CacheAdapter.CacheBin<T> bin = _cache.getCache(cacheId);
CacheAdapter.CachedValue<T> element = bin.lookup(cacheKey);
if (element == null) {
return;
}
// find the old entry, if any
T oldEntry = element.getValue();
if (oldEntry != null) {
// if there was one, do (possibly cascading) cache invalidations
Set<CacheListener<?>> listeners = _listenerSets.get(cacheId);
if (listeners != null && listeners.size() > 0) {
CacheKey key = new SimpleCacheKey(cacheId, cacheKey);
for (CacheListener<?> listener : listeners) {
log.fine("cacheInvalidate: cascading [listener=" + listener + "]");
@SuppressWarnings("unchecked") CacheListener<T> casted =
(CacheListener<T>)listener;
casted.entryInvalidated(key, oldEntry);
}
}
}
// then evict the keyed entry, if needed
log.fine("cacheInvalidate: evicting [cacheKey=" + cacheKey + "]");
bin.remove(cacheKey);
}
/**
* Brutally iterates over the entire contents of the cache associated with the given class,
* invoking the callback for each cache entry.
*/
public <T extends Serializable> void cacheTraverse (Class pClass, CacheTraverser<T> filter)
{
cacheTraverse(pClass.getName(), filter);
}
/**
* Brutally iterates over the entire contents of the cache identified by the given cache id,
* invoking the callback for each cache entry.
*/
public <T extends Serializable> void cacheTraverse (String cacheId, CacheTraverser<T> filter)
{
if (_cache == null) {
return;
}
CacheAdapter.CacheBin<T> bin = _cache.getCache(cacheId);
if (bin != null) {
for (Object key : bin.enumerateKeys()) {
CacheAdapter.CachedValue<T> element = bin.lookup((Serializable) key);
if (element != null) {
filter.visitCacheEntry(this, cacheId, (Serializable) key, element.getValue());
}
}
}
}
/**
* Registers a new cache listener with the cache associated with the given class.
*/
public <T extends Serializable> void addCacheListener (
Class<T> pClass, CacheListener<T> listener)
{
addCacheListener(pClass.getName(), listener);
}
/**
* Registers a new cache listener with the identified cache.
*/
public <T extends Serializable> void addCacheListener (
String cacheId, CacheListener<T> listener)
{
Set<CacheListener<?>> listenerSet = _listenerSets.get(cacheId);
if (listenerSet == null) {
listenerSet = new HashSet<CacheListener<?>>();
_listenerSets.put(cacheId, listenerSet);
}
listenerSet.add(listener);
}
/**
* Iterates over all {@link PersistentRecord} classes managed by this context and initializes
* their {@link DepotMarshaller}. This forces migrations to run and the database schema to be
* created.
*/
public void initializeManagedRecords ()
throws PersistenceException
{
for (Class<? extends PersistentRecord> rclass : _managedRecords) {
getMarshaller(rclass);
}
}
/**
* Called when a depot repository is created. We register all persistent record classes used by
* the repository so that systems that desire it can force the resolution of all database
* tables rather than allowing resolution to happen on demand.
*/
protected void repositoryCreated (DepotRepository repo)
{
repo.getManagedRecords(_managedRecords);
}
/**
* Looks up and creates, but does not initialize, the marshaller for the specified Entity
* type.
*/
protected <T extends PersistentRecord> DepotMarshaller<T> getRawMarshaller (Class<T> type)
{
@SuppressWarnings("unchecked") DepotMarshaller<T> marshaller =
(DepotMarshaller<T>)_marshallers.get(type);
if (marshaller == null) {
_marshallers.put(type, marshaller = new DepotMarshaller<T>(type, this));
}
return marshaller;
}
/**
* Internal invoke method that takes care of transient retries
* for both queries and modifiers.
*/
protected <T> Object invoke (
Query<T> query, Modifier modifier, boolean retryOnTransientFailure)
throws PersistenceException
{
boolean isReadOnlyQuery = (query != null);
Connection conn = _conprov.getConnection(_ident, isReadOnlyQuery);
// TEMP: we synchronize on the connection to cooperate with SimpleRepository when used in
// conjunction with a StaticConnectionProvider; at some point we'll switch to standard JDBC
// connection pooling which will block in getConnection() instead of returning a connection
// that someone else may be using
synchronized (conn) {
try {
if (isReadOnlyQuery) {
// if this becomes more complex than this single statement, then this should
// turn into a method call that contains the complexity
return query.invoke(conn, _liaison);
} else {
// if this becomes more complex than this single statement, then this should
// turn into a method call that contains the complexity
return modifier.invoke(conn, _liaison);
}
} catch (SQLException sqe) {
if (!isReadOnlyQuery) {
// convert this exception to a DuplicateKeyException if appropriate
if (_liaison.isDuplicateRowException(sqe)) {
throw new DuplicateKeyException(sqe.getMessage());
}
}
// let the provider know that the connection failed
_conprov.connectionFailed(_ident, isReadOnlyQuery, conn, sqe);
conn = null;
if (retryOnTransientFailure && _liaison.isTransientException(sqe)) {
// the MySQL JDBC driver has the annoying habit of including the embedded
// exception stack trace in the message of their outer exception; if I want a
// fucking stack trace, I'll call printStackTrace() thanksverymuch
String msg = StringUtil.split(String.valueOf(sqe), "\n")[0];
log.info("Transient failure executing op, retrying [error=" + msg + "].");
} else {
String msg = isReadOnlyQuery ?
"Query failure " + query : "Modifier failure " + modifier;
throw new PersistenceException(msg, sqe);
}
} finally {
_conprov.releaseConnection(_ident, isReadOnlyQuery, conn);
}
}
// if we got here, we want to retry a transient failure
return invoke(query, modifier, false);
}
protected String _ident;
protected ConnectionProvider _conprov;
protected DatabaseLiaison _liaison;
/** The object through which all our caching is relayed, or null, for no caching. */
protected CacheAdapter _cache;
protected Map<String, Set<CacheListener<?>>> _listenerSets =
new HashMap<String, Set<CacheListener<?>>>();
protected Map<Class<?>, DepotMarshaller<?>> _marshallers =
new HashMap<Class<?>, DepotMarshaller<?>>();
/**
* The set of persistent records for which this context is responsible. This data is used by
* {@link #initializeManagedRecords} to force migration/schema initialization.
*/
protected Set<Class<? extends PersistentRecord>> _managedRecords =
new HashSet<Class<? extends PersistentRecord>>();
}
|
package net.ossrs.yasea;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.Image;
import android.media.MediaCodec;
import android.media.MediaCodecInfo;
import android.media.MediaCodecList;
import android.media.MediaFormat;
import android.media.MediaRecorder;
import android.util.Log;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.atomic.AtomicInteger;
public class SrsEncoder {
private static final String TAG = "SrsEncoder";
public static final String VCODEC = "video/avc";
public static final String ACODEC = "audio/mp4a-latm";
public static String x264Preset = "veryfast";
public static int vPrevWidth = 640;
public static int vPrevHeight = 360;
public static int vPortraitWidth = 720;
public static int vPortraitHeight = 1280;
public static int vLandscapeWidth = 1280;
public static int vLandscapeHeight = 720;
public static int vOutWidth = 720; // Note: the stride of resolution must be set as 16x for hard encoding with some chip like MTK
public static int vOutHeight = 1280; // Since Y component is quadruple size as U and V component, the stride must be set as 32x
public static int vBitrate = 1200 * 1024; // 1200 kbps
public static final int VFPS = 30;
public static final int VGOP = 60;
public static final int ASAMPLERATE = 44100;
public static int aChannelConfig = AudioFormat.CHANNEL_IN_STEREO;
public static final int ABITRATE = 192 * 1024; // 192 kbps
private SrsEncodeHandler mHandler;
private SrsFlvMuxer flvMuxer;
private SrsMp4Muxer mp4Muxer;
private MediaCodec vencoder;
private MediaCodec aencoder;
private MediaCodec.BufferInfo vebi = new MediaCodec.BufferInfo();
private MediaCodec.BufferInfo aebi = new MediaCodec.BufferInfo();
private boolean networkWeakTriggered = false;
private boolean mCameraFaceFront = true;
private boolean useSoftEncoder = false;
private boolean canSoftEncode = false;
public long mPresentTimeUs;
private int mVideoColorFormat;
private int videoFlvTrack;
private int videoMp4Track;
private int audioFlvTrack;
private int audioMp4Track;
private int rotate = 0;
private int rotateFlip = 180;
private int vInputWidth;
private int vInputHeight;
private byte[] y_frame;
private byte[] u_frame;
private byte[] v_frame;
private int[] argb_frame;
private long lastVideoPTS = -1;
private long lastAudioPTS = -1;
// Y, U (Cb) and V (Cr)
// yuv420 yuv yuv yuv yuv
// yuv420p (planar) yyyy*2 uu vv
// yuv420sp(semi-planner) yyyy*2 uv uv
// I420 -> YUV420P yyyy*2 uu vv
// YV12 -> YUV420P yyyy*2 vv uu
// NV12 -> YUV420SP yyyy*2 uv uv
// NV21 -> YUV420SP yyyy*2 vu vu
// NV16 -> YUV422SP yyyy uv uv
// YUY2 -> YUV422SP yuyv yuyv
public SrsEncoder(SrsEncodeHandler handler) {
mHandler = handler;
}
public void setFlvMuxer(SrsFlvMuxer flvMuxer) {
this.flvMuxer = flvMuxer;
}
public void setMp4Muxer(SrsMp4Muxer mp4Muxer) {
this.mp4Muxer = mp4Muxer;
}
public boolean start() {
if (flvMuxer == null && mp4Muxer == null) {
return false;
}
// the referent PTS for video and audio encoder.
mPresentTimeUs = System.currentTimeMillis() * 1000;
lastVideoPTS = 0;
lastAudioPTS = 0;
setEncoderResolution(vOutWidth, vOutHeight);
setEncoderFps(VFPS);
setEncoderGop(VGOP);
// Unfortunately for some android phone, the output fps is less than 10 limited by the
// capacity of poor cheap chips even with x264. So for the sake of quick appearance of
// the first picture on the player, a spare lower GOP value is suggested. But note that
// lower GOP will produce more I frames and therefore more streaming data flow.
// setEncoderGop(15);
setEncoderBitrate(vBitrate);
setEncoderPreset(x264Preset);
if (useSoftEncoder) {
canSoftEncode = openSoftEncoder();
if (!canSoftEncode) {
return false;
}
}
MediaCodecList list = new MediaCodecList(MediaCodecList.REGULAR_CODECS);
// vencoder yuv to 264 es stream.
// requires sdk level 16+, Android 4.1, 4.1.1, the JELLY_BEAN
try {
mVideoColorFormat = MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar;
// setup the vencoder.
// Note: landscape to portrait, 90 degree rotation, so we need to switch width and height in configuration
MediaFormat videoFormat = MediaFormat.createVideoFormat(VCODEC, vOutWidth, vOutHeight);
videoFormat.setInteger(MediaFormat.KEY_COLOR_FORMAT, mVideoColorFormat);
videoFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, 0);
videoFormat.setInteger(MediaFormat.KEY_BIT_RATE, vBitrate);
videoFormat.setInteger(MediaFormat.KEY_FRAME_RATE, VFPS);
videoFormat.setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, VGOP / VFPS);
String videoCodecName = list.findEncoderForFormat(videoFormat);
vencoder = MediaCodec.createByCodecName(videoCodecName);
vencoder.configure(videoFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
// add the video tracker to muxer.
if (flvMuxer != null) videoFlvTrack = flvMuxer.addTrack(videoFormat);
if (mp4Muxer != null) videoMp4Track = mp4Muxer.addTrack(videoFormat);
} catch (IOException e) {
Log.e(TAG, "create vencoder failed.");
e.printStackTrace();
return false;
}
// aencoder pcm to aac raw stream.
// requires sdk level 16+, Android 4.1, 4.1.1, the JELLY_BEAN
try {
// setup the aencoder.
int ach = aChannelConfig == AudioFormat.CHANNEL_IN_STEREO ? 2 : 1;
MediaFormat audioFormat = MediaFormat.createAudioFormat(ACODEC, ASAMPLERATE, ach);
audioFormat.setInteger(MediaFormat.KEY_BIT_RATE, ABITRATE);
audioFormat.setInteger(MediaFormat.KEY_MAX_INPUT_SIZE, getPcmBufferSize());
String AudioCodecName = list.findEncoderForFormat(audioFormat);
aencoder = MediaCodec.createByCodecName(AudioCodecName);
aencoder.configure(audioFormat, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
// add the audio tracker to muxer.
if (flvMuxer != null) audioFlvTrack = flvMuxer.addTrack(audioFormat);
if (mp4Muxer != null) audioMp4Track = mp4Muxer.addTrack(audioFormat);
} catch (IOException e) {
Log.e(TAG, "create aencoder failed.");
e.printStackTrace();
return false;
}
// start device and encoder.
vencoder.start();
aencoder.start();
return true;
}
public void stop() {
if (useSoftEncoder) {
closeSoftEncoder();
canSoftEncode = false;
}
if (aencoder != null) {
Log.i(TAG, "stop aencoder");
aencoder.stop();
aencoder.release();
aencoder = null;
}
if (vencoder != null) {
Log.i(TAG, "stop vencoder");
vencoder.stop();
vencoder.release();
vencoder = null;
}
}
public void setCameraFrontFace() {
mCameraFaceFront = true;
}
public void setCameraBackFace() {
mCameraFaceFront = false;
}
public void switchToSoftEncoder() {
useSoftEncoder = true;
}
public void switchToHardEncoder() {
useSoftEncoder = false;
}
public boolean isSoftEncoder() {
return useSoftEncoder;
}
public boolean canHardEncode() {
return vencoder != null;
}
public boolean canSoftEncode() {
return canSoftEncode;
}
public boolean isEnabled() {
return canHardEncode() || canSoftEncode();
}
public void setPreviewResolution(int width, int height) {
vPrevWidth = width;
vPrevHeight = height;
}
public void setPortraitResolution(int width, int height) {
vOutWidth = width;
vOutHeight = height;
vPortraitWidth = width;
vPortraitHeight = height;
vLandscapeWidth = height;
vLandscapeHeight = width;
}
public void setInputResolution(int width, int height) {
vInputWidth = width;
vInputHeight = height;
y_frame = new byte[width * height];
u_frame = new byte[(width * height) / 2 - 1];
v_frame = new byte[(width * height) / 2 - 1];
}
public void setLandscapeResolution(int width, int height) {
vOutWidth = width;
vOutHeight = height;
vLandscapeWidth = width;
vLandscapeHeight = height;
vPortraitWidth = height;
vPortraitHeight = width;
}
public void setVideoHDMode() {
vBitrate = 3600 * 1024; // 3600 kbps
x264Preset = "veryfast";
}
public void setVideoSmoothMode() {
vBitrate = 1200 * 1024; // 1200 kbps
x264Preset = "superfast";
}
public int getPreviewWidth() {
return vPrevWidth;
}
public int getPreviewHeight() {
return vPrevHeight;
}
public int getOutputWidth() {
return vOutWidth;
}
public int getOutputHeight() {
return vOutHeight;
}
public void setScreenOrientation(int orientation) {
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
vOutWidth = vPortraitWidth;
vOutHeight = vPortraitHeight;
} else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
vOutWidth = vLandscapeWidth;
vOutHeight = vLandscapeHeight;
}
setEncoderResolution(vOutWidth, vOutHeight);
}
public void setCameraOrientation(int degrees) {
if (degrees < 0) {
rotate = 360 + degrees;
rotateFlip = 180 - degrees;
} else {
rotate = degrees;
rotateFlip = 180 + degrees;
}
}
private void encodeYuvFrame(byte[] yuvFrame, long pts) {
int inBufferIndex = vencoder.dequeueInputBuffer(-1);
if (inBufferIndex >= 0) {
ByteBuffer bb = vencoder.getInputBuffer(inBufferIndex);
bb.put(yuvFrame, 0, yuvFrame.length);
vencoder.queueInputBuffer(inBufferIndex, 0, yuvFrame.length, pts, 0);
}
}
public Frame getH264Frame() {
int outBufferIndex = vencoder.dequeueOutputBuffer(vebi, 0);
if (outBufferIndex >= 0) {
Frame frame = new Frame();
ByteBuffer bb = vencoder.getOutputBuffer(outBufferIndex);
frame.video = new byte[vebi.size];
bb.get(frame.video, 0, vebi.size);
frame.timestamp = vebi.presentationTimeUs + mPresentTimeUs;
vencoder.releaseOutputBuffer(outBufferIndex, false);
return frame;
}
return null;
}
/**
* Mux external H264 frame
*
* @param frame External frame
*/
public void muxH264Frame(Frame frame) {
if (frame==null) return;
ByteBuffer bb = ByteBuffer.wrap(frame.video, 0, frame.video.length);
vebi.offset = 0;
vebi.size = frame.video.length;
vebi.flags = 0;
vebi.presentationTimeUs = frame.timestamp - mPresentTimeUs;
mux264Frame(bb, vebi);
}
public boolean muxH264Frame() {
int outBufferIndex = vencoder.dequeueOutputBuffer(vebi, 0);
if (outBufferIndex >= 0) {
ByteBuffer bb = vencoder.getOutputBuffer(outBufferIndex);
mux264Frame(bb, vebi);
vencoder.releaseOutputBuffer(outBufferIndex, false);
return true;
}
return false;
}
/**
* Mux encoded H264 frame
*
* @param es Buffer
* @param bi Buffer info
*/
private void mux264Frame(ByteBuffer es, MediaCodec.BufferInfo bi) {
// Check video frame cache number to judge the networking situation.
// Just cache GOP / FPS seconds data according to latency.
AtomicInteger videoFrameCacheNumber = flvMuxer.getVideoFrameCacheNumber();
if (videoFrameCacheNumber != null && videoFrameCacheNumber.get() < VGOP) {
// if (bi.presentationTimeUs >= lastVideoPTS) {
if (flvMuxer != null) flvMuxer.writeSampleData(videoFlvTrack, es, bi);
if (mp4Muxer != null) mp4Muxer.writeSampleData(videoMp4Track, es.duplicate(), bi);
// lastVideoPTS = bi.presentationTimeUs;
if (networkWeakTriggered) {
networkWeakTriggered = false;
mHandler.notifyNetworkResume();
}
} else {
mHandler.notifyNetworkWeak();
networkWeakTriggered = true;
}
}
public void onGetPcmFrame(byte[] data, int size) {
int inBufferIndex = aencoder.dequeueInputBuffer(-1);
if (inBufferIndex >= 0) {
ByteBuffer bb = aencoder.getInputBuffer(inBufferIndex);
bb.put(data, 0, size);
long pts = System.currentTimeMillis() * 1000 - mPresentTimeUs;
aencoder.queueInputBuffer(inBufferIndex, 0, size, pts, 0);
}
}
public void muxPCMFrames() {
int outBufferIndex = aencoder.dequeueOutputBuffer(aebi, 0);
while (outBufferIndex >= 0) {
ByteBuffer bb = aencoder.getOutputBuffer(outBufferIndex);
muxAACFrame(bb, aebi);
aencoder.releaseOutputBuffer(outBufferIndex, false);
outBufferIndex = aencoder.dequeueOutputBuffer(aebi, 0);
}
}
/**
* Mux encoded AAC frame
*
* @param es Buffer
* @param bi Buffer info
*/
private void muxAACFrame(ByteBuffer es, MediaCodec.BufferInfo bi) {
// if (bi.presentationTimeUs >= lastAudioPTS) {
if (flvMuxer != null) flvMuxer.writeSampleData(audioFlvTrack, es, bi);
if (mp4Muxer != null) mp4Muxer.writeSampleData(audioMp4Track, es.duplicate(), bi);
// lastAudioPTS = bi.presentationTimeUs;
}
public void onGetRgbaFrame(byte[] data, int width, int height) {
encodeYuvFrame(RGBAtoYUV(data, width, height));
}
public void onGetYuvNV21Frame(byte[] data, int width, int height, Rect boundingBox) {
encodeYuvFrame(NV21toYUV(data, width, height, boundingBox));
}
public void onGetYUV420_888Frame(Image image, Rect boundingBox) {
encodeYuvFrame(YUV420_888toYUV(image, boundingBox));
}
public void onGetArgbFrame(int[] data, int width, int height, Rect boundingBox) {
encodeYuvFrame(ARGBtoYUV(data, width, height, boundingBox));
}
public void encodeYuvFrame(byte[] frame) {
long pts = System.currentTimeMillis() * 1000 - mPresentTimeUs;
encodeYuvFrame(frame, pts);
}
public byte[] RGBAtoYUV(byte[] data, int width, int height) {
switch (mVideoColorFormat) {
case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar:
return RGBAToI420(data, width, height, true, rotateFlip);
case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar:
return RGBAToNV12(data, width, height, true, rotateFlip);
default:
throw new IllegalStateException("Unsupported color format!");
}
}
public byte[] NV21toYUV(byte[] data, int width, int height, Rect boundingBox) {
switch (mVideoColorFormat) {
case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar:
return NV21ToI420(data, width, height, true, rotateFlip, boundingBox.left, boundingBox.top, boundingBox.width(), boundingBox.height());
case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar:
return NV21ToNV12(data, width, height, true, rotateFlip, boundingBox.left, boundingBox.top, boundingBox.width(), boundingBox.height());
default:
throw new IllegalStateException("Unsupported color format!");
}
}
public byte[] YUV420_888toYUV(Image image, Rect cropArea) {
Image.Plane[] planes = image.getPlanes();
planes[0].getBuffer().get(y_frame);
planes[1].getBuffer().get(u_frame);
planes[2].getBuffer().get(v_frame);
return YUV420_888toI420(y_frame, u_frame, v_frame, vInputWidth, vInputHeight, false, 0,
cropArea.left, cropArea.top, cropArea.width(), cropArea.height());
}
public void setOverlay(Bitmap overlay) {
if (overlay == null) return;
if (argb_frame == null) {
argb_frame = new int[vOutWidth * vOutHeight];
}
overlay.getPixels(argb_frame, 0, vOutWidth, 0, 0, vOutWidth, vOutHeight);
ARGBToOverlay(argb_frame, vOutWidth, vOutHeight, false, 0);
}
public byte[] ARGBtoYUV(int[] data, int width, int height, Rect boundingBox) {
switch (mVideoColorFormat) {
case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar:
return ARGBToI420(data, width, height, false, rotate, boundingBox.left, boundingBox.top, boundingBox.width(), boundingBox.height());
case MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar:
return ARGBToNV12(data, width, height, false, rotate, boundingBox.left, boundingBox.top, boundingBox.width(), boundingBox.height());
default:
throw new IllegalStateException("Unsupported color format!");
}
}
public void onGetRgbaSoftFrame(byte[] data, int width, int height, long pts) {
RGBASoftEncode(data, width, height, true, 180, pts);
}
public AudioRecord chooseAudioRecord() {
AudioRecord mic = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, SrsEncoder.ASAMPLERATE,
AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT, getPcmBufferSize() * 4);
if (mic.getState() != AudioRecord.STATE_INITIALIZED) {
mic = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, SrsEncoder.ASAMPLERATE,
AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, getPcmBufferSize() * 4);
if (mic.getState() != AudioRecord.STATE_INITIALIZED) {
mic = null;
} else {
SrsEncoder.aChannelConfig = AudioFormat.CHANNEL_IN_MONO;
}
} else {
SrsEncoder.aChannelConfig = AudioFormat.CHANNEL_IN_STEREO;
}
return mic;
}
public int getPcmBufferSize() {
return AudioRecord.getMinBufferSize(ASAMPLERATE, AudioFormat.CHANNEL_IN_STEREO,
AudioFormat.ENCODING_PCM_16BIT);
}
private native void setEncoderResolution(int outWidth, int outHeight);
private native void setEncoderFps(int fps);
private native void setEncoderGop(int gop);
private native void setEncoderBitrate(int bitrate);
private native void setEncoderPreset(String preset);
private native byte[] RGBAToI420(byte[] frame, int width, int height, boolean flip, int rotate);
private native byte[] RGBAToNV12(byte[] frame, int width, int height, boolean flip, int rotate);
private native byte[] ARGBToI420(int[] frame, int width, int height, boolean flip, int rotate, int crop_x, int crop_y, int crop_width, int crop_height);
private native void ARGBToOverlay(int[] frame, int width, int height, boolean flip, int rotate);
private native byte[] YUV420_888toI420(byte[] y_frame, byte[] u_frame, byte[] v_frame, int width, int height, boolean flip, int rotate, int crop_x, int crop_y, int crop_width, int crop_height);
private native byte[] ARGBToNV12(int[] frame, int width, int height, boolean flip, int rotate, int crop_x, int crop_y, int crop_width, int crop_height);
private native byte[] NV21ToNV12(byte[] frame, int width, int height, boolean flip, int rotate, int crop_x, int crop_y, int crop_width, int crop_height);
private native byte[] NV21ToI420(byte[] frame, int width, int height, boolean flip, int rotate, int crop_x, int crop_y, int crop_width, int crop_height);
private native int RGBASoftEncode(byte[] frame, int width, int height, boolean flip, int rotate, long pts);
private native boolean openSoftEncoder();
private native void closeSoftEncoder();
static {
System.loadLibrary("yuv");
System.loadLibrary("enc");
}
}
|
package de.lmu.ifi.dbs.elki.utilities.datastructures;
import java.util.Comparator;
import java.util.List;
import de.lmu.ifi.dbs.elki.database.ids.ArrayModifiableDBIDs;
import de.lmu.ifi.dbs.elki.database.ids.DBID;
import de.lmu.ifi.dbs.elki.database.ids.DBIDArrayIter;
import de.lmu.ifi.dbs.elki.database.ids.DBIDRef;
/**
* QuickSelect computes ("selects") the element at a given rank and can be used
* to compute Medians and arbitrary quantiles by computing the appropriate rank.
*
* This algorithm is essentially an incomplete QuickSort that only descends into
* that part of the data that we are interested in, and also attributed to
* Charles Antony Richard Hoare
*
* @author Erich Schubert
*
* @apiviz.uses ArrayModifiableDBIDs
* @apiviz.uses List
* @apiviz.uses Comparator
*/
public class QuickSelect {
/**
* For small arrays, use a simpler method:
*/
private static final int SMALL = 10;
/**
* QuickSelect is essentially quicksort, except that we only "sort" that half
* of the array that we are interested in.
*
* Note: the array is <b>modified</b> by this.
*
* @param data Data to process
* @param rank Rank position that we are interested in (integer!)
* @return Value at the given rank
*/
public static double quickSelect(double[] data, int rank) {
quickSelect(data, 0, data.length, rank);
return data[rank];
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* Note: the array is <b>modified</b> by this.
*
* @param data Data to process
* @return Median value
*/
public static double median(double[] data) {
return median(data, 0, data.length);
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* Note: the array is <b>modified</b> by this.
*
* @param data Data to process
* @param begin Begin of valid values
* @param end End of valid values (exclusive!)
* @return Median value
*/
public static double median(double[] data, int begin, int end) {
final int length = end - begin;
assert (length > 0);
// Integer division is "floor" since we are non-negative.
final int left = begin + (length - 1) / 2;
quickSelect(data, begin, end, left);
if(length % 2 == 1) {
return data[left];
}
else {
quickSelect(data, begin, end, left + 1);
return data[left] + (data[left + 1] - data[left]) / 2;
}
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* Note: the array is <b>modified</b> by this.
*
* @param data Data to process
* @param quant Quantile to compute
* @return Value at quantile
*/
public static double quantile(double[] data, double quant) {
return quantile(data, 0, data.length, quant);
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* Note: the array is <b>modified</b> by this.
*
* @param data Data to process
* @param begin Begin of valid values
* @param end End of valid values (exclusive!)
* @param quant Quantile to compute
* @return Value at quantile
*/
public static double quantile(double[] data, int begin, int end, double quant) {
final int length = end - begin;
assert (length > 0) : "Quantile on empty set?";
// Integer division is "floor" since we are non-negative.
final double dleft = begin + (length - 1) * quant;
final int ileft = (int) Math.floor(dleft);
final double err = dleft - ileft;
quickSelect(data, begin, end, ileft);
if(err <= Double.MIN_NORMAL) {
return data[ileft];
}
else {
quickSelect(data, begin, end, ileft + 1);
// Mix:
double mix = data[ileft] + (data[ileft + 1] - data[ileft]) * err;
return mix;
}
}
/**
* QuickSelect is essentially quicksort, except that we only "sort" that half
* of the array that we are interested in.
*
* @param data Data to process
* @param start Interval start
* @param end Interval end (exclusive)
* @param rank rank position we are interested in (starting at 0)
*/
public static void quickSelect(double[] data, int start, int end, int rank) {
while(true) {
// Optimization for small arrays
// This also ensures a minimum size below
if(start + SMALL > end) {
insertionSort(data, start, end);
return;
}
// Pick pivot from three candidates: start, middle, end
// Since we compare them, we can also just "bubble sort" them.
final int middle = (start + end) / 2;
if(data[start] > data[middle]) {
swap(data, start, middle);
}
if(data[start] > data[end - 1]) {
swap(data, start, end - 1);
}
if(data[middle] > data[end - 1]) {
swap(data, middle, end - 1);
}
// TODO: use more candidates for larger arrays?
final double pivot = data[middle];
// Move middle element out of the way, just before end
// (Since we already know that "end" is bigger)
swap(data, middle, end - 2);
// Begin partitioning
int i = start + 1, j = end - 3;
// This is classic quicksort stuff
while(true) {
while(data[i] <= pivot && i <= j) {
i++;
}
while(data[j] >= pivot && j >= i) {
j
}
if(i >= j) {
break;
}
swap(data, i, j);
}
// Move pivot (former middle element) back into the appropriate place
swap(data, i, end - 2);
// In contrast to quicksort, we only need to recurse into the half we are
// interested in. Instead of recursion we now use iteration.
if(rank < i) {
end = i;
}
else if(rank > i) {
start = i + 1;
}
else {
break;
}
} // Loop until rank==i
}
/**
* Sort a small array using repetitive insertion sort.
*
* @param data Data to sort
* @param start Interval start
* @param end Interval end
*/
private static void insertionSort(double[] data, int start, int end) {
for(int i = start + 1; i < end; i++) {
for(int j = i; j > start && data[j - 1] > data[j]; j
swap(data, j, j - 1);
}
}
}
/**
* The usual swap method.
*
* @param data Array
* @param a First index
* @param b Second index
*/
private static final void swap(double[] data, int a, int b) {
double tmp = data[a];
data[a] = data[b];
data[b] = tmp;
}
/**
* QuickSelect is essentially quicksort, except that we only "sort" that half
* of the array that we are interested in.
*
* Note: the array is <b>modified</b> by this.
*
* @param <T> object type
* @param data Data to process
* @param rank Rank position that we are interested in (integer!)
* @return Value at the given rank
*/
public static <T extends Comparable<? super T>> T quickSelect(T[] data, int rank) {
quickSelect(data, 0, data.length, rank);
return data[rank];
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* Note: the array is <b>modified</b> by this.
*
* @param data Data to process
* @return Median value
*/
public static <T extends Comparable<? super T>> T median(T[] data) {
return median(data, 0, data.length);
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* On an odd length, it will return the lower element.
*
* Note: the array is <b>modified</b> by this.
*
* @param <T> object type
* @param data Data to process
* @param begin Begin of valid values
* @param end End of valid values (exclusive!)
* @return Median value
*/
public static <T extends Comparable<? super T>> T median(T[] data, int begin, int end) {
final int length = end - begin;
assert (length > 0);
// Integer division is "floor" since we are non-negative.
final int left = begin + (length - 1) / 2;
quickSelect(data, begin, end, left);
return data[left];
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* Note: the array is <b>modified</b> by this.
*
* @param <T> object type
* @param data Data to process
* @param quant Quantile to compute
* @return Value at quantile
*/
public static <T extends Comparable<? super T>> T quantile(T[] data, double quant) {
return quantile(data, 0, data.length, quant);
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* It will prefer the lower element.
*
* Note: the array is <b>modified</b> by this.
*
* @param <T> object type
* @param data Data to process
* @param begin Begin of valid values
* @param end End of valid values (exclusive!)
* @param quant Quantile to compute
* @return Value at quantile
*/
public static <T extends Comparable<? super T>> T quantile(T[] data, int begin, int end, double quant) {
final int length = end - begin;
assert (length > 0) : "Quantile on empty set?";
// Integer division is "floor" since we are non-negative.
final double dleft = begin + (length - 1) * quant;
final int ileft = (int) Math.floor(dleft);
quickSelect(data, begin, end, ileft);
return data[ileft];
}
/**
* QuickSelect is essentially quicksort, except that we only "sort" that half
* of the array that we are interested in.
*
* @param <T> object type
* @param data Data to process
* @param start Interval start
* @param end Interval end (exclusive)
* @param rank rank position we are interested in (starting at 0)
*/
public static <T extends Comparable<? super T>> void quickSelect(T[] data, int start, int end, int rank) {
while(true) {
// Optimization for small arrays
// This also ensures a minimum size below
if(start + SMALL > end) {
insertionSort(data, start, end);
return;
}
// Pick pivot from three candidates: start, middle, end
// Since we compare them, we can also just "bubble sort" them.
final int middle = (start + end) / 2;
if(data[start].compareTo(data[middle]) > 0) {
swap(data, start, middle);
}
if(data[start].compareTo(data[end - 1]) > 0) {
swap(data, start, end - 1);
}
if(data[middle].compareTo(data[end - 1]) > 0) {
swap(data, middle, end - 1);
}
// TODO: use more candidates for larger arrays?
final T pivot = data[middle];
// Move middle element out of the way, just before end
// (Since we already know that "end" is bigger)
swap(data, middle, end - 2);
// Begin partitioning
int i = start + 1, j = end - 3;
// This is classic quicksort stuff
while(true) {
while(data[i].compareTo(pivot) <= 0 && i <= j) {
i++;
}
while(data[j].compareTo(pivot) >= 0 && j >= i) {
j
}
if(i >= j) {
break;
}
swap(data, i, j);
}
// Move pivot (former middle element) back into the appropriate place
swap(data, i, end - 2);
// In contrast to quicksort, we only need to recurse into the half we are
// interested in. Instead of recursion we now use iteration.
if(rank < i) {
end = i;
}
else if(rank > i) {
start = i + 1;
}
else {
break;
}
} // Loop until rank==i
}
/**
* Sort a small array using repetitive insertion sort.
*
* @param <T> object type
* @param data Data to sort
* @param start Interval start
* @param end Interval end
*/
private static <T extends Comparable<? super T>> void insertionSort(T[] data, int start, int end) {
for(int i = start + 1; i < end; i++) {
for(int j = i; j > start && data[j - 1].compareTo(data[j]) > 0; j
swap(data, j, j - 1);
}
}
}
/**
* The usual swap method.
*
* @param <T> object type
* @param data Array
* @param a First index
* @param b Second index
*/
private static final <T extends Comparable<? super T>> void swap(T[] data, int a, int b) {
T tmp = data[a];
data[a] = data[b];
data[b] = tmp;
}
/**
* QuickSelect is essentially quicksort, except that we only "sort" that half
* of the array that we are interested in.
*
* Note: the array is <b>modified</b> by this.
*
* @param <T> object type
* @param data Data to process
* @param rank Rank position that we are interested in (integer!)
* @return Value at the given rank
*/
public static <T extends Comparable<? super T>> T quickSelect(List<? extends T> data, int rank) {
quickSelect(data, 0, data.size(), rank);
return data.get(rank);
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* Note: the array is <b>modified</b> by this.
*
* @param <T> object type
* @param data Data to process
* @return Median value
*/
public static <T extends Comparable<? super T>> T median(List<? extends T> data) {
return median(data, 0, data.size());
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* On an odd length, it will return the lower element.
*
* Note: the array is <b>modified</b> by this.
*
* @param <T> object type
* @param data Data to process
* @param begin Begin of valid values
* @param end End of valid values (exclusive!)
* @return Median value
*/
public static <T extends Comparable<? super T>> T median(List<? extends T> data, int begin, int end) {
final int length = end - begin;
assert (length > 0);
// Integer division is "floor" since we are non-negative.
final int left = begin + (length - 1) / 2;
quickSelect(data, begin, end, left);
return data.get(left);
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* Note: the array is <b>modified</b> by this.
*
* @param <T> object type
* @param data Data to process
* @param quant Quantile to compute
* @return Value at quantile
*/
public static <T extends Comparable<? super T>> T quantile(List<? extends T> data, double quant) {
return quantile(data, 0, data.size(), quant);
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* It will prefer the lower element.
*
* Note: the array is <b>modified</b> by this.
*
* @param <T> object type
* @param data Data to process
* @param begin Begin of valid values
* @param end End of valid values (exclusive!)
* @param quant Quantile to compute
* @return Value at quantile
*/
public static <T extends Comparable<? super T>> T quantile(List<? extends T> data, int begin, int end, double quant) {
final int length = end - begin;
assert (length > 0) : "Quantile on empty set?";
// Integer division is "floor" since we are non-negative.
final double dleft = begin + (length - 1) * quant;
final int ileft = (int) Math.floor(dleft);
quickSelect(data, begin, end, ileft);
return data.get(ileft);
}
/**
* QuickSelect is essentially quicksort, except that we only "sort" that half
* of the array that we are interested in.
*
* @param <T> object type
* @param data Data to process
* @param start Interval start
* @param end Interval end (exclusive)
* @param rank rank position we are interested in (starting at 0)
*/
public static <T extends Comparable<? super T>> void quickSelect(List<? extends T> data, int start, int end, int rank) {
while(true) {
// Optimization for small arrays
// This also ensures a minimum size below
if(start + SMALL > end) {
insertionSort(data, start, end);
return;
}
// Pick pivot from three candidates: start, middle, end
// Since we compare them, we can also just "bubble sort" them.
final int middle = (start + end) / 2;
if(data.get(start).compareTo(data.get(middle)) > 0) {
swap(data, start, middle);
}
if(data.get(start).compareTo(data.get(end - 1)) > 0) {
swap(data, start, end - 1);
}
if(data.get(middle).compareTo(data.get(end - 1)) > 0) {
swap(data, middle, end - 1);
}
// TODO: use more candidates for larger arrays?
final T pivot = data.get(middle);
// Move middle element out of the way, just before end
// (Since we already know that "end" is bigger)
swap(data, middle, end - 2);
// Begin partitioning
int i = start + 1, j = end - 3;
// This is classic quicksort stuff
while(true) {
while(data.get(i).compareTo(pivot) <= 0 && i <= j) {
i++;
}
while(data.get(j).compareTo(pivot) >= 0 && j >= i) {
j
}
if(i >= j) {
break;
}
swap(data, i, j);
}
// Move pivot (former middle element) back into the appropriate place
swap(data, i, end - 2);
// In contrast to quicksort, we only need to recurse into the half we are
// interested in. Instead of recursion we now use iteration.
if(rank < i) {
end = i;
}
else if(rank > i) {
start = i + 1;
}
else {
break;
}
} // Loop until rank==i
}
/**
* Sort a small array using repetitive insertion sort.
*
* @param <T> object type
* @param data Data to sort
* @param start Interval start
* @param end Interval end
*/
private static <T extends Comparable<? super T>> void insertionSort(List<T> data, int start, int end) {
for(int i = start + 1; i < end; i++) {
for(int j = i; j > start && data.get(j - 1).compareTo(data.get(j)) > 0; j
swap(data, j, j - 1);
}
}
}
/**
* The usual swap method.
*
* @param <T> object type
* @param data Array
* @param a First index
* @param b Second index
*/
private static final <T> void swap(List<T> data, int a, int b) {
data.set(b, data.set(a, data.get(b)));
}
/**
* QuickSelect is essentially quicksort, except that we only "sort" that half
* of the array that we are interested in.
*
* Note: the array is <b>modified</b> by this.
*
* @param <T> object type
* @param data Data to process
* @param comparator Comparator to use
* @param rank Rank position that we are interested in (integer!)
* @return Value at the given rank
*/
public static <T> T quickSelect(List<? extends T> data, Comparator<? super T> comparator, int rank) {
quickSelect(data, comparator, 0, data.size(), rank);
return data.get(rank);
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* Note: the array is <b>modified</b> by this.
*
* @param <T> object type
* @param data Data to process
* @param comparator Comparator to use
* @return Median value
*/
public static <T> T median(List<? extends T> data, Comparator<? super T> comparator) {
return median(data, comparator, 0, data.size());
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* On an odd length, it will return the lower element.
*
* Note: the array is <b>modified</b> by this.
*
* @param <T> object type
* @param data Data to process
* @param comparator Comparator to use
* @param begin Begin of valid values
* @param end End of valid values (exclusive!)
* @return Median value
*/
public static <T> T median(List<? extends T> data, Comparator<? super T> comparator, int begin, int end) {
final int length = end - begin;
assert (length > 0);
// Integer division is "floor" since we are non-negative.
final int left = begin + (length - 1) / 2;
quickSelect(data, comparator, begin, end, left);
return data.get(left);
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* Note: the array is <b>modified</b> by this.
*
* @param <T> object type
* @param data Data to process
* @param comparator Comparator to use
* @param quant Quantile to compute
* @return Value at quantile
*/
public static <T> T quantile(List<? extends T> data, Comparator<? super T> comparator, double quant) {
return quantile(data, comparator, 0, data.size(), quant);
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* It will prefer the lower element.
*
* Note: the array is <b>modified</b> by this.
*
* @param <T> object type
* @param data Data to process
* @param comparator Comparator to use
* @param begin Begin of valid values
* @param end End of valid values (inclusive!)
* @param quant Quantile to compute
* @return Value at quantile
*/
public static <T> T quantile(List<? extends T> data, Comparator<? super T> comparator, int begin, int end, double quant) {
final int length = end - begin;
assert (length > 0) : "Quantile on empty set?";
// Integer division is "floor" since we are non-negative.
final double dleft = begin + (length - 1) * quant;
final int ileft = (int) Math.floor(dleft);
quickSelect(data, comparator, begin, end, ileft);
return data.get(ileft);
}
/**
* QuickSelect is essentially quicksort, except that we only "sort" that half
* of the array that we are interested in.
*
* @param <T> object type
* @param data Data to process
* @param comparator Comparator to use
* @param start Interval start
* @param end Interval end (inclusive)
* @param rank rank position we are interested in (starting at 0)
*/
public static <T> void quickSelect(List<? extends T> data, Comparator<? super T> comparator, int start, int end, int rank) {
while(true) {
// Optimization for small arrays
// This also ensures a minimum size below
if(start + SMALL > end) {
insertionSort(data, comparator, start, end);
return;
}
// Pick pivot from three candidates: start, middle, end
// Since we compare them, we can also just "bubble sort" them.
final int middle = (start + end) / 2;
if(comparator.compare(data.get(start), data.get(middle)) > 0) {
swap(data, start, middle);
}
if(comparator.compare(data.get(start), data.get(end - 1)) > 0) {
swap(data, start, end - 1);
}
if(comparator.compare(data.get(middle), data.get(end - 1)) > 0) {
swap(data, middle, end - 1);
}
// TODO: use more candidates for larger arrays?
final T pivot = data.get(middle);
// Move middle element out of the way, just before end
// (Since we already know that "end" is bigger)
swap(data, middle, end - 2);
// Begin partitioning
int i = start + 1, j = end - 3;
// This is classic quicksort stuff
while(true) {
while(comparator.compare(data.get(i), pivot) <= 0 && i <= j) {
i++;
}
while(comparator.compare(data.get(j), pivot) >= 0 && j >= i) {
j
}
if(i >= j) {
break;
}
swap(data, i, j);
}
// Move pivot (former middle element) back into the appropriate place
swap(data, i, end - 2);
// In contrast to quicksort, we only need to recurse into the half we are
// interested in. Instead of recursion we now use iteration.
if(rank < i) {
end = i;
}
else if(rank > i) {
start = i + 1;
}
else {
break;
}
} // Loop until rank==i
}
/**
* Sort a small array using repetitive insertion sort.
*
* @param <T> object type
* @param data Data to sort
* @param start Interval start
* @param end Interval end
*/
private static <T> void insertionSort(List<T> data, Comparator<? super T> comparator, int start, int end) {
for(int i = start + 1; i < end; i++) {
for(int j = i; j > start && comparator.compare(data.get(j - 1), data.get(j)) > 0; j
swap(data, j, j - 1);
}
}
}
/**
* QuickSelect is essentially quicksort, except that we only "sort" that half
* of the array that we are interested in.
*
* Note: the array is <b>modified</b> by this.
*
* @param data Data to process
* @param comparator Comparator to use
* @param rank Rank position that we are interested in (integer!)
* @return Value at the given rank
*/
public static DBID quickSelect(ArrayModifiableDBIDs data, Comparator<? super DBIDRef> comparator, int rank) {
quickSelect(data, comparator, 0, data.size(), rank);
return data.get(rank);
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* Note: the array is <b>modified</b> by this.
*
* @param data Data to process
* @param comparator Comparator to use
* @return Median value
*/
public static DBID median(ArrayModifiableDBIDs data, Comparator<? super DBIDRef> comparator) {
return median(data, comparator, 0, data.size());
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* On an odd length, it will return the lower element.
*
* Note: the array is <b>modified</b> by this.
*
* @param data Data to process
* @param comparator Comparator to use
* @param begin Begin of valid values
* @param end End of valid values (exclusive!)
* @return Median value
*/
public static DBID median(ArrayModifiableDBIDs data, Comparator<? super DBIDRef> comparator, int begin, int end) {
final int length = end - begin;
assert (length > 0);
// Integer division is "floor" since we are non-negative.
final int left = begin + (length - 1) / 2;
quickSelect(data, comparator, begin, end, left);
return data.get(left);
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* Note: the array is <b>modified</b> by this.
*
* @param data Data to process
* @param comparator Comparator to use
* @param quant Quantile to compute
* @return Value at quantile
*/
public static DBID quantile(ArrayModifiableDBIDs data, Comparator<? super DBIDRef> comparator, double quant) {
return quantile(data, comparator, 0, data.size(), quant);
}
/**
* Compute the median of an array efficiently using the QuickSelect method.
*
* It will prefer the lower element.
*
* Note: the array is <b>modified</b> by this.
*
* @param data Data to process
* @param comparator Comparator to use
* @param begin Begin of valid values
* @param end End of valid values (inclusive!)
* @param quant Quantile to compute
* @return Value at quantile
*/
public static DBID quantile(ArrayModifiableDBIDs data, Comparator<? super DBIDRef> comparator, int begin, int end, double quant) {
final int length = end - begin;
assert (length > 0) : "Quantile on empty set?";
// Integer division is "floor" since we are non-negative.
final double dleft = begin + (length - 1) * quant;
final int ileft = (int) Math.floor(dleft);
quickSelect(data, comparator, begin, end, ileft);
return data.get(ileft);
}
/**
* QuickSelect is essentially quicksort, except that we only "sort" that half
* of the array that we are interested in.
*
* @param data Data to process
* @param comparator Comparator to use
* @param start Interval start
* @param end Interval end (inclusive)
* @param rank rank position we are interested in (starting at 0)
*/
public static void quickSelect(ArrayModifiableDBIDs data, Comparator<? super DBIDRef> comparator, int start, int end, int rank) {
while(true) {
// Optimization for small arrays
// This also ensures a minimum size below
if(start + SMALL > end) {
insertionSort(data, comparator, start, end);
return;
}
// Pick pivot from three candidates: start, middle, end
// Since we compare them, we can also just "bubble sort" them.
final int middle = (start + end) / 2;
if(comparator.compare(data.get(start), data.get(middle)) > 0) {
data.swap(start, middle);
}
if(comparator.compare(data.get(start), data.get(end - 1)) > 0) {
data.swap(start, end - 1);
}
if(comparator.compare(data.get(middle), data.get(end - 1)) > 0) {
data.swap(middle, end - 1);
}
// TODO: use more candidates for larger arrays?
final DBID pivot = data.get(middle);
// Move middle element out of the way, just before end
// (Since we already know that "end" is bigger)
data.swap(middle, end - 2);
// Begin partitioning
int i = start + 1, j = end - 3;
DBIDArrayIter refi = data.iter(), refj = data.iter();
refi.seek(i);
refj.seek(j);
// This is classic quicksort stuff
while(true) {
while(comparator.compare(refi, pivot) <= 0 && i <= j) {
i++;
refi.advance();
}
while(comparator.compare(refj, pivot) >= 0 && j >= i) {
j
refj.retract();
}
if(i >= j) {
break;
}
data.swap(i, j);
}
// Move pivot (former middle element) back into the appropriate place
data.swap(i, end - 2);
// In contrast to quicksort, we only need to recurse into the half we are
// interested in. Instead of recursion we now use iteration.
if(rank < i) {
end = i;
}
else if(rank > i) {
start = i + 1;
}
else {
break;
}
} // Loop until rank==i
}
/**
* Sort a small array using repetitive insertion sort.
*
* @param data Data to sort
* @param start Interval start
* @param end Interval end
*/
private static void insertionSort(ArrayModifiableDBIDs data, Comparator<? super DBIDRef> comparator, int start, int end) {
DBIDArrayIter iter1 = data.iter(), iter2 = data.iter();
for(int i = start + 1; i < end; i++) {
iter1.seek(i - 1);
iter2.seek(i);
for(int j = i; j > start; j--, iter1.retract(), iter2.retract()) {
if(comparator.compare(iter1, iter2) > 0) {
break;
}
data.swap(j, j - 1);
}
}
}
}
|
package rxreddit.api;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.File;
import java.util.List;
import java.util.Map;
import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.HttpException;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.functions.Func1;
import rxreddit.RxRedditUtil;
import rxreddit.model.AbsComment;
import rxreddit.model.AccessToken;
import rxreddit.model.Comment;
import rxreddit.model.Friend;
import rxreddit.model.FriendInfo;
import rxreddit.model.Listing;
import rxreddit.model.ListingResponse;
import rxreddit.model.MoreChildrenResponse;
import rxreddit.model.Subreddit;
import rxreddit.model.UserAccessToken;
import rxreddit.model.UserIdentity;
import rxreddit.model.UserIdentityListing;
import rxreddit.model.UserSettings;
public class RedditService implements IRedditService {
public static final String BASE_URL = "https://oauth.reddit.com";
private RedditAPI mAPI;
private IRedditAuthService mRedditAuthService;
protected RedditService(
String baseUrl, String baseAuthUrl, String redditAppId, String redirectUri,
String deviceId, String userAgent, AccessTokenManager atm, int cacheSizeBytes, File cacheFile,
boolean loggingEnabled) {
mRedditAuthService = new RedditAuthService(
baseAuthUrl, redditAppId, redirectUri, deviceId, userAgent, atm, loggingEnabled);
mAPI = buildApi(baseUrl, userAgent, cacheSizeBytes, cacheFile, loggingEnabled);
}
@Override
public String getRedirectUri() {
return mRedditAuthService.getRedirectUri();
}
@Override
public String getAuthorizationUrl() {
return mRedditAuthService.getAuthorizationUrl();
}
@Override
public boolean isUserAuthorized() {
return mRedditAuthService.isUserAuthorized();
}
@Override
public Observable<UserAccessToken> processAuthenticationCallback(String callbackUrl) {
Map<String, String> params;
try {
params = RxRedditUtil.getQueryParametersFromUrl(callbackUrl);
} catch (Exception e) {
return Observable.error(new IllegalArgumentException("invalid callback url: " + callbackUrl));
}
if (params.containsKey("error")) {
return Observable.error(
new IllegalStateException("Error during user authentication: " + params.get("error"))
);
}
String authCode = params.get("code");
if (authCode == null) {
return Observable.error(new IllegalArgumentException("invalid callback url: " + callbackUrl));
}
String state = params.get("state");
return mRedditAuthService.onAuthCodeReceived(authCode, state);
}
@Override
public Observable<UserIdentity> getUserIdentity() {
return requireUserAccessToken().flatMap(
token -> mAPI.getUserIdentity()
.flatMap(responseToBody())
);
}
@Override
public Observable<UserSettings> getUserSettings() {
return requireUserAccessToken().flatMap(
token -> mAPI.getUserSettings()
.flatMap(responseToBody())
);
}
@Override
public Observable<Void> updateUserSettings(Map<String, String> settings) {
String json = new Gson().toJson(settings);
RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);
return requireUserAccessToken().flatMap(
token ->
mAPI.updateUserSettings(body)
.flatMap(responseToBody())
);
}
@Override
public Observable<ListingResponse> getSubreddits(String where, String before, String after) {
return requireUserAccessToken().flatMap(
token -> mAPI.getSubreddits(where, before, after)
.flatMap(responseToBody())
);
}
@Override
public Observable<ListingResponse> loadLinks(
String subreddit, String sort, String timespan, String before, String after) {
return requireAccessToken().flatMap(
token -> {
String resolvedSort = sort != null ? sort : "hot";
return mAPI.getLinks(resolvedSort, subreddit, timespan, before, after)
.flatMap(responseToBody());
}
);
}
@Override
public Observable<List<ListingResponse>> loadLinkComments(
String subreddit, String article, String sort, String commentId) {
if (subreddit == null) {
return Observable.error(new IllegalArgumentException("subreddit == null"));
}
if (article == null) {
return Observable.error(new IllegalArgumentException("article == null"));
}
return requireAccessToken().flatMap(
token -> mAPI.getComments(subreddit, article, sort, commentId)
.flatMap(responseToBody())
);
}
@Override
public Observable<MoreChildrenResponse> loadMoreChildren(
String linkId, List<String> childrenIds, String sort) {
if (linkId == null) {
return Observable.error(new IllegalArgumentException("linkId == null"));
}
if (childrenIds == null || childrenIds.size() == 0) {
return Observable.error(new IllegalArgumentException("no comment IDs provided"));
}
return requireAccessToken().flatMap(
token -> mAPI.getMoreChildren("t3_" + linkId, RxRedditUtil.join(",", childrenIds), sort)
.flatMap(responseToBody())
);
}
@Override
public Observable<UserIdentity> getUserInfo(String username) {
return requireAccessToken().flatMap(
token -> mAPI.getUserInfo(username)
.flatMap(responseToBody())
.map(UserIdentityListing::getUser)
);
}
@Override
public Observable<FriendInfo> getFriendInfo(String username) {
return requireUserAccessToken().flatMap(
token -> mAPI.getFriendInfo(username)
.flatMap(responseToBody())
);
}
@Override
public Observable<List<Listing>> getUserTrophies(String username) {
// TODO: This should return a List of Trophies instead of Listings
if (username == null) {
return Observable.error(new IllegalArgumentException("username == null"));
}
return requireAccessToken().flatMap(
token -> mAPI.getUserTrophies(username)
.flatMap(responseToBody())
.map(trophyResponse -> trophyResponse.getData().getTrophies())
);
}
@Override
public Observable<ListingResponse> loadUserProfile(
String show, String username, String sort, String timespan, String before, String after) {
if (show == null) {
return Observable.error(new IllegalArgumentException("show == null"));
}
if (username == null) {
return Observable.error(new IllegalArgumentException("username == null"));
}
return requireAccessToken().flatMap(
token -> mAPI.getUserProfile(show, username, sort, timespan, before, after)
.flatMap(responseToBody())
);
}
@Override
public Observable<Void> addFriend(String username) {
if (username == null)
return Observable.error(new IllegalArgumentException("username == null"));
RequestBody body = RequestBody.create(MediaType.parse("application/json"), "{}");
return requireUserAccessToken().flatMap(
token -> mAPI.addFriend(username, body)
.flatMap(responseToBody())
);
}
@Override
public Observable<Void> deleteFriend(String username) {
return requireUserAccessToken().flatMap(
token -> mAPI.deleteFriend(username)
.flatMap(responseToBody())
);
}
@Override
public Observable<Void> saveFriendNote(String username, String note) {
if (RxRedditUtil.isEmpty(note)) {
return Observable.error(new IllegalArgumentException("user note should be non-empty"));
}
String json = new Gson().toJson(new Friend(note));
return requireUserAccessToken().flatMap(token ->
mAPI.addFriend(username, RequestBody.create(MediaType.parse("application/json"), json))
.flatMap(responseToBody())
);
}
@Override
public Observable<Subreddit> getSubredditInfo(String subreddit) {
if (subreddit == null) {
return Observable.error(new IllegalArgumentException("subreddit == null"));
}
return requireAccessToken().flatMap(
token -> mAPI.getSubredditInfo(subreddit)
.flatMap(responseToBody())
);
}
@Override
public Observable<Void> vote(String fullname, int direction) {
if (fullname == null) {
return Observable.error(new IllegalArgumentException("fullname == null"));
}
return requireUserAccessToken().flatMap(token ->
mAPI.vote(fullname, direction)
.flatMap(responseToBody())
);
}
@Override
public Observable<Void> save(String fullname, String category, boolean toSave) {
if (fullname == null) {
return Observable.error(new IllegalArgumentException("fullname == null"));
}
if (toSave) { // Save
return requireUserAccessToken().flatMap(
token -> mAPI.save(fullname, category)
.flatMap(responseToBody())
);
} else { // Unsave
return requireUserAccessToken().flatMap(
token -> mAPI.unsave(fullname)
.flatMap(responseToBody())
);
}
}
@Override
public Observable<Void> hide(String fullname, boolean toHide) {
if (fullname == null) {
return Observable.error(new IllegalArgumentException("fullname == null"));
}
if (toHide) { // Hide
return requireUserAccessToken().flatMap(
token -> mAPI.hide(fullname)
.flatMap(responseToBody())
);
} else { // Unhide
return requireUserAccessToken().flatMap(
token -> mAPI.unhide(fullname)
.flatMap(responseToBody())
);
}
}
@Override
public Observable<Void> report(String id, String reason) {
return Observable.error(new UnsupportedOperationException());
}
@Override
public Observable<Comment> addComment(String parentId, String text) {
if (parentId == null) {
return Observable.error(new IllegalArgumentException("parentId == null"));
}
if (text == null) {
return Observable.error(new IllegalArgumentException("text == null"));
}
return requireUserAccessToken().flatMap(
token -> mAPI.addComment(parentId, text)
.flatMap(responseToBody())
.map(response -> {
List<String> errors = response.getErrors();
if (errors.size() > 0) {
throw new IllegalStateException("an error occurred: " + response.getErrors().get(0));
}
return response.getComment();
})
);
}
@Override
public Observable<ListingResponse> getInbox(String show, String before, String after) {
if (show == null) {
return Observable.error(new IllegalArgumentException("show == null"));
}
return requireUserAccessToken().flatMap(
token -> mAPI.getInbox(show, before, after)
.flatMap(responseToBody())
);
}
@Override
public Observable<Void> markAllMessagesRead() {
return requireUserAccessToken().flatMap(
token -> mAPI.markAllMessagesRead()
.flatMap(responseToBody())
);
}
@Override
public Observable<Void> markMessagesRead(String commaSeparatedFullnames) {
// TODO: This should take a List of message fullnames and construct the parameter
return requireUserAccessToken().flatMap(
token -> mAPI.markMessagesRead(commaSeparatedFullnames)
.flatMap(responseToBody())
);
}
@Override
public Observable<Void> markMessagesUnread(String commaSeparatedFullnames) {
// TODO: This should take a List of message fullnames and construct the parameter
return requireUserAccessToken().flatMap(
token -> mAPI.markMessagesUnread(commaSeparatedFullnames)
.flatMap(responseToBody())
);
}
@Override
public Observable<Void> revokeAuthentication() {
return mRedditAuthService.revokeUserAuthentication();
}
protected Observable<AccessToken> requireAccessToken() {
return mRedditAuthService.refreshAccessToken();
}
protected Observable<UserAccessToken> requireUserAccessToken() {
return mRedditAuthService.refreshUserAccessToken();
}
private RedditAPI buildApi(String baseUrl, String userAgent, int cacheSizeBytes, File cachePath, boolean loggingEnabled) {
Retrofit restAdapter = new Retrofit.Builder()
.client(getOkHttpClient(userAgent, cacheSizeBytes, cachePath, loggingEnabled))
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(getGson()))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
return restAdapter.create(RedditAPI.class);
}
protected OkHttpClient getOkHttpClient(String userAgent, int cacheSizeBytes, File cachePath, boolean loggingEnabled) {
OkHttpClient.Builder builder = new OkHttpClient.Builder()
.addNetworkInterceptor(new UserAgentInterceptor(userAgent))
.addNetworkInterceptor(new RawResponseInterceptor())
.addNetworkInterceptor(getUserAuthInterceptor());
if (cacheSizeBytes > 0) {
builder.cache(new Cache(cachePath, cacheSizeBytes));
}
if (loggingEnabled) {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
builder.addInterceptor(loggingInterceptor);
}
return builder.build();
}
public Gson getGson() {
return new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.registerTypeAdapter(ListingResponse.class, new ListingResponseDeserializer())
.registerTypeAdapter(Listing.class, new ListingDeserializer())
.registerTypeAdapter(AbsComment.class, new CommentDeserializer())
.create();
}
protected IRedditAuthService getAuthService() {
return mRedditAuthService;
}
private Interceptor getUserAuthInterceptor() {
return chain -> {
Request originalRequest = chain.request();
AccessToken token = mRedditAuthService.getAccessToken();
Request newRequest = originalRequest.newBuilder()
.removeHeader("Authorization")
.addHeader("Authorization", "bearer " + token.getToken())
.build();
return chain.proceed(newRequest);
};
}
public static <T> Func1<Response<T>, Observable<T>> responseToBody() {
return response -> {
if (!response.isSuccessful()) {
return Observable.error(new HttpException(response));
}
return Observable.just(response.body());
};
}
public static final class Builder {
private String mBaseUrl = "https://oauth.reddit.com/";
private String mBaseAuthUrl = "https:
private String mAppId;
private String mRedirectUri;
private String mDeviceId;
private String mUserAgent;
private AccessTokenManager mAccessTokenManager = AccessTokenManager.NONE;
private int mCacheSizeBytes = 0;
private File mCacheFile = null;
private boolean mLoggingEnabled = false;
public Builder baseUrl(String baseUrl) {
mBaseUrl = baseUrl;
return this;
}
public Builder baseAuthUrl(String baseAuthUrl) {
mBaseAuthUrl = baseAuthUrl;
return this;
}
public Builder appId(String appId) {
mAppId = appId;
return this;
}
public Builder redirectUri(String redirectUri) {
mRedirectUri = redirectUri;
return this;
}
public Builder deviceId(String deviceId) {
mDeviceId = deviceId;
return this;
}
public Builder userAgent(String userAgent) {
mUserAgent = userAgent;
return this;
}
public Builder accessTokenManager(AccessTokenManager accessTokenManager) {
mAccessTokenManager = accessTokenManager;
return this;
}
public Builder cache(int sizeBytes, File path) {
mCacheSizeBytes = sizeBytes;
mCacheFile = path;
return this;
}
public Builder loggingEnabled(boolean enabled) {
mLoggingEnabled = enabled;
return this;
}
public RedditService build() {
if (mAppId == null) throw new IllegalStateException("app id must be set");
if (mRedirectUri == null) throw new IllegalStateException("redirect uri must be set");
if (mDeviceId == null) throw new IllegalStateException("device id must be set");
if (mUserAgent == null) throw new IllegalStateException("user agent must be set");
return new RedditService(
mBaseUrl, mBaseAuthUrl, mAppId, mRedirectUri, mDeviceId, mUserAgent,
mAccessTokenManager, mCacheSizeBytes, mCacheFile, mLoggingEnabled);
}
}
}
|
package de.ust.skill.common.java.internal;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Set;
import java.util.concurrent.Semaphore;
import de.ust.skill.common.java.api.SkillException;
import de.ust.skill.common.java.internal.fieldTypes.ConstantI16;
import de.ust.skill.common.java.internal.fieldTypes.ConstantI32;
import de.ust.skill.common.java.internal.fieldTypes.ConstantI64;
import de.ust.skill.common.java.internal.fieldTypes.ConstantI8;
import de.ust.skill.common.java.internal.fieldTypes.ConstantLengthArray;
import de.ust.skill.common.java.internal.fieldTypes.ConstantV64;
import de.ust.skill.common.java.internal.fieldTypes.MapType;
import de.ust.skill.common.java.internal.fieldTypes.SingleArgumentType;
import de.ust.skill.common.java.internal.parts.BulkChunk;
import de.ust.skill.common.java.internal.parts.Chunk;
import de.ust.skill.common.java.internal.parts.SimpleChunk;
import de.ust.skill.common.jvm.streams.FileOutputStream;
import de.ust.skill.common.jvm.streams.MappedOutStream;
import de.ust.skill.common.jvm.streams.OutStream;
abstract public class SerializationFunctions {
/**
* Data structure used for parallel serialization scheduling
*/
protected static final class Task implements Runnable {
public final FieldDeclaration<?, ?> f;
public final long begin;
public final long end;
MappedOutStream outMap;
LinkedList<SkillException> writeErrors;
Semaphore barrier;
Task(FieldDeclaration<?, ?> f, long begin, long end) {
this.f = f;
this.begin = begin;
this.end = end;
}
@Override
public void run() {
try {
Chunk c = f.lastChunk();
if (c instanceof SimpleChunk) {
int i = (int) ((SimpleChunk) c).bpo;
f.wsc(i, i + (int) c.count, outMap);
} else
f.wbc((BulkChunk) c, outMap);
} catch (SkillException e) {
synchronized (writeErrors) {
writeErrors.add(e);
}
} catch (IOException e) {
synchronized (writeErrors) {
writeErrors.add(new SkillException("failed to write field " + f.toString(), e));
}
} catch (Throwable e) {
synchronized (writeErrors) {
writeErrors.add(new SkillException("unexpected failure while writing field " + f.toString(), e));
}
} finally {
// ensure that writer can terminate, errors will be
// printed to command line anyway, and we wont
// be able to recover, because errors can only happen if
// the skill implementation itself is
// broken
barrier.release();
}
}
}
protected final SkillState state;
protected final HashMap<String, Integer> stringIDs;
public SerializationFunctions(SkillState state) {
this.state = state;
StringPool strings = (StringPool) state.Strings();
for (StoragePool<?, ?> p : state.types) {
strings.add(p.name);
for (FieldDeclaration<?, ?> f : p.dataFields) {
strings.add(f.name);
// collect strings
switch (f.type.typeID) {
// string
case 14:
for (SkillObject i : p)
strings.add((String) i.get(f));
break;
// container<string>
case 15:
case 17:
case 18:
case 19:
if (((SingleArgumentType<?, ?>) (f.type)).groundType.typeID == 14) {
for (SkillObject i : p) {
@SuppressWarnings("unchecked")
Collection<String> xs = (Collection<String>) i.get(f);
for (String s : xs)
strings.add(s);
}
}
break;
case 20:
MapType<?, ?> type = (MapType<?, ?>) f.type;
// simple maps
boolean k, v;
if ((k = (type.keyType.typeID == 14)) | (v = (type.valueType.typeID == 14))) {
for (SkillObject i : p) {
HashMap<?, ?> xs = (HashMap<?, ?>) i.get(f);
if (null != xs) {
if (k)
for (String s : (Set<String>) xs.keySet())
strings.add(s);
if (v)
for (String s : (Collection<String>) xs.values())
strings.add(s);
}
}
}
// @note overlap is intended
// nested maps
if (type.valueType.typeID == 20) {
MapType<?, ?> nested = (MapType<?, ?>) type.valueType;
if (nested.keyType.typeID == 14 || nested.valueType.typeID == 14 || nested.valueType.typeID == 20) {
for (SkillObject i : p) {
collectNestedStrings(strings, type, (HashMap<?, ?>) i.get(f));
}
}
}
break;
default:
// nothing important
}
/**
* ensure that lazy fields have been loaded
*/
if (f instanceof LazyField<?, ?>)
((LazyField<?, ?>) f).ensureLoaded();
}
}
/**
* check consistency of the state, now that we aggregated all instances
*/
state.check();
stringIDs = state.stringType.resetIDs();
}
private static void collectNestedStrings(StringPool strings, MapType<?, ?> type, HashMap<?, ?> xs) {
if (null != xs) {
if (type.keyType.typeID == 14)
for (String s : (Set<String>) xs.keySet())
strings.add(s);
if (type.valueType.typeID == 14)
for (String s : (Collection<String>) xs.values())
strings.add(s);
if (type.valueType.typeID == 20)
for (HashMap<?, ?> s : (Collection<HashMap<?, ?>>) xs.values())
collectNestedStrings(strings, (MapType<?, ?>) type.valueType, s);
}
}
/**
* TODO serialization of restrictions
*/
protected static final void restrictions(StoragePool<?, ?> p, OutStream out) throws IOException {
out.i8((byte) 0);
}
/**
* TODO serialization of restrictions
*/
protected static final void restrictions(FieldDeclaration<?, ?> f, OutStream out) throws IOException {
out.i8((byte) 0);
}
/**
* serialization of types is fortunately independent of state, because field
* types know their ID
*/
protected static final void writeType(FieldType<?> t, OutStream out) throws IOException {
switch (t.typeID) {
case 0:
out.i8((byte) 0);
out.i8(((ConstantI8) t).value);
return;
case 1:
out.i8((byte) 1);
out.i16(((ConstantI16) t).value);
return;
case 2:
out.i8((byte) 2);
out.i32(((ConstantI32) t).value);
return;
case 3:
out.i8((byte) 3);
out.i64(((ConstantI64) t).value);
return;
case 4:
out.i8((byte) 4);
out.v64(((ConstantV64) t).value);
return;
case 15:
out.i8((byte) 0x0F);
out.v64(((ConstantLengthArray<?>) t).length);
out.v64(((SingleArgumentType<?, ?>) t).groundType.typeID);
return;
case 17:
case 18:
case 19:
out.i8((byte) t.typeID);
out.v64(((SingleArgumentType<?, ?>) t).groundType.typeID);
return;
case 20:
out.i8((byte) 0x14);
writeType(((MapType<?, ?>) t).keyType, out);
writeType(((MapType<?, ?>) t).valueType, out);
return;
default:
out.v64(t.typeID);
return;
}
}
protected final static void writeFieldData(SkillState state, FileOutputStream out, ArrayList<Task> data, int offset,
final Semaphore barrier) throws IOException, InterruptedException {
// async reads will post their errors in this queue
final LinkedList<SkillException> writeErrors = new LinkedList<SkillException>();
MappedOutStream writeMap = out.mapBlock(offset);
for (Task t : data) {
t.outMap = writeMap.clone((int) t.begin, (int) t.end);
t.writeErrors = writeErrors;
t.barrier = barrier;
SkillState.pool.execute(t);
}
barrier.acquire(data.size());
writeMap.close();
out.close();
// report errors
for (SkillException e : writeErrors) {
e.printStackTrace();
}
if (!writeErrors.isEmpty())
throw writeErrors.peek();
// release data structures
state.stringType.clearIDs();
StoragePool.unfix(state.types);
}
}
|
package liquibase;
import liquibase.change.CheckSum;
import liquibase.change.core.RawSQLChange;
import liquibase.changelog.*;
import liquibase.changelog.filter.*;
import liquibase.changelog.visitor.*;
import liquibase.command.CommandExecutionException;
import liquibase.command.CommandFactory;
import liquibase.command.CommandResult;
import liquibase.command.core.DropAllCommand;
import liquibase.command.core.SyncHubCommand;
import liquibase.database.Database;
import liquibase.database.DatabaseConnection;
import liquibase.database.DatabaseFactory;
import liquibase.database.ObjectQuotingStrategy;
import liquibase.database.core.MSSQLDatabase;
import liquibase.diff.DiffGeneratorFactory;
import liquibase.diff.DiffResult;
import liquibase.diff.compare.CompareControl;
import liquibase.diff.output.changelog.DiffToChangeLog;
import liquibase.exception.DatabaseException;
import liquibase.exception.LiquibaseException;
import liquibase.exception.LockException;
import liquibase.exception.UnexpectedLiquibaseException;
import liquibase.executor.Executor;
import liquibase.executor.ExecutorService;
import liquibase.executor.LoggingExecutor;
import liquibase.hub.HubService;
import liquibase.hub.HubServiceFactory;
import liquibase.hub.listener.HubChangeExecListener;
import liquibase.hub.model.Environment;
import liquibase.hub.model.HubChangeLog;
import liquibase.hub.model.Operation;
import liquibase.hub.model.OperationEvent;
import liquibase.lockservice.DatabaseChangeLogLock;
import liquibase.lockservice.LockService;
import liquibase.lockservice.LockServiceFactory;
import liquibase.logging.Logger;
import liquibase.parser.ChangeLogParser;
import liquibase.parser.ChangeLogParserFactory;
import liquibase.resource.InputStreamList;
import liquibase.resource.ResourceAccessor;
import liquibase.serializer.ChangeLogSerializer;
import liquibase.snapshot.DatabaseSnapshot;
import liquibase.snapshot.InvalidExampleException;
import liquibase.snapshot.SnapshotControl;
import liquibase.snapshot.SnapshotGeneratorFactory;
import liquibase.statement.core.RawSqlStatement;
import liquibase.statement.core.UpdateStatement;
import liquibase.structure.DatabaseObject;
import liquibase.structure.core.Catalog;
import liquibase.util.LiquibaseUtil;
import liquibase.util.StreamUtil;
import liquibase.util.StringUtil;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Writer;
import java.text.DateFormat;
import java.util.*;
import static java.util.ResourceBundle.getBundle;
/**
* Primary facade class for interacting with Liquibase.
* The built in command line, Ant, Maven and other ways of running Liquibase are wrappers around methods in this class.
*/
public class Liquibase implements AutoCloseable {
private static final Logger LOG = Scope.getCurrentScope().getLog(Liquibase.class);
protected static final int CHANGESET_ID_NUM_PARTS = 3;
protected static final int CHANGESET_ID_AUTHOR_PART = 2;
protected static final int CHANGESET_ID_CHANGESET_PART = 1;
protected static final int CHANGESET_ID_CHANGELOG_PART = 0;
private static ResourceBundle coreBundle = getBundle("liquibase/i18n/liquibase-core");
protected static final String MSG_COULD_NOT_RELEASE_LOCK = coreBundle.getString("could.not.release.lock");
protected Database database;
private DatabaseChangeLog databaseChangeLog;
private String changeLogFile;
private ResourceAccessor resourceAccessor;
private ChangeLogParameters changeLogParameters;
private ChangeExecListener changeExecListener;
private ChangeLogSyncListener changeLogSyncListener;
private UUID hubEnvironmentId;
/**
* Creates a Liquibase instance for a given DatabaseConnection. The Database instance used will be found with {@link DatabaseFactory#findCorrectDatabaseImplementation(liquibase.database.DatabaseConnection)}
*
* @see DatabaseConnection
* @see Database
* @see #Liquibase(String, liquibase.resource.ResourceAccessor, liquibase.database.Database)
* @see ResourceAccessor
*/
public Liquibase(String changeLogFile, ResourceAccessor resourceAccessor, DatabaseConnection conn)
throws LiquibaseException {
this(changeLogFile, resourceAccessor, DatabaseFactory.getInstance().findCorrectDatabaseImplementation(conn));
}
/**
* Creates a Liquibase instance. The changeLogFile parameter must be a path that can be resolved by the passed
* ResourceAccessor. If windows style path separators are used for the changeLogFile, they will be standardized to
* unix style for better cross-system compatibility.
*
* @see DatabaseConnection
* @see Database
* @see ResourceAccessor
*/
public Liquibase(String changeLogFile, ResourceAccessor resourceAccessor, Database database) {
if (changeLogFile != null) {
// Convert to STANDARD / if using absolute path on windows:
this.changeLogFile = changeLogFile.replace('\\', '/');
}
this.resourceAccessor = resourceAccessor;
this.changeLogParameters = new ChangeLogParameters(database);
this.database = database;
}
public Liquibase(DatabaseChangeLog changeLog, ResourceAccessor resourceAccessor, Database database) {
this.databaseChangeLog = changeLog;
if (changeLog != null) {
this.changeLogFile = changeLog.getPhysicalFilePath();
}
if (this.changeLogFile != null) {
// Convert to STANDARD "/" if using an absolute path on Windows:
changeLogFile = changeLogFile.replace('\\', '/');
}
this.resourceAccessor = resourceAccessor;
this.database = database;
this.changeLogParameters = new ChangeLogParameters(database);
}
public UUID getHubEnvironmentId() {
return hubEnvironmentId;
}
public void setHubEnvironmentId(UUID hubEnvironmentId) {
this.hubEnvironmentId = hubEnvironmentId;
}
/**
* Return the change log file used by this Liquibase instance.
*/
public String getChangeLogFile() {
return changeLogFile;
}
/**
* Return the log used by this Liquibase instance.
*/
public Logger getLog() {
return LOG;
}
/**
* Returns the ChangeLogParameters container used by this Liquibase instance.
*/
public ChangeLogParameters getChangeLogParameters() {
return changeLogParameters;
}
/**
* Returns the Database used by this Liquibase instance.
*/
public Database getDatabase() {
return database;
}
/**
* Return ResourceAccessor used by this Liquibase instance.
*/
public ResourceAccessor getResourceAccessor() {
return resourceAccessor;
}
/**
* Convience method for {@link #update(Contexts)} that constructs the Context object from the passed string.
*/
public void update(String contexts) throws LiquibaseException {
this.update(new Contexts(contexts));
}
/**
* Executes Liquibase "update" logic which ensures that the configured {@link Database} is up to date according to
* the configured changelog file. To run in "no context mode", pass a null or empty context object.
*/
public void update(Contexts contexts) throws LiquibaseException {
update(contexts, new LabelExpression());
}
public void update(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException {
update(contexts, labelExpression, true);
}
public void update(Contexts contexts, LabelExpression labelExpression, boolean checkLiquibaseTables) throws LiquibaseException {
Date startTime = new Date();
runInScope(() -> {
LockService lockService = LockServiceFactory.getInstance().getLockService(database);
lockService.waitForLock();
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
final HubService hubService = Scope.getCurrentScope().getSingleton(HubServiceFactory.class).getService();
Operation updateOperation = null;
try {
DatabaseChangeLog changeLog = getDatabaseChangeLog();
if (checkLiquibaseTables) {
checkLiquibaseTables(true, changeLog, contexts, labelExpression);
}
ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId();
changeLog.validate(database, contexts, labelExpression);
ChangeLogIterator changeLogIterator = getStandardChangelogIterator(contexts, labelExpression, changeLog);
if (hubService.isOnline() && changeLog.getChangeLogId() != null) {
Environment environment;
if (Liquibase.this.hubEnvironmentId == null) {
HubChangeLog hubChangeLog = hubService.getChangeLog(UUID.fromString(changeLog.getChangeLogId()));
Environment exampleEnvironment = new Environment();
exampleEnvironment.setPrj(hubChangeLog.getPrj());
exampleEnvironment.setJdbcUrl(Liquibase.this.database.getConnection().getURL());
environment = hubService.getEnvironment(exampleEnvironment, true);
Liquibase.this.hubEnvironmentId = environment.getId();
} else {
environment = hubService.getEnvironment(new Environment().setId(Liquibase.this.hubEnvironmentId), true);
}
syncHub();
final HubChangeLog hubChangeLog = hubService.getChangeLog(UUID.fromString(changeLog.getChangeLogId()));
updateOperation = hubService.createOperation("UPDATE", hubChangeLog, environment, null);
try {
if (hubService.isOnline()) {
hubService.sendOperationEvent(updateOperation, new OperationEvent()
.setEventType("START")
.setStartDate(startTime)
.setOperationEventStatus(
new OperationEvent.OperationEventStatus()
.setOperationEventStatusType("PASS")
.setStatusMessage("Update operation started successfully")
)
);
}
} catch (LiquibaseException e) {
Scope.getCurrentScope().getLog(getClass()).warning(e.getMessage(), e);
}
if (changeExecListener != null) {
throw new RuntimeException("ChangeExecListener already defined");
}
changeExecListener = new HubChangeExecListener(updateOperation);
}
changeLogIterator.run(createUpdateVisitor(), new RuntimeEnvironment(database, contexts, labelExpression));
try {
if (hubService.isOnline()) {
hubService.sendOperationEvent(updateOperation, new OperationEvent()
.setEventType("COMPLETE")
.setStartDate(startTime)
.setEndDate(new Date())
.setOperationEventStatus(
new OperationEvent.OperationEventStatus()
.setOperationEventStatusType("PASS")
.setStatusMessage("Update operation completed successfully")
)
);
}
} catch (LiquibaseException e) {
Scope.getCurrentScope().getLog(getClass()).warning(e.getMessage(), e);
}
} catch (Throwable e) {
try {
if (hubService.isOnline()) {
hubService.sendOperationEvent(updateOperation, new OperationEvent()
.setEventType("COMPLETE")
.setStartDate(startTime)
.setEndDate(new Date())
.setOperationEventStatus(
new OperationEvent.OperationEventStatus()
.setOperationEventStatusType("FAIL")
.setStatusMessage("Update operation completed with errors")
)
);
}
} catch (LiquibaseException serviceException) {
Scope.getCurrentScope().getLog(getClass()).warning(e.getMessage(), serviceException);
}
throw e;
} finally {
database.setObjectQuotingStrategy(ObjectQuotingStrategy.LEGACY);
try {
lockService.releaseLock();
} catch (LockException e) {
LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
}
resetServices();
}
});
}
public void syncHub() {
final SyncHubCommand syncHub = (SyncHubCommand) CommandFactory.getInstance().getCommand("syncHub");
syncHub.setChangeLogFile(changeLogFile);
syncHub.setUrl(database.getConnection().getURL());
syncHub.setHubEnvironmentId(Objects.toString(hubEnvironmentId));
syncHub.setDatabase(database);
syncHub.setFailIfOnline(false);
try {
syncHub.configure(Collections.singletonMap("changeLog", databaseChangeLog));
final CommandResult commandResult = syncHub.execute();
if (!commandResult.succeeded) {
Scope.getCurrentScope().getLog(getClass()).warning("Liquibase Hub sync failed: " + commandResult.message);
}
} catch (Exception e) {
Scope.getCurrentScope().getLog(getClass()).warning("Liquibase Hub sync failed: " + e.getMessage(), e);
}
}
public DatabaseChangeLog getDatabaseChangeLog() throws LiquibaseException {
if (databaseChangeLog == null && changeLogFile != null) {
ChangeLogParser parser = ChangeLogParserFactory.getInstance().getParser(changeLogFile, resourceAccessor);
databaseChangeLog = parser.parse(changeLogFile, changeLogParameters, resourceAccessor);
}
return databaseChangeLog;
}
protected UpdateVisitor createUpdateVisitor() {
return new UpdateVisitor(database, changeExecListener);
}
protected RollbackVisitor createRollbackVisitor() {
return new RollbackVisitor(database, changeExecListener);
}
protected ChangeLogIterator getStandardChangelogIterator(Contexts contexts, LabelExpression labelExpression,
DatabaseChangeLog changeLog) throws DatabaseException {
return new ChangeLogIterator(changeLog,
new ShouldRunChangeSetFilter(database),
new ContextChangeSetFilter(contexts),
new LabelChangeSetFilter(labelExpression),
new DbmsChangeSetFilter(database),
new IgnoreChangeSetFilter());
}
public void update(String contexts, Writer output) throws LiquibaseException {
this.update(new Contexts(contexts), output);
}
public void update(Contexts contexts, Writer output) throws LiquibaseException {
update(contexts, new LabelExpression(), output);
}
public void update(Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException {
update(contexts, labelExpression, output, true);
}
public void update(Contexts contexts, LabelExpression labelExpression, Writer output, boolean checkLiquibaseTables)
throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
/* We have no other choice than to save the current Executer here. */
@SuppressWarnings("squid:S1941")
Executor oldTemplate = getAndReplaceJdbcExecutor(output);
outputHeader("Update Database Script");
LockService lockService = LockServiceFactory.getInstance().getLockService(database);
lockService.waitForLock();
try {
update(contexts, labelExpression, checkLiquibaseTables);
output.flush();
} catch (IOException e) {
throw new LiquibaseException(e);
}
Scope.getCurrentScope().getSingleton(ExecutorService.class).setExecutor("jdbc", database, oldTemplate);
}
});
}
public void update(int changesToApply, String contexts) throws LiquibaseException {
update(changesToApply, new Contexts(contexts), new LabelExpression());
}
public void update(int changesToApply, Contexts contexts, LabelExpression labelExpression)
throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
LockService lockService = LockServiceFactory.getInstance().getLockService(database);
lockService.waitForLock();
try {
DatabaseChangeLog changeLog = getDatabaseChangeLog();
checkLiquibaseTables(true, changeLog, contexts, labelExpression);
ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId();
changeLog.validate(database, contexts, labelExpression);
ChangeLogIterator logIterator = new ChangeLogIterator(changeLog,
new ShouldRunChangeSetFilter(database),
new ContextChangeSetFilter(contexts),
new LabelChangeSetFilter(labelExpression),
new DbmsChangeSetFilter(database),
new IgnoreChangeSetFilter(),
new CountChangeSetFilter(changesToApply));
logIterator.run(createUpdateVisitor(), new RuntimeEnvironment(database, contexts, labelExpression));
} finally {
try {
lockService.releaseLock();
} catch (LockException e) {
LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
}
resetServices();
}
}
});
}
public void update(String tag, String contexts) throws LiquibaseException {
update(tag, new Contexts(contexts), new LabelExpression());
}
public void update(String tag, Contexts contexts) throws LiquibaseException {
update(tag, contexts, new LabelExpression());
}
public void update(String tag, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException {
if (tag == null) {
update(contexts, labelExpression);
return;
}
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
LockService lockService = LockServiceFactory.getInstance().getLockService(database);
lockService.waitForLock();
try {
DatabaseChangeLog changeLog = getDatabaseChangeLog();
checkLiquibaseTables(true, changeLog, contexts, labelExpression);
changeLog.validate(database, contexts, labelExpression);
List<RanChangeSet> ranChangeSetList = database.getRanChangeSetList();
ChangeLogIterator logIterator = new ChangeLogIterator(changeLog,
new ShouldRunChangeSetFilter(database),
new ContextChangeSetFilter(contexts),
new LabelChangeSetFilter(labelExpression),
new DbmsChangeSetFilter(database),
new IgnoreChangeSetFilter(),
new UpToTagChangeSetFilter(tag, ranChangeSetList));
logIterator.run(createUpdateVisitor(), new RuntimeEnvironment(database, contexts, labelExpression));
} finally {
try {
lockService.releaseLock();
} catch (LockException e) {
LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
}
resetServices();
}
}
});
}
public void update(int changesToApply, String contexts, Writer output) throws LiquibaseException {
this.update(changesToApply, new Contexts(contexts), new LabelExpression(), output);
}
public void update(int changesToApply, Contexts contexts, LabelExpression labelExpression, Writer output) throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
/* We have no other choice than to save the current Executer here. */
@SuppressWarnings("squid:S1941")
Executor oldTemplate = getAndReplaceJdbcExecutor(output);
outputHeader("Update " + changesToApply + " Change Sets Database Script");
update(changesToApply, contexts, labelExpression);
flushOutputWriter(output);
resetServices();
Scope.getCurrentScope().getSingleton(ExecutorService.class).setExecutor("jdbc", database, oldTemplate);
}
});
}
public void update(String tag, String contexts, Writer output) throws LiquibaseException {
update(tag, new Contexts(contexts), new LabelExpression(), output);
}
public void update(String tag, Contexts contexts, Writer output) throws LiquibaseException {
update(tag, contexts, new LabelExpression(), output);
}
public void update(String tag, Contexts contexts, LabelExpression labelExpression, Writer output)
throws LiquibaseException {
if (tag == null) {
update(contexts, labelExpression, output);
return;
}
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
/* We have no other choice than to save the current Executer here. */
@SuppressWarnings("squid:S1941")
Executor oldTemplate = getAndReplaceJdbcExecutor(output);
outputHeader("Update to '" + tag + "' Database Script");
update(tag, contexts, labelExpression);
flushOutputWriter(output);
resetServices();
Scope.getCurrentScope().getSingleton(ExecutorService.class).setExecutor("jdbc", database, oldTemplate);
}
});
}
public void outputHeader(String message) throws DatabaseException {
Executor executor = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("logging", database);
executor.comment("*********************************************************************");
executor.comment(message);
executor.comment("*********************************************************************");
executor.comment("Change Log: " + changeLogFile);
executor.comment("Ran at: " +
DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format(new Date())
);
DatabaseConnection connection = getDatabase().getConnection();
if (connection != null) {
executor.comment("Against: " + connection.getConnectionUserName() + "@" + connection.getURL());
}
executor.comment("Liquibase version: " + LiquibaseUtil.getBuildVersion());
executor.comment("*********************************************************************" +
StreamUtil.getLineSeparator()
);
if ((database instanceof MSSQLDatabase) && (database.getDefaultCatalogName() != null)) {
executor.execute(new RawSqlStatement("USE " +
database.escapeObjectName(database.getDefaultCatalogName(), Catalog.class) + ";")
);
}
}
public void rollback(int changesToRollback, String contexts, Writer output) throws LiquibaseException {
rollback(changesToRollback, null, contexts, output);
}
public void rollback(int changesToRollback, Contexts contexts, Writer output) throws LiquibaseException {
rollback(changesToRollback, null, contexts, output);
}
public void rollback(int changesToRollback, Contexts contexts, LabelExpression labelExpression, Writer output)
throws LiquibaseException {
rollback(changesToRollback, null, contexts, labelExpression, output);
}
public void rollback(int changesToRollback, String rollbackScript, String contexts, Writer output)
throws LiquibaseException {
rollback(changesToRollback, rollbackScript, new Contexts(contexts), output);
}
public void rollback(int changesToRollback, String rollbackScript, Contexts contexts, Writer output)
throws LiquibaseException {
rollback(changesToRollback, rollbackScript, contexts, new LabelExpression(), output);
}
public void rollback(int changesToRollback, String rollbackScript, Contexts contexts,
LabelExpression labelExpression, Writer output) throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
/* We have no other choice than to save the current Executer here. */
@SuppressWarnings("squid:S1941")
Executor oldTemplate = getAndReplaceJdbcExecutor(output);
outputHeader("Rollback " + changesToRollback + " Change(s) Script");
rollback(changesToRollback, rollbackScript, contexts, labelExpression);
flushOutputWriter(output);
Scope.getCurrentScope().getSingleton(ExecutorService.class).setExecutor("jdbc", database, oldTemplate);
resetServices();
}
});
}
public void rollback(int changesToRollback, String contexts) throws LiquibaseException {
rollback(changesToRollback, null, contexts);
}
public void rollback(int changesToRollback, Contexts contexts, LabelExpression labelExpression)
throws LiquibaseException {
rollback(changesToRollback, null, contexts, labelExpression);
}
public void rollback(int changesToRollback, String rollbackScript, String contexts) throws LiquibaseException {
rollback(changesToRollback, rollbackScript, new Contexts(contexts), new LabelExpression());
}
public void rollback(int changesToRollback, String rollbackScript, Contexts contexts,
LabelExpression labelExpression) throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
LockService lockService = LockServiceFactory.getInstance().getLockService(database);
lockService.waitForLock();
try {
DatabaseChangeLog changeLog = getDatabaseChangeLog();
checkLiquibaseTables(false, changeLog, contexts, labelExpression);
changeLog.validate(database, contexts, labelExpression);
ChangeLogIterator logIterator = new ChangeLogIterator(database.getRanChangeSetList(), changeLog,
new AlreadyRanChangeSetFilter(database.getRanChangeSetList()),
new ContextChangeSetFilter(contexts),
new LabelChangeSetFilter(labelExpression),
new DbmsChangeSetFilter(database),
new IgnoreChangeSetFilter(),
new CountChangeSetFilter(changesToRollback));
if (rollbackScript == null) {
logIterator.run(createRollbackVisitor(), new RuntimeEnvironment(database, contexts, labelExpression));
} else {
executeRollbackScript(rollbackScript, contexts, labelExpression);
removeRunStatus(logIterator, contexts, labelExpression);
}
} finally {
try {
lockService.releaseLock();
} catch (LockException e) {
LOG.severe("Error releasing lock", e);
}
resetServices();
}
}
});
}
protected void removeRunStatus(ChangeLogIterator logIterator, Contexts contexts, LabelExpression labelExpression)
throws LiquibaseException {
logIterator.run(new ChangeSetVisitor() {
@Override
public Direction getDirection() {
return Direction.REVERSE;
}
@Override
public void visit(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database,
Set<ChangeSetFilterResult> filterResults) throws LiquibaseException {
database.removeRanStatus(changeSet);
database.commit();
}
}, new RuntimeEnvironment(database, contexts, labelExpression));
}
protected void executeRollbackScript(String rollbackScript, Contexts contexts, LabelExpression labelExpression) throws LiquibaseException {
final Executor executor = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database);
String rollbackScriptContents;
try {
InputStreamList streams = resourceAccessor.openStreams(null, rollbackScript);
if ((streams == null) || streams.isEmpty()) {
throw new LiquibaseException("WARNING: The rollback script '" + rollbackScript + "' was not located. Please check your parameters. No rollback was performed");
} else if (streams.size() > 1) {
throw new LiquibaseException("Found multiple rollbackScripts named " + rollbackScript);
}
rollbackScriptContents = StreamUtil.readStreamAsString(streams.iterator().next());
} catch (IOException e) {
throw new LiquibaseException("Error reading rollbackScript " + executor + ": " + e.getMessage());
}
// Expand changelog properties
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
DatabaseChangeLog changelog = getDatabaseChangeLog();
rollbackScriptContents = changeLogParameters.expandExpressions(rollbackScriptContents, changelog);
RawSQLChange rollbackChange = buildRawSQLChange(rollbackScriptContents);
try {
executor.execute(rollbackChange);
} catch (DatabaseException e) {
Scope.getCurrentScope().getLog(getClass()).warning(e.getMessage());
LOG.severe("Error executing rollback script: " + e.getMessage());
if (changeExecListener != null) {
changeExecListener.runFailed(null, databaseChangeLog, database, e);
}
throw new DatabaseException("Error executing rollback script", e);
}
database.commit();
}
protected RawSQLChange buildRawSQLChange(String rollbackScriptContents) {
RawSQLChange rollbackChange = new RawSQLChange(rollbackScriptContents);
rollbackChange.setSplitStatements(true);
rollbackChange.setStripComments(true);
return rollbackChange;
}
public void rollback(String tagToRollBackTo, String contexts, Writer output) throws LiquibaseException {
rollback(tagToRollBackTo, null, contexts, output);
}
public void rollback(String tagToRollBackTo, Contexts contexts, Writer output) throws LiquibaseException {
rollback(tagToRollBackTo, null, contexts, output);
}
public void rollback(String tagToRollBackTo, Contexts contexts, LabelExpression labelExpression, Writer output)
throws LiquibaseException {
rollback(tagToRollBackTo, null, contexts, labelExpression, output);
}
public void rollback(String tagToRollBackTo, String rollbackScript, String contexts, Writer output)
throws LiquibaseException {
rollback(tagToRollBackTo, rollbackScript, new Contexts(contexts), output);
}
public void rollback(String tagToRollBackTo, String rollbackScript, Contexts contexts, Writer output)
throws LiquibaseException {
rollback(tagToRollBackTo, rollbackScript, contexts, new LabelExpression(), output);
}
public void rollback(String tagToRollBackTo, String rollbackScript, Contexts contexts,
LabelExpression labelExpression, Writer output) throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
/* We have no other choice than to save the current Executer here. */
@SuppressWarnings("squid:S1941")
Executor oldTemplate = getAndReplaceJdbcExecutor(output);
outputHeader("Rollback to '" + tagToRollBackTo + "' Script");
rollback(tagToRollBackTo, contexts, labelExpression);
flushOutputWriter(output);
Scope.getCurrentScope().getSingleton(ExecutorService.class).setExecutor("jdbc", database, oldTemplate);
resetServices();
}
public void rollback(String tagToRollBackTo, String contexts) throws LiquibaseException {
rollback(tagToRollBackTo, null, contexts);
}
public void rollback(String tagToRollBackTo, Contexts contexts) throws LiquibaseException {
rollback(tagToRollBackTo, null, contexts);
}
public void rollback(String tagToRollBackTo, Contexts contexts, LabelExpression labelExpression)
throws LiquibaseException {
rollback(tagToRollBackTo, null, contexts, labelExpression);
}
public void rollback(String tagToRollBackTo, String rollbackScript, String contexts) throws LiquibaseException {
rollback(tagToRollBackTo, rollbackScript, new Contexts(contexts));
}
public void rollback(String tagToRollBackTo, String rollbackScript, Contexts contexts) throws LiquibaseException {
rollback(tagToRollBackTo, rollbackScript, contexts, new LabelExpression());
}
public void rollback(String tagToRollBackTo, String rollbackScript, Contexts contexts,
LabelExpression labelExpression) throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
LockService lockService = LockServiceFactory.getInstance().getLockService(database);
lockService.waitForLock();
try {
DatabaseChangeLog changeLog = getDatabaseChangeLog();
checkLiquibaseTables(false, changeLog, contexts, labelExpression);
changeLog.validate(database, contexts, labelExpression);
List<RanChangeSet> ranChangeSetList = database.getRanChangeSetList();
ChangeLogIterator logIterator = new ChangeLogIterator(ranChangeSetList, changeLog,
new AfterTagChangeSetFilter(tagToRollBackTo, ranChangeSetList),
new AlreadyRanChangeSetFilter(ranChangeSetList),
new ContextChangeSetFilter(contexts),
new LabelChangeSetFilter(labelExpression),
new IgnoreChangeSetFilter(),
new DbmsChangeSetFilter(database));
if (rollbackScript == null) {
logIterator.run(createRollbackVisitor(),
new RuntimeEnvironment(database, contexts, labelExpression));
} else {
executeRollbackScript(rollbackScript, contexts, labelExpression);
removeRunStatus(logIterator, contexts, labelExpression);
}
} finally {
try {
lockService.releaseLock();
} catch (LockException e) {
LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
}
}
resetServices();
}
});
}
public void rollback(Date dateToRollBackTo, String contexts, Writer output) throws LiquibaseException {
rollback(dateToRollBackTo, null, contexts, output);
}
public void rollback(Date dateToRollBackTo, String rollbackScript, String contexts, Writer output)
throws LiquibaseException {
rollback(dateToRollBackTo, new Contexts(contexts), new LabelExpression(), output);
}
public void rollback(Date dateToRollBackTo, Contexts contexts, LabelExpression labelExpression, Writer output)
throws LiquibaseException {
rollback(dateToRollBackTo, null, contexts, labelExpression, output);
}
public void rollback(Date dateToRollBackTo, String rollbackScript, Contexts contexts,
LabelExpression labelExpression, Writer output) throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
@SuppressWarnings("squid:S1941")
Executor oldTemplate = getAndReplaceJdbcExecutor(output);
outputHeader("Rollback to " + dateToRollBackTo + " Script");
rollback(dateToRollBackTo, contexts, labelExpression);
flushOutputWriter(output);
Scope.getCurrentScope().getSingleton(ExecutorService.class).setExecutor("jdbc", database, oldTemplate);
resetServices();
}
private Executor getAndReplaceJdbcExecutor(Writer output) {
/* We have no other choice than to save the current Executer here. */
@SuppressWarnings("squid:S1941")
Executor oldTemplate = Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database);
final LoggingExecutor loggingExecutor = new LoggingExecutor(oldTemplate, output, database);
Scope.getCurrentScope().getSingleton(ExecutorService.class).setExecutor("logging", database, loggingExecutor);
Scope.getCurrentScope().getSingleton(ExecutorService.class).setExecutor("jdbc", database, loggingExecutor);
return oldTemplate;
}
public void rollback(Date dateToRollBackTo, String contexts) throws LiquibaseException {
rollback(dateToRollBackTo, null, contexts);
}
public void rollback(Date dateToRollBackTo, Contexts contexts, LabelExpression labelExpression)
throws LiquibaseException {
rollback(dateToRollBackTo, null, contexts, labelExpression);
}
public void rollback(Date dateToRollBackTo, String rollbackScript, String contexts) throws LiquibaseException {
rollback(dateToRollBackTo, new Contexts(contexts), new LabelExpression());
}
public void rollback(Date dateToRollBackTo, String rollbackScript, Contexts contexts,
LabelExpression labelExpression) throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
LockService lockService = LockServiceFactory.getInstance().getLockService(database);
lockService.waitForLock();
try {
DatabaseChangeLog changeLog = getDatabaseChangeLog();
checkLiquibaseTables(false, changeLog, contexts, labelExpression);
changeLog.validate(database, contexts, labelExpression);
List<RanChangeSet> ranChangeSetList = database.getRanChangeSetList();
ChangeLogIterator logIterator = new ChangeLogIterator(ranChangeSetList, changeLog,
new ExecutedAfterChangeSetFilter(dateToRollBackTo, ranChangeSetList),
new AlreadyRanChangeSetFilter(ranChangeSetList),
new ContextChangeSetFilter(contexts),
new LabelChangeSetFilter(labelExpression),
new IgnoreChangeSetFilter(),
new DbmsChangeSetFilter(database));
if (rollbackScript == null) {
logIterator.run(createRollbackVisitor(),
new RuntimeEnvironment(database, contexts, labelExpression));
} else {
executeRollbackScript(rollbackScript, contexts, labelExpression);
removeRunStatus(logIterator, contexts, labelExpression);
}
} finally {
try {
lockService.releaseLock();
} catch (LockException e) {
LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
}
}
resetServices();
}
});
}
public void changeLogSync(String contexts, Writer output) throws LiquibaseException {
changeLogSync(new Contexts(contexts), new LabelExpression(), output);
}
public void changeLogSync(Contexts contexts, LabelExpression labelExpression, Writer output)
throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
LoggingExecutor outputTemplate = new LoggingExecutor(
Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor(database), output, database
);
/* We have no other choice than to save the current Executer here. */
@SuppressWarnings("squid:S1941")
Executor oldTemplate = getAndReplaceJdbcExecutor(output);
outputHeader("SQL to add all changesets to database history table");
changeLogSync(contexts, labelExpression);
flushOutputWriter(output);
Scope.getCurrentScope().getSingleton(ExecutorService.class).setExecutor("jdbc", database, oldTemplate);
resetServices();
}
});
}
private void flushOutputWriter(Writer output) throws LiquibaseException {
try {
output.flush();
} catch (IOException e) {
throw new LiquibaseException(e);
}
}
public void changeLogSync(String contexts) throws LiquibaseException {
changeLogSync(new Contexts(contexts), new LabelExpression());
}
/**
* @deprecated use version with LabelExpression
*/
@Deprecated
public void changeLogSync(Contexts contexts) throws LiquibaseException {
changeLogSync(contexts, new LabelExpression());
}
public void changeLogSync(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
LockService lockService = LockServiceFactory.getInstance().getLockService(database);
lockService.waitForLock();
try {
DatabaseChangeLog changeLog = getDatabaseChangeLog();
checkLiquibaseTables(true, changeLog, contexts, labelExpression);
ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId();
changeLog.validate(database, contexts, labelExpression);
ChangeLogIterator logIterator = new ChangeLogIterator(changeLog,
new NotRanChangeSetFilter(database.getRanChangeSetList()),
new ContextChangeSetFilter(contexts),
new LabelChangeSetFilter(labelExpression),
new IgnoreChangeSetFilter(),
new DbmsChangeSetFilter(database));
logIterator.run(new ChangeLogSyncVisitor(database, changeLogSyncListener),
new RuntimeEnvironment(database, contexts, labelExpression)
);
} finally {
try {
lockService.releaseLock();
} catch (LockException e) {
LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
}
resetServices();
}
}
});
}
public void markNextChangeSetRan(String contexts, Writer output) throws LiquibaseException {
markNextChangeSetRan(new Contexts(contexts), new LabelExpression(), output);
}
public void markNextChangeSetRan(Contexts contexts, LabelExpression labelExpression, Writer output)
throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
@SuppressWarnings("squid:S1941")
Executor oldTemplate = getAndReplaceJdbcExecutor(output);
outputHeader("SQL to add all changesets to database history table");
markNextChangeSetRan(contexts, labelExpression);
flushOutputWriter(output);
Scope.getCurrentScope().getSingleton(ExecutorService.class).setExecutor("jdbc", database, oldTemplate);
resetServices();
}
});
}
public void markNextChangeSetRan(String contexts) throws LiquibaseException {
markNextChangeSetRan(new Contexts(contexts), new LabelExpression());
}
public void markNextChangeSetRan(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
LockService lockService = LockServiceFactory.getInstance().getLockService(database);
lockService.waitForLock();
try {
DatabaseChangeLog changeLog = getDatabaseChangeLog();
ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId();
checkLiquibaseTables(false, changeLog, contexts, labelExpression);
changeLog.validate(database, contexts, labelExpression);
ChangeLogIterator logIterator = new ChangeLogIterator(changeLog,
new NotRanChangeSetFilter(database.getRanChangeSetList()),
new ContextChangeSetFilter(contexts),
new LabelChangeSetFilter(labelExpression),
new DbmsChangeSetFilter(database),
new IgnoreChangeSetFilter(),
new CountChangeSetFilter(1));
logIterator.run(new ChangeLogSyncVisitor(database),
new RuntimeEnvironment(database, contexts, labelExpression)
);
} finally {
try {
lockService.releaseLock();
} catch (LockException e) {
LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
}
resetServices();
}
}
});
}
public void futureRollbackSQL(String contexts, Writer output) throws LiquibaseException {
futureRollbackSQL(null, contexts, output, true);
}
public void futureRollbackSQL(Writer output) throws LiquibaseException {
futureRollbackSQL(null, null, new Contexts(), new LabelExpression(), output);
}
public void futureRollbackSQL(String contexts, Writer output, boolean checkLiquibaseTables)
throws LiquibaseException {
futureRollbackSQL(null, contexts, output, checkLiquibaseTables);
}
public void futureRollbackSQL(Integer count, String contexts, Writer output) throws LiquibaseException {
futureRollbackSQL(count, new Contexts(contexts), new LabelExpression(), output, true);
}
public void futureRollbackSQL(Contexts contexts, LabelExpression labelExpression, Writer output)
throws LiquibaseException {
futureRollbackSQL(null, null, contexts, labelExpression, output);
}
public void futureRollbackSQL(Integer count, String contexts, Writer output, boolean checkLiquibaseTables)
throws LiquibaseException {
futureRollbackSQL(count, new Contexts(contexts), new LabelExpression(), output, checkLiquibaseTables);
}
public void futureRollbackSQL(Integer count, Contexts contexts, LabelExpression labelExpression, Writer output)
throws LiquibaseException {
futureRollbackSQL(count, contexts, labelExpression, output, true);
}
public void futureRollbackSQL(Integer count, Contexts contexts, LabelExpression labelExpression, Writer output,
boolean checkLiquibaseTables) throws LiquibaseException {
futureRollbackSQL(count, null, contexts, labelExpression, output);
}
public void futureRollbackSQL(String tag, Contexts contexts, LabelExpression labelExpression, Writer output)
throws LiquibaseException {
futureRollbackSQL(null, tag, contexts, labelExpression, output);
}
protected void futureRollbackSQL(Integer count, String tag, Contexts contexts, LabelExpression labelExpression,
Writer output) throws LiquibaseException {
futureRollbackSQL(count, tag, contexts, labelExpression, output, true);
}
protected void futureRollbackSQL(Integer count, String tag, Contexts contexts, LabelExpression labelExpression,
Writer output, boolean checkLiquibaseTables) throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
LoggingExecutor outputTemplate = new LoggingExecutor(Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor(database),
output, database);
Executor oldTemplate = getAndReplaceJdbcExecutor(output);
Scope.getCurrentScope().getSingleton(ExecutorService.class).setExecutor(database, outputTemplate);
outputHeader("SQL to roll back currently unexecuted changes");
LockService lockService = LockServiceFactory.getInstance().getLockService(database);
lockService.waitForLock();
try {
DatabaseChangeLog changeLog = getDatabaseChangeLog();
if (checkLiquibaseTables) {
checkLiquibaseTables(false, changeLog, contexts, labelExpression);
}
ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId();
changeLog.validate(database, contexts, labelExpression);
ChangeLogIterator logIterator;
if ((count == null) && (tag == null)) {
logIterator = new ChangeLogIterator(changeLog,
new NotRanChangeSetFilter(database.getRanChangeSetList()),
new ContextChangeSetFilter(contexts),
new LabelChangeSetFilter(labelExpression),
new IgnoreChangeSetFilter(),
new DbmsChangeSetFilter(database));
} else if (count != null) {
ChangeLogIterator forwardIterator = new ChangeLogIterator(changeLog,
new NotRanChangeSetFilter(database.getRanChangeSetList()),
new ContextChangeSetFilter(contexts),
new LabelChangeSetFilter(labelExpression),
new DbmsChangeSetFilter(database),
new IgnoreChangeSetFilter(),
new CountChangeSetFilter(count));
final ListVisitor listVisitor = new ListVisitor();
forwardIterator.run(listVisitor, new RuntimeEnvironment(database, contexts, labelExpression));
logIterator = new ChangeLogIterator(changeLog,
new NotRanChangeSetFilter(database.getRanChangeSetList()),
new ContextChangeSetFilter(contexts),
new LabelChangeSetFilter(labelExpression),
new DbmsChangeSetFilter(database),
new IgnoreChangeSetFilter(),
new ChangeSetFilter() {
@Override
public ChangeSetFilterResult accepts(ChangeSet changeSet) {
return new ChangeSetFilterResult(
listVisitor.getSeenChangeSets().contains(changeSet), null, null
);
}
});
} else {
List<RanChangeSet> ranChangeSetList = database.getRanChangeSetList();
ChangeLogIterator forwardIterator = new ChangeLogIterator(changeLog,
new NotRanChangeSetFilter(ranChangeSetList),
new ContextChangeSetFilter(contexts),
new LabelChangeSetFilter(labelExpression),
new DbmsChangeSetFilter(database),
new IgnoreChangeSetFilter(),
new UpToTagChangeSetFilter(tag, ranChangeSetList));
final ListVisitor listVisitor = new ListVisitor();
forwardIterator.run(listVisitor, new RuntimeEnvironment(database, contexts, labelExpression));
logIterator = new ChangeLogIterator(changeLog,
new NotRanChangeSetFilter(ranChangeSetList),
new ContextChangeSetFilter(contexts),
new LabelChangeSetFilter(labelExpression),
new DbmsChangeSetFilter(database),
new IgnoreChangeSetFilter(),
new ChangeSetFilter() {
@Override
public ChangeSetFilterResult accepts(ChangeSet changeSet) {
return new ChangeSetFilterResult(
listVisitor.getSeenChangeSets().contains(changeSet), null, null
);
}
});
}
logIterator.run(createRollbackVisitor(),
new RuntimeEnvironment(database, contexts, labelExpression)
);
} finally {
try {
lockService.releaseLock();
} catch (LockException e) {
LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
}
Scope.getCurrentScope().getSingleton(ExecutorService.class).setExecutor("jdbc", database, oldTemplate);
resetServices();
}
flushOutputWriter(
output);
}
});
}
protected void resetServices() {
LockServiceFactory.getInstance().resetAll();
ChangeLogHistoryServiceFactory.getInstance().resetAll();
Scope.getCurrentScope().getSingleton(ExecutorService.class).reset();
}
/**
* Drops all database objects in the default schema.
*/
public final void dropAll() throws DatabaseException {
dropAll(new CatalogAndSchema(getDatabase().getDefaultCatalogName(), getDatabase().getDefaultSchemaName()));
}
/**
* Drops all database objects in the passed schema(s).
*/
public final void dropAll(CatalogAndSchema... schemas) throws DatabaseException {
if ((schemas == null) || (schemas.length == 0)) {
schemas = new CatalogAndSchema[]{
new CatalogAndSchema(getDatabase().getDefaultCatalogName(), getDatabase().getDefaultSchemaName())
};
}
CatalogAndSchema[] finalSchemas = schemas;
try {
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
DropAllCommand dropAll = (DropAllCommand) CommandFactory.getInstance().getCommand("dropAll");
dropAll.setDatabase(Liquibase.this.getDatabase());
dropAll.setSchemas(finalSchemas);
try {
dropAll.execute();
} catch (CommandExecutionException e) {
throw new DatabaseException(e);
}
}
});
} catch (LiquibaseException e) {
if (e instanceof DatabaseException) {
throw (DatabaseException) e;
} else {
throw new DatabaseException(e);
}
}
}
/**
* 'Tags' the database for future rollback
*/
public void tag(String tagString) throws LiquibaseException {
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
LockService lockService = LockServiceFactory.getInstance().getLockService(database);
lockService.waitForLock();
try {
ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(database).generateDeploymentId();
checkLiquibaseTables(false, null, new Contexts(),
new LabelExpression());
getDatabase().tag(tagString);
} finally {
try {
lockService.releaseLock();
} catch (LockException e) {
LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
}
}
}
});
}
public boolean tagExists(String tagString) throws LiquibaseException {
LockService lockService = LockServiceFactory.getInstance().getLockService(database);
lockService.waitForLock();
try {
checkLiquibaseTables(false, null, new Contexts(),
new LabelExpression());
return getDatabase().doesTagExist(tagString);
} finally {
try {
lockService.releaseLock();
} catch (LockException e) {
LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
}
}
}
public void updateTestingRollback(String contexts) throws LiquibaseException {
updateTestingRollback(new Contexts(contexts), new LabelExpression());
}
public void updateTestingRollback(Contexts contexts, LabelExpression labelExpression) throws LiquibaseException {
updateTestingRollback(null, contexts, labelExpression);
}
public void updateTestingRollback(String tag, Contexts contexts, LabelExpression labelExpression)
throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
Date baseDate = new Date();
update(tag, contexts, labelExpression);
rollback(baseDate, null, contexts, labelExpression);
update(tag, contexts, labelExpression);
}
public void checkLiquibaseTables(boolean updateExistingNullChecksums, DatabaseChangeLog databaseChangeLog,
Contexts contexts, LabelExpression labelExpression) throws LiquibaseException {
ChangeLogHistoryService changeLogHistoryService =
ChangeLogHistoryServiceFactory.getInstance().getChangeLogService(getDatabase());
changeLogHistoryService.init();
if (updateExistingNullChecksums) {
changeLogHistoryService.upgradeChecksums(databaseChangeLog, contexts, labelExpression);
}
LockServiceFactory.getInstance().getLockService(getDatabase()).init();
}
/**
* Returns true if it is "save" to migrate the database.
* Currently, "safe" is defined as running in an output-sql mode or against a database on localhost.
* It is fine to run Liquibase against a "non-safe" database, the method is mainly used to determine if the user
* should be prompted before continuing.
*/
public boolean isSafeToRunUpdate() throws DatabaseException {
return getDatabase().isSafeToRunUpdate();
}
/**
* Display change log lock information.
*/
public DatabaseChangeLogLock[] listLocks() throws LiquibaseException {
checkLiquibaseTables(false, null, new Contexts(), new LabelExpression());
return LockServiceFactory.getInstance().getLockService(database).listLocks();
}
public void reportLocks(PrintStream out) throws LiquibaseException {
DatabaseChangeLogLock[] locks = listLocks();
out.println("Database change log locks for " + getDatabase().getConnection().getConnectionUserName()
+ "@" + getDatabase().getConnection().getURL());
if (locks.length == 0) {
out.println(" - No locks");
}
for (DatabaseChangeLogLock lock : locks) {
out.println(" - " + lock.getLockedBy() + " at " +
DateFormat.getDateTimeInstance().format(lock.getLockGranted()));
}
}
public void forceReleaseLocks() throws LiquibaseException {
checkLiquibaseTables(false, null, new Contexts(), new LabelExpression());
LockServiceFactory.getInstance().getLockService(database).forceReleaseLock();
}
/**
* @deprecated use version with LabelExpression
*/
@Deprecated
public List<ChangeSet> listUnrunChangeSets(Contexts contexts) throws LiquibaseException {
return listUnrunChangeSets(contexts, new LabelExpression());
}
public List<ChangeSet> listUnrunChangeSets(Contexts contexts, LabelExpression labels) throws LiquibaseException {
return listUnrunChangeSets(contexts, labels, true);
}
public List<ChangeSet> listUnrunChangeSets(Contexts contexts, LabelExpression labels, boolean checkLiquibaseTables) throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labels);
ListVisitor visitor = new ListVisitor();
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
DatabaseChangeLog changeLog = getDatabaseChangeLog();
if (checkLiquibaseTables) {
checkLiquibaseTables(true, changeLog, contexts, labels);
}
changeLog.validate(database, contexts, labels);
ChangeLogIterator logIterator = getStandardChangelogIterator(contexts, labels, changeLog);
logIterator.run(visitor, new RuntimeEnvironment(database, contexts, labels));
}
});
return visitor.getSeenChangeSets();
}
/**
* @deprecated use version with LabelExpression
*/
@Deprecated
public List<ChangeSetStatus> getChangeSetStatuses(Contexts contexts) throws LiquibaseException {
return getChangeSetStatuses(contexts, new LabelExpression());
}
public List<ChangeSetStatus> getChangeSetStatuses(Contexts contexts, LabelExpression labelExpression)
throws LiquibaseException {
return getChangeSetStatuses(contexts, labelExpression, true);
}
/**
* Returns the ChangeSetStatuses of all changesets in the change log file and history in the order they
* would be ran.
*/
public List<ChangeSetStatus> getChangeSetStatuses(Contexts contexts, LabelExpression labelExpression,
boolean checkLiquibaseTables) throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
StatusVisitor visitor = new StatusVisitor(database);
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
DatabaseChangeLog changeLog = getDatabaseChangeLog();
if (checkLiquibaseTables) {
checkLiquibaseTables(true, changeLog, contexts, labelExpression);
}
changeLog.validate(database, contexts, labelExpression);
ChangeLogIterator logIterator = getStandardChangelogIterator(contexts, labelExpression, changeLog);
logIterator.run(visitor, new RuntimeEnvironment(database, contexts, labelExpression));
}
});
return visitor.getStatuses();
}
public void reportStatus(boolean verbose, String contexts, Writer out) throws LiquibaseException {
reportStatus(verbose, new Contexts(contexts), new LabelExpression(), out);
}
public void reportStatus(boolean verbose, Contexts contexts, Writer out) throws LiquibaseException {
reportStatus(verbose, contexts, new LabelExpression(), out);
}
public void reportStatus(boolean verbose, Contexts contexts, LabelExpression labels, Writer out)
throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labels);
try {
List<ChangeSet> unrunChangeSets = listUnrunChangeSets(contexts, labels, false);
if (unrunChangeSets.isEmpty()) {
out.append(getDatabase().getConnection().getConnectionUserName());
out.append("@");
out.append(getDatabase().getConnection().getURL());
out.append(" is up to date");
out.append(StreamUtil.getLineSeparator());
} else {
out.append(String.valueOf(unrunChangeSets.size()));
out.append(" change sets have not been applied to ");
out.append(getDatabase().getConnection().getConnectionUserName());
out.append("@");
out.append(getDatabase().getConnection().getURL());
out.append(StreamUtil.getLineSeparator());
if (verbose) {
for (ChangeSet changeSet : unrunChangeSets) {
out.append(" ").append(changeSet.toString(false))
.append(StreamUtil.getLineSeparator());
}
}
}
out.flush();
} catch (IOException e) {
throw new LiquibaseException(e);
}
}
public Collection<RanChangeSet> listUnexpectedChangeSets(String contexts) throws LiquibaseException {
return listUnexpectedChangeSets(new Contexts(contexts), new LabelExpression());
}
public Collection<RanChangeSet> listUnexpectedChangeSets(Contexts contexts, LabelExpression labelExpression)
throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
ExpectedChangesVisitor visitor = new ExpectedChangesVisitor(database.getRanChangeSetList());
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
DatabaseChangeLog changeLog = getDatabaseChangeLog();
changeLog.validate(database, contexts, labelExpression);
ChangeLogIterator logIterator = new ChangeLogIterator(changeLog,
new ContextChangeSetFilter(contexts),
new LabelChangeSetFilter(labelExpression),
new DbmsChangeSetFilter(database),
new IgnoreChangeSetFilter());
logIterator.run(visitor, new RuntimeEnvironment(database, contexts, labelExpression));
}
});
return visitor.getUnexpectedChangeSets();
}
public void reportUnexpectedChangeSets(boolean verbose, String contexts, Writer out) throws LiquibaseException {
reportUnexpectedChangeSets(verbose, new Contexts(contexts), new LabelExpression(), out);
}
public void reportUnexpectedChangeSets(boolean verbose, Contexts contexts, LabelExpression labelExpression,
Writer out) throws LiquibaseException {
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
try {
Collection<RanChangeSet> unexpectedChangeSets = listUnexpectedChangeSets(contexts, labelExpression);
if (unexpectedChangeSets.isEmpty()) {
out.append(getDatabase().getConnection().getConnectionUserName());
out.append("@");
out.append(getDatabase().getConnection().getURL());
out.append(" contains no unexpected changes!");
out.append(StreamUtil.getLineSeparator());
} else {
out.append(String.valueOf(unexpectedChangeSets.size()));
out.append(" unexpected changes were found in ");
out.append(getDatabase().getConnection().getConnectionUserName());
out.append("@");
out.append(getDatabase().getConnection().getURL());
out.append(StreamUtil.getLineSeparator());
if (verbose) {
for (RanChangeSet ranChangeSet : unexpectedChangeSets) {
out.append(" ").append(ranChangeSet.toString()).append(StreamUtil.getLineSeparator());
}
}
}
out.flush();
} catch (IOException e) {
throw new LiquibaseException(e);
}
}
/**
* Sets checksums to null so they will be repopulated next run
*/
public void clearCheckSums() throws LiquibaseException {
LOG.info("Clearing database change log checksums");
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
LockService lockService = LockServiceFactory.getInstance().getLockService(database);
lockService.waitForLock();
try {
checkLiquibaseTables(false, null, new Contexts(), new LabelExpression());
UpdateStatement updateStatement = new UpdateStatement(
getDatabase().getLiquibaseCatalogName(),
getDatabase().getLiquibaseSchemaName(),
getDatabase().getDatabaseChangeLogTableName()
);
updateStatement.addNewColumnValue("MD5SUM", null);
Scope.getCurrentScope().getSingleton(ExecutorService.class).getExecutor("jdbc", database).execute(updateStatement);
getDatabase().commit();
} finally {
try {
lockService.releaseLock();
} catch (LockException e) {
LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
}
}
resetServices();
}
});
}
public final CheckSum calculateCheckSum(final String changeSetIdentifier) throws LiquibaseException {
if (changeSetIdentifier == null) {
throw new LiquibaseException(new IllegalArgumentException("changeSetIdentifier"));
}
final List<String> parts = StringUtil.splitAndTrim(changeSetIdentifier, "::");
if ((parts == null) || (parts.size() < CHANGESET_ID_NUM_PARTS)) {
throw new LiquibaseException(
new IllegalArgumentException("Invalid changeSet identifier: " + changeSetIdentifier)
);
}
return this.calculateCheckSum(parts.get(CHANGESET_ID_CHANGELOG_PART),
parts.get(CHANGESET_ID_CHANGESET_PART), parts.get(CHANGESET_ID_AUTHOR_PART));
}
public CheckSum calculateCheckSum(final String filename, final String id, final String author)
throws LiquibaseException {
LOG.info(String.format("Calculating checksum for changeset %s::%s::%s", filename, id, author));
final ChangeLogParameters clParameters = this.getChangeLogParameters();
final ResourceAccessor resourceAccessor = this.getResourceAccessor();
final DatabaseChangeLog changeLog =
ChangeLogParserFactory.getInstance().getParser(
this.changeLogFile, resourceAccessor
).parse(this.changeLogFile, clParameters, resourceAccessor);
// TODO: validate?
final ChangeSet changeSet = changeLog.getChangeSet(filename, author, id);
if (changeSet == null) {
throw new LiquibaseException(
new IllegalArgumentException("No such changeSet: " + filename + "::" + id + "::" + author)
);
}
return changeSet.generateCheckSum();
}
public void generateDocumentation(String outputDirectory) throws LiquibaseException {
// call without context
generateDocumentation(outputDirectory, new Contexts(), new LabelExpression());
}
public void generateDocumentation(String outputDirectory, String contexts) throws LiquibaseException {
generateDocumentation(outputDirectory, new Contexts(contexts), new LabelExpression());
}
public void generateDocumentation(String outputDirectory, Contexts contexts,
LabelExpression labelExpression) throws LiquibaseException {
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
LOG.info("Generating Database Documentation");
changeLogParameters.setContexts(contexts);
changeLogParameters.setLabels(labelExpression);
LockService lockService = LockServiceFactory.getInstance().getLockService(database);
lockService.waitForLock();
try {
DatabaseChangeLog changeLog = getDatabaseChangeLog();
checkLiquibaseTables(false, changeLog, new Contexts(), new LabelExpression());
changeLog.validate(database, contexts, labelExpression);
ChangeLogIterator logIterator = new ChangeLogIterator(changeLog,
new DbmsChangeSetFilter(database));
DBDocVisitor visitor = new DBDocVisitor(database);
logIterator.run(visitor, new RuntimeEnvironment(database, contexts, labelExpression));
visitor.writeHTML(new File(outputDirectory), resourceAccessor);
} catch (IOException e) {
throw new LiquibaseException(e);
} finally {
try {
lockService.releaseLock();
} catch (LockException e) {
LOG.severe(MSG_COULD_NOT_RELEASE_LOCK, e);
}
}
}
});
}
public DiffResult diff(Database referenceDatabase, Database targetDatabase, CompareControl compareControl)
throws LiquibaseException {
return DiffGeneratorFactory.getInstance().compare(referenceDatabase, targetDatabase, compareControl);
}
/**
* Checks changelogs for bad MD5Sums and preconditions before attempting a migration
*/
public void validate() throws LiquibaseException {
DatabaseChangeLog changeLog = getDatabaseChangeLog();
changeLog.validate(database);
}
public void setChangeLogParameter(String key, Object value) {
this.changeLogParameters.set(key, value);
}
/**
* Add safe database properties as changelog parameters.<br/>
* Safe properties are the ones that doesn't have side effects in liquibase state and also don't change in during the liquibase execution
*
* @param database Database which propeties are put in the changelog
* @throws DatabaseException
*/
private void setDatabasePropertiesAsChangelogParameters(Database database) throws DatabaseException {
setChangeLogParameter("database.autoIncrementClause", database.getAutoIncrementClause(null, null, null, null));
setChangeLogParameter("database.currentDateTimeFunction", database.getCurrentDateTimeFunction());
setChangeLogParameter("database.databaseChangeLogLockTableName", database.getDatabaseChangeLogLockTableName());
setChangeLogParameter("database.databaseChangeLogTableName", database.getDatabaseChangeLogTableName());
setChangeLogParameter("database.databaseMajorVersion", database.getDatabaseMajorVersion());
setChangeLogParameter("database.databaseMinorVersion", database.getDatabaseMinorVersion());
setChangeLogParameter("database.databaseProductName", database.getDatabaseProductName());
setChangeLogParameter("database.databaseProductVersion", database.getDatabaseProductVersion());
setChangeLogParameter("database.defaultCatalogName", database.getDefaultCatalogName());
setChangeLogParameter("database.defaultSchemaName", database.getDefaultSchemaName());
setChangeLogParameter("database.defaultSchemaNamePrefix", StringUtil.trimToNull(database.getDefaultSchemaName()) == null ? "" : "." + database.getDefaultSchemaName());
setChangeLogParameter("database.lineComment", database.getLineComment());
setChangeLogParameter("database.liquibaseSchemaName", database.getLiquibaseSchemaName());
setChangeLogParameter("database.liquibaseTablespaceName", database.getLiquibaseTablespaceName());
setChangeLogParameter("database.typeName", database.getShortName());
setChangeLogParameter("database.isSafeToRunUpdate", database.isSafeToRunUpdate());
setChangeLogParameter("database.requiresPassword", database.requiresPassword());
setChangeLogParameter("database.requiresUsername", database.requiresUsername());
setChangeLogParameter("database.supportsForeignKeyDisable", database.supportsForeignKeyDisable());
setChangeLogParameter("database.supportsInitiallyDeferrableColumns", database.supportsInitiallyDeferrableColumns());
setChangeLogParameter("database.supportsRestrictForeignKeys", database.supportsRestrictForeignKeys());
setChangeLogParameter("database.supportsSchemas", database.supportsSchemas());
setChangeLogParameter("database.supportsSequences", database.supportsSequences());
setChangeLogParameter("database.supportsTablespaces", database.supportsTablespaces());
}
private LockService getLockService() {
return LockServiceFactory.getInstance().getLockService(database);
}
public void setChangeExecListener(ChangeExecListener listener) {
this.changeExecListener = listener;
}
public void setChangeLogSyncListener(ChangeLogSyncListener changeLogSyncListener) {
this.changeLogSyncListener = changeLogSyncListener;
}
@SafeVarargs
public final void generateChangeLog(CatalogAndSchema catalogAndSchema, DiffToChangeLog changeLogWriter,
PrintStream outputStream, Class<? extends DatabaseObject>... snapshotTypes)
throws DatabaseException, IOException, ParserConfigurationException {
generateChangeLog(catalogAndSchema, changeLogWriter, outputStream, null, snapshotTypes);
}
@SafeVarargs
public final void generateChangeLog(CatalogAndSchema catalogAndSchema, DiffToChangeLog changeLogWriter,
PrintStream outputStream, ChangeLogSerializer changeLogSerializer,
Class<? extends DatabaseObject>... snapshotTypes)
throws DatabaseException, IOException, ParserConfigurationException {
try {
runInScope(new Scope.ScopedRunner() {
@Override
public void run() throws Exception {
Set<Class<? extends DatabaseObject>> finalCompareTypes = null;
if ((snapshotTypes != null) && (snapshotTypes.length > 0)) {
finalCompareTypes = new HashSet<>(Arrays.asList(snapshotTypes));
}
SnapshotControl snapshotControl = new SnapshotControl(Liquibase.this.getDatabase(), snapshotTypes);
CompareControl compareControl = new CompareControl(new CompareControl.SchemaComparison[]{
new CompareControl.SchemaComparison(catalogAndSchema, catalogAndSchema)
}, finalCompareTypes);
DatabaseSnapshot originalDatabaseSnapshot = null;
try {
originalDatabaseSnapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(
compareControl.getSchemas(CompareControl.DatabaseRole.REFERENCE),
getDatabase(),
snapshotControl
);
DiffResult diffResult = DiffGeneratorFactory.getInstance().compare(
originalDatabaseSnapshot,
SnapshotGeneratorFactory.getInstance().createSnapshot(
compareControl.getSchemas(CompareControl.DatabaseRole.REFERENCE),
null,
snapshotControl
),
compareControl
);
changeLogWriter.setDiffResult(diffResult);
if (changeLogSerializer != null) {
changeLogWriter.print(outputStream, changeLogSerializer);
} else {
changeLogWriter.print(outputStream);
}
} catch (InvalidExampleException e) {
throw new UnexpectedLiquibaseException(e);
}
}
});
} catch (LiquibaseException e) {
throw new DatabaseException(e);
}
}
private void runInScope(Scope.ScopedRunner scopedRunner) throws LiquibaseException {
Map<String, Object> scopeObjects = new HashMap<>();
scopeObjects.put(Scope.Attr.database.name(), getDatabase());
scopeObjects.put(Scope.Attr.resourceAccessor.name(), getResourceAccessor());
try {
Scope.child(scopeObjects, scopedRunner);
} catch (Exception e) {
if (e instanceof LiquibaseException) {
throw (LiquibaseException) e;
} else {
throw new LiquibaseException(e);
}
}
}
@Override
public void close() throws Exception {
if (database != null) {
database.close();
}
}
}
|
package org.apache.xmlrpc;
import java.util.Vector;
/**
* An XML-RPC handler that also handles user authentication.
*
* @author <a href="mailto:hannes@apache.org">Hannes Wallnoefer</a>
* @see org.apache.xmlrpc.AuthenticationFailed
* @version $Id$
*/
public interface AuthenticatedXmlRpcHandler
{
/**
* Return the result, or throw an Exception if something went wrong.
*
* @throws AuthenticationFailed If authentication fails, an
* exception of this type must be thrown.
* @see org.apache.xmlrpc.AuthenticationFailed
*/
public Object execute(String method, Vector params, String user,
String password)
throws Exception;
}
|
package org.concord.otrunk.util;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import org.concord.framework.otrunk.OTChangeEvent;
import org.concord.framework.otrunk.OTChangeListener;
import org.concord.framework.otrunk.OTObject;
import org.concord.framework.otrunk.OTObjectService;
import org.concord.framework.otrunk.view.OTLabbookManager;
import org.concord.otrunk.datamodel.OTDataCollection;
import org.concord.otrunk.util.OTLabbookBundle;
import org.concord.otrunk.util.OTLabbookBundle.ResourceSchema;
public class OTLabbookManagerImpl
implements OTLabbookManager, OTChangeListener
{
private OTLabbookBundle.ResourceSchema resources;
private Vector listeners;
private OTObjectService objectService;
private boolean tempShowLabbook;
public OTLabbookManagerImpl(OTLabbookBundle.ResourceSchema resources)
{
this.resources = resources;
resources.addOTChangeListener(this);
}
public void add(OTObject otObject)
{
OTLabbookEntry entry = createEntry(otObject);
resources.getEntries().add(entry);
}
public void add(OTObject otObject, OTObject container)
{
this.add(otObject, container, null, true);
}
public void add(OTObject otObject, OTObject container, OTObject originalObject)
{
this.add(otObject, container, originalObject, true);
}
public void add(OTObject otObject, OTObject container, OTObject originalObject, boolean showLabbook)
{
OTLabbookEntry entry = createEntry(otObject);
entry.setContainer(container);
if (originalObject != null){
entry.setOriginalObject(originalObject);
}
tempShowLabbook = showLabbook;
resources.getEntries().add(entry);
}
public void addSnapshot(OTObject snapshot)
{
OTLabbookEntry entry = createEntry(snapshot);
resources.getEntries().add(entry);
}
public void addDataCollector(OTObject dataCollector)
{
OTLabbookEntry entry = createEntry(dataCollector);
resources.getEntries().add(entry);
}
public void addDrawingTool(OTObject drawingTool)
{
OTLabbookEntry entry = createEntry(drawingTool);
resources.getEntries().add(entry);
}
public void addText(OTObject question)
{
OTLabbookEntry entry = createEntry(question);
resources.getEntries().add(entry);
}
public Vector getGraphs()
{
return resources.getEntries().getVector();
}
public Vector getDrawings()
{
return resources.getEntries().getVector();
}
public Vector getText()
{
return resources.getEntries().getVector();
}
public Vector getSnapshots()
{
return resources.getEntries().getVector();
}
public Vector getAllEntries(){
return resources.getEntries().getVector();
}
public void remove(OTObject labbookEntry){
resources.getEntries().remove(labbookEntry);
}
private OTLabbookEntry createEntry(OTObject object){
String type = null;
if (object.toString().indexOf("OTDataCollector") > -1){
type = "Graphs";
} else if (object.toString().indexOf("OTDrawing") > -1){
type = "Drawings";
} else if (object.toString().indexOf("OTBlob") > -1){
type = "Snapshots";
} else if (object.toString().indexOf("OTText") > -1 ||
object.toString().indexOf("Question") > -1){
type = "Text";
}
return createEntry(object, type);
}
private OTLabbookEntry createEntry(OTObject object, String type){
try {
OTLabbookEntry entry = (OTLabbookEntry) resources.getOTObjectService().createObject(OTLabbookEntry.class);
entry.setOTObject(object);
SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM d 'at' K:mm");
Date now = new Date();
String timeString = dateFormat.format(now);
entry.setTimeStamp(timeString);
if (type != null){
entry.setType(type);
}
return entry;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean isEmpty()
{
return (resources.getEntries().getVector().isEmpty());
}
/**
* Change events on the bundle will get passed straight through to listeners
*/
public void stateChanged(OTChangeEvent e)
{
notifyListeners(e);
}
public void addLabbookListener(OTChangeListener listener){
if (listeners == null){
listeners = new Vector();
}
if (!listeners.contains(listener)){
listeners.add(listener);
}
}
public void removeLabbookListener(OTChangeListener listener){
if (listeners != null){
listeners.remove(listener);
}
}
private void notifyListeners(OTChangeEvent e){
if (listeners == null){
return;
}
OTLabbookChangeEvent labbookChangeEvent = new OTLabbookChangeEvent((OTObject) e.getSource());
labbookChangeEvent.setOperation(e.getOperation());
labbookChangeEvent.setProperty(e.getProperty());
labbookChangeEvent.setValue(e.getValue());
labbookChangeEvent.setShowLabbook(tempShowLabbook);
for (int i = 0; i < listeners.size(); i++) {
((OTChangeListener)listeners.get(i)).stateChanged(labbookChangeEvent);
}
}
/*
public void setOTObjectService(OTObjectService objectService)
{
this.objectService = objectService;
try {
OTLabbookBundle bundle = (OTLabbookBundle) objectService.getOTObject(resources.getGlobalId());
this.resources = bundle.resources;
resources.addOTChangeListener(this);
} catch (Exception e) {
e.printStackTrace();
}
}
*/
public class OTLabbookChangeEvent extends OTChangeEvent
{
private boolean showLabbook = true;
public OTLabbookChangeEvent(OTObject source)
{
super(source);
}
public void setShowLabbook(boolean showLabbook){
this.showLabbook = showLabbook;
}
/*
* Any listener that will pop up a labbook view should check this first
*/
public boolean getShowLabbook(){
return showLabbook;
}
}
}
|
package org.formic.wizard.impl.console;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import charva.awt.BorderLayout;
import charva.awt.Component;
import charva.awt.Dimension;
import charva.awt.FlowLayout;
import charva.awt.Toolkit;
import charva.awt.event.WindowAdapter;
import charva.awt.event.WindowEvent;
import charvax.swing.BorderFactory;
import charvax.swing.JButton;
import charvax.swing.JFrame;
import charvax.swing.JLabel;
import charvax.swing.JPanel;
import charvax.swing.JSeparator;
import edu.emory.mathcs.backport.java.util.concurrent.Semaphore;
import org.formic.Installer;
import org.formic.wizard.Wizard;
import org.formic.wizard.WizardStep;
import org.formic.wizard.console.dialog.Dialogs;
import org.formic.wizard.impl.models.MultiPathModel;
import org.pietschy.wizard.WizardModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Wizard for console installers.
*
* @author Eric Van Dewoestine (ervandew@yahoo.com)
* @version $Revision$
*/
public class ConsoleWizard
implements Wizard, PropertyChangeListener
{
private static final Logger logger =
LoggerFactory.getLogger(ConsoleWizard.class);
private static JFrame frame;
private Semaphore semaphore = new Semaphore(1);
private WizardModel model;
private org.pietschy.wizard.WizardStep activeStep;
private boolean canceled;
private JPanel viewPanel;
private JButton previousButton;
private JButton nextButton;
//private JButton lastButton;
private JButton finishButton;
private JButton cancelButton;
//private JButton closeButton;
/**
* Constructs a new instance.
*/
public ConsoleWizard (WizardModel _model)
{
model = _model;
model.addPropertyChangeListener(this);
try{
semaphore.acquire();
}catch(Exception e){
logger.error("Error acquiring console wizard lock.", e);
}
}
/**
* {@inheritDoc}
* @see org.formic.wizard.Wizard#showWizard()
*/
public void showWizard ()
{
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
int width = Installer.getDimension().width / 7;
int height = Installer.getDimension().height / 12;
String error = null;
if(screen.width < width){
error = Installer.getString("console.width.min",
new Integer(screen.width), new Integer(width));
}
if(screen.height < height){
error = Installer.getString("console.height.min",
new Integer(screen.height), new Integer(height));
}
Dimension dimension = new Dimension(width, height);
// Below will screw up error dialog in some dimensions.
/*Math.max(width, screen.width),
Math.max(height, screen.height));*/
frame = new JFrame(Installer.getString("title"));
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing (WindowEvent _event){
canceled = true;
}
});
viewPanel = new JPanel(new BorderLayout());
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(createInfoPanel(), BorderLayout.NORTH);
mainPanel.add(createButtonPanel(), BorderLayout.SOUTH);
if(error == null){
mainPanel.add(viewPanel, BorderLayout.CENTER);
frame.setSize(dimension);
}else{
frame.setSize(screen);
}
frame.add(mainPanel);
frame.setVisible(true);
if(error != null){
logger.error(error);
Dialogs.showError(error);
close(true);
}else{
model.reset();
}
}
/**
* Creates the info panel on the installation wizard.
*
* @return The info panel.
*/
private JPanel createInfoPanel()
{
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(
BorderFactory.createLineBorder(Toolkit.getDefaultForeground()));
JLabel title = new JLabel("Title");
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
titlePanel.add(title);
JLabel summary = new JLabel("Summary");
JPanel summaryPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
summaryPanel.add(summary);
panel.add(titlePanel, BorderLayout.NORTH);
panel.add(summaryPanel, BorderLayout.CENTER);
return panel;
}
/**
* Creates the button panel on the installation wizard.
*
* @return The button panel.
*/
private JPanel createButtonPanel()
{
JPanel panel = new JPanel(new BorderLayout());
previousButton = new JButton(Installer.getString("previous.text"));
previousButton.addActionListener(new PreviousAction(this));
nextButton = new JButton(Installer.getString("next.text"));
nextButton.addActionListener(new NextAction(this));
finishButton = new JButton(Installer.getString("finish.text"));
finishButton.addActionListener(new FinishAction(this));
cancelButton = new JButton(Installer.getString("cancel.text"));
cancelButton.addActionListener(new CancelAction(this));
JPanel buttonBar = new JPanel(new FlowLayout(FlowLayout.RIGHT, 3, 3));
buttonBar.add(previousButton);
buttonBar.add(nextButton);
buttonBar.add(finishButton);
buttonBar.add(cancelButton);
panel.add(new JSeparator(), BorderLayout.NORTH);
panel.add(buttonBar, BorderLayout.CENTER);
return panel;
}
/**
* {@inheritDoc}
* @see org.formic.wizard.Wizard#waitFor()
*/
public void waitFor ()
{
try{
semaphore.acquire();
}catch(Exception e){
logger.error("Error acquiring console wizard lock in waitFor.", e);
}
}
/**
* {@inheritDoc}
* @see org.formic.wizard.Wizard#wasCanceled()
*/
public boolean wasCanceled ()
{
return canceled;
}
/**
* Close the wizard.
*
* @param _canceled true if the wizard was canceled.
*/
public void close (boolean _canceled)
{
canceled = _canceled;
//frame.setVisible(false);
Toolkit.getDefaultToolkit().close();
try{
semaphore.release();
}catch(Exception e){
logger.error("Error releasing console wizard lock", e);
}
}
/**
* Gets the model for this instance.
*
* @return The model.
*/
public WizardModel getModel ()
{
return this.model;
}
/**
* Gets the frame for this instance.
*
* @return The frame.
*/
public static JFrame getFrame ()
{
return frame;
}
/**
* {@inheritDoc}
* @see PropertyChangeListener#propertyChange(PropertyChangeEvent)
*/
public void propertyChange (PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals(Wizard.ACTIVE_STEP)){
MultiPathModel model = (MultiPathModel)getModel();
org.pietschy.wizard.WizardStep step = model.getActiveStep();
// update step listening.
if (activeStep != null){
activeStep.removePropertyChangeListener(this);
}
activeStep = step;
activeStep.addPropertyChangeListener(this);
if(step != null){
updateView();
WizardStep ws = ((ConsoleWizardStep)step).getStep();
updateButtonStatus(model, ws, step);
// notify step that it is displayed.
ws.displayed();
}
}else if (evt.getPropertyName().equals(WizardStep.CANCEL)){
boolean cancelEnabled = ((Boolean)evt.getNewValue()).booleanValue();
cancelButton.setEnabled(cancelEnabled);
}else if (evt.getPropertyName().equals(WizardStep.VALID) ||
evt.getPropertyName().equals(WizardStep.BUSY))
{
MultiPathModel model = (MultiPathModel)getModel();
org.pietschy.wizard.WizardStep step = model.getActiveStep();
WizardStep ws = ((ConsoleWizardStep)step).getStep();
boolean nextEnabled =
ws.isValid() && !ws.isBusy() && !model.isLastStep(step);
nextButton.setEnabled(nextEnabled);
}
}
/**
* Update the view for the current step.
*/
private void updateView ()
{
Component view = ((ConsoleWizardStep)activeStep).getConsoleView();
viewPanel.add(view);
Component[] components = viewPanel.getComponents();
for (int ii = 0; ii < components.length; ii++){
if(components[ii] != view){
viewPanel.remove(components[ii]);
}
}
viewPanel.validate();
viewPanel.repaint();
}
/**
* Update the state (enabled / disabled) of the buttons in the button bar.
*/
private void updateButtonStatus (
MultiPathModel model, WizardStep ws, org.pietschy.wizard.WizardStep step)
{
// set whether previous step is enabled or not.
boolean previousAvailable =
!model.isFirstStep(step) &&
!model.isLastStep(step) &&
ws.isPreviousEnabled();
previousButton.setEnabled(previousAvailable);
// set whether next step is enabled or not.
boolean nextEnabled =
ws.isValid() && !ws.isBusy() && !model.isLastStep(step);
nextButton.setEnabled(nextEnabled);
// set whether cancel step is enabled or not.
boolean cancelAvailable =
!model.isLastStep(step) && ws.isCancelEnabled();
cancelButton.setEnabled(cancelAvailable);
// set whether finish step is enabled or not.
finishButton.setEnabled(model.isLastStep(step));
}
}
|
package org.jdesktop.swingx.decorator;
import java.util.BitSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Vector;
import javax.swing.event.EventListenerList;
/**
* <p>A <b><code>FilterPipeline</code></b> is used to define the set of
* {@link org.jdesktop.swingx.decorator.Filter filters}
* for a data-aware component such as a {@link org.jdesktop.swingx.JXList} or a
* {@link org.jdesktop.swingx.JXTable}. Filtering involves interposing one or
* more filters in a {@link org.jdesktop.swingx.decorator.FilterPipeline} between
* a data model and a view to change the apparent order and/or number of records
* in the data model. The order of filters in the filter pipeline determines the
* order in which each filter is applied. The output from one filter in the
* pipeline is piped as the input to the next filter in the pipeline.</p>
*
* <pre>
* {@link org.jdesktop.swingx.decorator.Filter}[] filters = new {@link org.jdesktop.swingx.decorator.Filter}[] {
* new {@link org.jdesktop.swingx.decorator.PatternFilter}("S.*", 0, 1), // regex, matchflags, column
* new {@link org.jdesktop.swingx.decorator.ShuttleSorter}(1, false), // column 1, descending
* new {@link org.jdesktop.swingx.decorator.ShuttleSorter}(0, true), // column 0, ascending
* };
* {@link org.jdesktop.swingx.decorator.FilterPipeline} pipeline = new {@link org.jdesktop.swingx.decorator.FilterPipeline}(filters);
* {@link org.jdesktop.swingx.JXTable} table = new {@link org.jdesktop.swingx.JXTable}(model);
* table.setFilters(pipeline);
* </pre>
*
* This is all you need to do in order to use <code>FilterPipeline</code>. Most
* of the methods in this class are only for advanced developers who want to write
* their own filter subclasses and want to override the way a filter pipeline works.
*
* @author Ramesh Gupta
* @see org.jdesktop.swingx.decorator.Filter
*/
public class FilterPipeline {
protected EventListenerList listenerList = new EventListenerList();
private ComponentAdapter adapter = null;
private Sorter sorter = null;
private final Filter[] filters;
private SortController sortController;
/**
* Creates an empty open pipeline.
*
*/
public FilterPipeline() {
this(new Filter[] {});
}
/**
* Constructs a new <code>FilterPipeline</code> populated with the specified
* filters that are applied in the order they appear in the list. Since filters
* maintain state about the view to which they are attached, an instance of
* a filter may not ever be used in more than one pipeline.
*
* @param inList array of filters
*/
public FilterPipeline(Filter[] inList) {
filters = reorderSorters(inList, locateSorters(inList));
assignFilters();
}
/*
* JW let each contained filter assign both order and pipeline.
* Now we have a invariant
*
* (containedFilter.order >= 0) && (containedFilter.pipeline != null)
*
* which simplifies access logic (IMO)
*
*/
private void assignFilters() {
for (int i = 0; i < filters.length; i++) {
// JW: changed to bind early and move
// binding responsibility to filter
// instead of fiddling around in other's bowels
filters[i].assign(this, i);
}
}
/**
* Sets the sorter that the output of the filter pipeline is piped through.
* This is the sorter that is installed interactively on a view by a user
* action.
*
* This method is responsible for doing all the bookkeeping to assign/cleanup
* pipeline/adapter assignments.
*
* @param sorter the interactive sorter, if any; null otherwise.
*/
protected void setSorter(Sorter sorter) {
Sorter oldSorter = getSorter();
if (oldSorter == sorter) return;
if (oldSorter != null) {
oldSorter.assign((FilterPipeline) null);
}
this.sorter = sorter;
if (sorter != null) {
sorter.assign((FilterPipeline) null);
sorter.assign(this);
if (adapter != null) {
sorter.assign(adapter);
sorter.refresh();
}
}
if ((sorter == null) && isAssigned()) {
fireContentsChanged();
}
}
/**
* Returns the sorter that the output of the filter pipeline is piped through.
* This is the sorter that is installed interactively on a view by a user
* action.
*
* @return the interactive sorter, if any; null otherwise.
*/
protected Sorter getSorter() {
return sorter;
}
public SortController getSortController() {
if (sortController == null) {
sortController = createDefaultSortController();
}
return sortController;
}
protected SortController createDefaultSortController() {
return new SorterBasedSortController();
}
protected class SorterBasedSortController implements SortController {
public void toggleSortOrder(int column) {
toggleSortOrder(column, null);
}
public void toggleSortOrder(int column, Comparator comparator) {
Sorter currentSorter = getSorter();
if ((currentSorter != null) && (currentSorter.getColumnIndex() == column)) {
// JW: think about logic - need to update comparator?
currentSorter.toggle();
} else {
setSorter(createDefaultSorter(new SortKey(SortOrder.ASCENDING, column, comparator)));
}
}
public void setSortKeys(List<? extends SortKey> keys) {
if ((keys == null) || keys.isEmpty()) {
setSorter(null);
return;
}
SortKey sortKey = SortKey.getFirstSortingKey(keys);
// only crappy unsorted...
if (sortKey == null) return;
Sorter sorter = getSorter();
if (sorter == null) {
sorter = createDefaultSorter();
}
sorter.setSortKey(sortKey);
// technically, we could re-use the sorter
// and only reset column, comparator and direction
// need to detangle from TableColumn before going there...
// so for now we only change the order if we have a sorter
// for the given column, create a new default sorter if not
// if ((currentSorter == null) ||
// (currentSorter.getColumnIndex() != sortKey.getColumn())) {
// currentSorter = createDefaultSorter(sortKey);
// if (currentSorter.isAscending() != sortKey.getSortOrder().isAscending()) {
// currentSorter.setAscending(sortKey.getSortOrder().isAscending());
setSorter(sorter);
}
/**
* creates a Sorter initialized with sortKey
* @param sortKey the properties to use
* @return <code>Sorter</code> initialized with the specified <code>sortKey</code>
*/
protected Sorter createDefaultSorter(SortKey sortKey) {
Sorter sorter = createDefaultSorter();
sorter.setSortKey(sortKey);
return sorter;
}
protected Sorter createDefaultSorter() {
return new ShuttleSorter();
}
public List<? extends SortKey> getSortKeys() {
Sorter sorter = getSorter();
if (sorter == null) {
return Collections.EMPTY_LIST;
}
return Collections.singletonList(sorter.getSortKey());
}
public SortOrder getSortOrder(int column) {
Sorter sorter = getSorter();
if ((sorter == null) || (sorter.getColumnIndex() != column)) {
return SortOrder.UNSORTED;
}
return sorter.getSortOrder();
}
}
public final void assign(ComponentAdapter adapter) {
if (adapter == null) {
throw new IllegalArgumentException("null adapter");
}
// also assign individual filters when adapter is bound
if (this.adapter == null) {
this.adapter = adapter;
for (int i = 0; i < filters.length; i++) {
filters[i].assign(adapter);
}
if (sorter != null) {
sorter.assign(adapter);
}
flush();
}
else if (this.adapter != adapter){
throw new IllegalStateException("Can't bind to a different adapter");
}
}
/**
*
* @return true if an adapter has been assigned, false otherwise
*/
public boolean isAssigned() {
return adapter != null;
}
/**
* Returns true if this pipeline contains the specified filter;
* otherwise it returns false.
*
* @param filter filter whose membership in this pipeline is tested
* @return true if this pipeline contains the specified filter;
* otherwise it returns false
* @throws NullPointerException if filter == null
*
*/
boolean contains(Filter filter) {
return (filter.equals(sorter)) ||
(filter.order >= 0) &&
(filters.length > 0) &&
(filters[filter.order] == filter);
}
/**
* Returns the first filter, if any, in this pipeline, or null, if there are
* no filters in this pipeline.
*
* @return the first filter, if any, in this pipeline, or null, if there are
* no filters in this pipeline
*/
Filter first() {
return (filters.length > 0) ? filters[0] : null;
}
/**
* Returns the last filter, if any, in this pipeline, or null, if there are
* no filters in this pipeline.
*
* @return the last filter, if any, in this pipeline, or null, if there are
* no filters in this pipeline
*/
Filter last() {
if (sorter != null) return sorter;
return (filters.length > 0) ? filters[filters.length - 1] : null;
}
/**
* Returns the filter after the supplied filter in this pipeline, or null,
* if there aren't any filters after the supplied filter.
*
* @param filter a filter in this pipeline
* @return the filter after the supplied filter in this pipeline, or null,
* if there aren't any filters after the supplied filter
*/
Filter next(Filter filter) {
if (last().equals(filter))
return null;
return filter.order + 1 < filters.length ? filters[filter.order + 1]
: getSorter();
}
/**
* Returns the filter before the supplied filter in this pipeline,
* or null, if there aren't any filters before the supplied filter.
*
* @param filter a filter in this pipeline
* @return the filter before the supplied filter in this pipeline,
* or null, if there aren't any filters before the supplied filter
*/
Filter previous(Filter filter) {
if (filter.equals(sorter)) return filters.length > 0 ? filters[filters.length - 1] : null;
return first().equals(filter) ? null : filters[filter.order - 1];
}
/**
* Called when the specified filter has changed.
* Cascades <b><code>filterChanged</code></b> notifications to the next
* filter in the pipeline after the specified filter. If the specified filter
* is the last filter in the pipeline, this method broadcasts a
* <b><code>filterChanged</code></b> notification to all
* <b><code>PipelineListener</code></b> objects registered with this pipeline.
*
* @param filter a filter in this pipeline that has changed in any way
*/
protected void filterChanged(Filter filter) {
// JW: quick partial fix for #370-swingx: don't
// fire if there are no active filters/and no sorter.
// can't do anything if we have filters/sorters
// because we have no notion to turn "auto-flush on model update" off
// (Mustang does - and has it off by default)
if ((filter instanceof IdentityFilter) && (getSorter() == null)) return;
Filter next = next(filter);
if (next == null) {
// prepared for additional event type
// if (filter == getSorter()) {
// fireSortOrderChanged();
fireContentsChanged();
}
else {
next.refresh(); // Cascade to next filter
}
}
/**
* returns the unfiltered data adapter size or 0 if unassigned.
*
* @return the unfiltered data adapter size or 0 if unassigned
*/
public int getInputSize() {
return isAssigned() ? adapter.getRowCount() : 0;
}
/**
* @param filter
* @return returns the unfiltered data adapter size or 0 if unassigned.
*/
int getInputSize(Filter filter) {
Filter previous = previous(filter);
if (previous != null) {
return previous.getSize();
}
// fixed issue #64-swingx - removed precondition... (was: isAssigned())
return getInputSize();
}
/**
* Returns the number of records in the filtered view.
*
* @return the number of records in the filtered view
*/
public int getOutputSize() {
// JW: don't need to check - but that's heavily dependent on the
// implementation detail that there's always the identityFilter
// (which might change any time)
if (!isAssigned()) return 0;
Filter last = last();
return (last == null) ? adapter.getRowCount() : last.getSize();
}
/**
* Convert row index from view coordinates to model coordinates
* accounting for the presence of sorters and filters. This is essentially
* a pass-through to the {@link org.jdesktop.swingx.decorator.Filter#convertRowIndexToModel(int) convertRowIndexToModel}
* method of the <em>last</em> {@link org.jdesktop.swingx.decorator.Filter},
* if any, in this pipeline.
*
* @param row row index in view coordinates
* @return row index in model coordinates
*/
public int convertRowIndexToModel(int row) {
Filter last = last();
return (last == null) ? row : last.convertRowIndexToModel(row);
}
/**
* Convert row index from model coordinates to view coordinates
* accounting for the presence of sorters and filters. This is essentially
* a pass-through to the {@link org.jdesktop.swingx.decorator.Filter#convertRowIndexToView(int) convertRowIndexToModel}
* method of the <em>last</em> {@link org.jdesktop.swingx.decorator.Filter},
* if any, in this pipeline.
*
* @param row row index in model coordinates
* @return row index in view coordinates
*/
public int convertRowIndexToView(int row) {
Filter last = last();
return (last == null) ? row : last.convertRowIndexToView(row);
}
/**
* Returns the value of the cell at the specified coordinates.
*
*
* @param row in view coordinates
* @param column in model coordinates
* @return the value of the cell at the specified coordinates
*/
public Object getValueAt(int row, int column) {
// JW: this impl relies on the fact that there's always the
// identity filter installed
// should use adapter if assigned and no filter
Filter last = last();
return (last == null) ? null : last.getValueAt(row, column);
}
public void setValueAt(Object aValue, int row, int column) {
// JW: this impl relies on the fact that there's always the
// identity filter installed
// should use adapter if assigned and no filter
Filter last = last();
if (last != null) {
last.setValueAt(aValue, row, column);
}
}
public boolean isCellEditable(int row, int column) {
// JW: this impl relies on the fact that there's always the
// identity filter installed
// should use adapter if assigned and no filter
Filter last = last();
return (last == null) ? false : last.isCellEditable(row, column);
}
/**
* Flushes the pipeline by initiating a {@link org.jdesktop.swingx.decorator.Filter#refresh() refresh}
* on the <em>first</em> {@link org.jdesktop.swingx.decorator.Filter filter},
* if any, in this pipeline. After that filter has refreshed itself, it sends a
* {@link #filterChanged(org.jdesktop.swingx.decorator.Filter) filterChanged}
* notification to this pipeline, and the pipeline responds by initiating a
* {@link org.jdesktop.swingx.decorator.Filter#refresh() refresh}
* on the <em>next</em> {@link org.jdesktop.swingx.decorator.Filter filter},
* if any, in this pipeline. Eventualy, when there are no more filters left
* in the pipeline, it broadcasts a {@link org.jdesktop.swingx.decorator.PipelineEvent}
* signaling a {@link org.jdesktop.swingx.decorator.PipelineEvent#CONTENTS_CHANGED}
* message to all {@link org.jdesktop.swingx.decorator.PipelineListener} objects
* registered with this pipeline.
*/
public void flush() {
// JW PENDING: use first!
if ((filters != null) && (filters.length > 0)) {
filters[0].refresh();
}
else if (sorter != null) {
sorter.refresh();
}
}
/**
* Adds a listener to the list that's notified each time there is a change
* to this pipeline.
*
* @param l the <code>PipelineListener</code> to be added
*/
public void addPipelineListener(PipelineListener l) {
listenerList.add(PipelineListener.class, l);
}
/**
* Removes a listener from the list that's notified each time there is a change
* to this pipeline.
*
* @param l the <code>PipelineListener</code> to be removed
*/
public void removePipelineListener(PipelineListener l) {
listenerList.remove(PipelineListener.class, l);
}
/**
* Returns an array of all the pipeline listeners
* registered on this <code>FilterPipeline</code>.
*
* @return all of this pipeline's <code>PipelineListener</code>s,
* or an empty array if no pipeline listeners
* are currently registered
*
* @see #addPipelineListener
* @see #removePipelineListener
*/
public PipelineListener[] getPipelineListeners() {
return (PipelineListener[]) listenerList.getListeners(
PipelineListener.class);
}
/**
* Notifies all registered {@link org.jdesktop.swingx.decorator.PipelineListener}
* objects that the contents of this pipeline has changed. The event instance
* is lazily created.
*/
protected void fireContentsChanged() {
Object[] listeners = listenerList.getListenerList();
PipelineEvent e = null;
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == PipelineListener.class) {
if (e == null) {
e = new PipelineEvent(this, PipelineEvent.CONTENTS_CHANGED);
}
( (PipelineListener) listeners[i + 1]).contentsChanged(e);
}
}
}
/**
* Notifies all registered {@link org.jdesktop.swingx.decorator.PipelineListener}
* objects that the contents of this pipeline has changed.
*/
protected void fireSortOrderChanged() {
Object[] listeners = listenerList.getListenerList();
PipelineEvent e = null;
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == PipelineListener.class) {
if (e == null) {
e = new PipelineEvent(this, PipelineEvent.SORT_ORDER_CHANGED);
}
( (PipelineListener) listeners[i + 1]).contentsChanged(e);
}
}
}
private List locateSorters(Filter[] inList) {
BitSet sortableColumns = new BitSet(); // temporary structure for checking
List sorterLocations = new Vector();
for (int i = 0; i < inList.length; i++) {
if (inList[i] instanceof Sorter) {
int columnIndex = inList[i].getColumnIndex();
if (columnIndex < 0) {
throw new IndexOutOfBoundsException(
"Negative column index for filter: " + inList[i]);
}
if (sortableColumns.get(columnIndex)) {
throw new IllegalArgumentException(
"Filter "+ i +" attempting to overwrite sorter for column "
+ columnIndex);
}
sortableColumns.set(columnIndex); // mark column index
sorterLocations.add(new Integer(i)); // mark sorter index
//columnSorterMap.put(new Integer(columnIndex), inList[i]);
}
}
return sorterLocations;
}
private Filter[] reorderSorters(Filter[] inList, List sorterLocations) {
// quick hack for issue #46-swingx: make sure we are open
// without filter.
if (inList.length == 0) {
return new Filter[] {new IdentityFilter()};
}
// always returns a new copy of inList
Filter[] outList = (Filter[]) inList.clone();
// Invert the order of sorters, if any, in outList
int max = sorterLocations.size() - 1;
for (int i = 0; i <= max; i++) {
int orig = ((Integer) sorterLocations.get(max - i)).intValue();
int copy = ((Integer) sorterLocations.get(i)).intValue();
outList[copy] = inList[orig];
}
return outList;
}
public class IdentityFilter extends Filter {
protected void init() {
}
protected void reset() {
}
protected void filter() {
}
public int getSize() {
return getInputSize();
}
protected int mapTowardModel(int row) {
return row;
}
@Override
protected int mapTowardView(int row) {
return row;
}
}
}
|
package backtype.storm.drpc;
import backtype.storm.Constants;
import backtype.storm.ILocalDRPC;
import backtype.storm.drpc.CoordinatedBolt.SourceArgs;
import backtype.storm.generated.StormTopology;
import backtype.storm.generated.StreamInfo;
import backtype.storm.topology.BasicBoltExecutor;
import backtype.storm.topology.IBasicBolt;
import backtype.storm.topology.IRichBolt;
import backtype.storm.topology.InputDeclarer;
import backtype.storm.topology.OutputFieldsGetter;
import backtype.storm.topology.TopologyBuilder;
import backtype.storm.tuple.Fields;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class LinearDRPCTopologyBuilder {
String _function;
List<Component> _components = new ArrayList<Component>();
public LinearDRPCTopologyBuilder(String function) {
_function = function;
}
public LinearDRPCInputDeclarer addBolt(IRichBolt bolt, int parallelism) {
Component component = new Component(bolt, parallelism);
_components.add(component);
return new InputDeclarerImpl(component);
}
public LinearDRPCInputDeclarer addBolt(IRichBolt bolt) {
return addBolt(bolt, 1);
}
public LinearDRPCInputDeclarer addBolt(IBasicBolt bolt, int parallelism) {
return addBolt(new BasicBoltExecutor(bolt), parallelism);
}
public LinearDRPCInputDeclarer addBolt(IBasicBolt bolt) {
return addBolt(bolt, 1);
}
public StormTopology createLocalTopology(ILocalDRPC drpc) {
return createTopology(new DRPCSpout(_function, drpc));
}
public StormTopology createRemoteTopology() {
return createTopology(new DRPCSpout(_function));
}
private StormTopology createTopology(DRPCSpout spout) {
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout(1, spout);
builder.setBolt(2, new PrepareRequest())
.noneGrouping(1);
int id = 3;
for(int i=0; i<_components.size();i++) {
Component component = _components.get(i);
SourceArgs source;
if(i==0) {
source = null;
} else if (i==1) {
source = SourceArgs.single();
} else {
source = SourceArgs.all();
}
boolean allOut = (i < _components.size()-2);
InputDeclarer declarer = builder.setBolt(
id,
new CoordinatedBolt(component.bolt, source, allOut),
component.parallelism);
if(i==0 && component.declarations.size()==0) {
declarer.noneGrouping(2, PrepareRequest.ARGS_STREAM);
} else {
for(InputDeclaration declaration: component.declarations) {
declaration.declare(id-1, declarer);
}
}
if(i>0) {
declarer.directGrouping(id-1, Constants.COORDINATED_STREAM_ID);
}
id++;
}
IRichBolt lastBolt = _components.get(_components.size()-1).bolt;
OutputFieldsGetter getter = new OutputFieldsGetter();
lastBolt.declareOutputFields(getter);
Map<Integer, StreamInfo> streams = getter.getFieldsDeclaration();
if(streams.size()!=1) {
throw new RuntimeException("Must declare exactly one stream from last bolt in LinearDRPCTopology");
}
int outputStream = streams.keySet().iterator().next();
List<String> fields = streams.get(outputStream).get_output_fields();
if(fields.size()!=2) {
throw new RuntimeException("Output stream of last component in LinearDRPCTopology must contain exactly two fields. The first should be the request id, and the second should be the result.");
}
builder.setBolt(id, new JoinResult(2))
.fieldsGrouping(id-1, outputStream, new Fields(fields.get(0)))
.fieldsGrouping(2, PrepareRequest.RETURN_STREAM, new Fields("request"));
id++;
builder.setBolt(id, new ReturnResults())
.noneGrouping(id-1);
return builder.createTopology();
}
private static class Component {
public IRichBolt bolt;
public int parallelism;
public List<InputDeclaration> declarations = new ArrayList<InputDeclaration>();
public Component(IRichBolt bolt, int parallelism) {
this.bolt = bolt;
this.parallelism = parallelism;
}
}
private static interface InputDeclaration {
public void declare(int prevComponent, InputDeclarer declarer);
}
private class InputDeclarerImpl implements LinearDRPCInputDeclarer {
Component _component;
public InputDeclarerImpl(Component component) {
_component = component;
}
@Override
public LinearDRPCInputDeclarer fieldsGrouping(final Fields fields) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(int prevComponent, InputDeclarer declarer) {
declarer.fieldsGrouping(prevComponent, fields);
}
});
return this;
}
@Override
public LinearDRPCInputDeclarer fieldsGrouping(final int streamId, final Fields fields) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(int prevComponent, InputDeclarer declarer) {
declarer.fieldsGrouping(prevComponent, streamId, fields);
}
});
return this;
}
@Override
public LinearDRPCInputDeclarer globalGrouping() {
addDeclaration(new InputDeclaration() {
@Override
public void declare(int prevComponent, InputDeclarer declarer) {
declarer.globalGrouping(prevComponent);
}
});
return this;
}
@Override
public LinearDRPCInputDeclarer globalGrouping(final int streamId) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(int prevComponent, InputDeclarer declarer) {
declarer.globalGrouping(prevComponent, streamId);
}
});
return this;
}
@Override
public LinearDRPCInputDeclarer shuffleGrouping() {
addDeclaration(new InputDeclaration() {
@Override
public void declare(int prevComponent, InputDeclarer declarer) {
declarer.shuffleGrouping(prevComponent);
}
});
return this;
}
@Override
public LinearDRPCInputDeclarer shuffleGrouping(final int streamId) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(int prevComponent, InputDeclarer declarer) {
declarer.shuffleGrouping(prevComponent, streamId);
}
});
return this;
}
@Override
public LinearDRPCInputDeclarer noneGrouping() {
addDeclaration(new InputDeclaration() {
@Override
public void declare(int prevComponent, InputDeclarer declarer) {
declarer.noneGrouping(prevComponent);
}
});
return this;
}
@Override
public LinearDRPCInputDeclarer noneGrouping(final int streamId) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(int prevComponent, InputDeclarer declarer) {
declarer.noneGrouping(prevComponent, streamId);
}
});
return this;
}
@Override
public LinearDRPCInputDeclarer allGrouping() {
addDeclaration(new InputDeclaration() {
@Override
public void declare(int prevComponent, InputDeclarer declarer) {
declarer.allGrouping(prevComponent);
}
});
return this;
}
@Override
public LinearDRPCInputDeclarer allGrouping(final int streamId) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(int prevComponent, InputDeclarer declarer) {
declarer.allGrouping(prevComponent, streamId);
}
});
return this;
}
@Override
public LinearDRPCInputDeclarer directGrouping() {
addDeclaration(new InputDeclaration() {
@Override
public void declare(int prevComponent, InputDeclarer declarer) {
declarer.directGrouping(prevComponent);
}
});
return this;
}
@Override
public LinearDRPCInputDeclarer directGrouping(final int streamId) {
addDeclaration(new InputDeclaration() {
@Override
public void declare(int prevComponent, InputDeclarer declarer) {
declarer.directGrouping(prevComponent, streamId);
}
});
return this;
}
private void addDeclaration(InputDeclaration declaration) {
_component.declarations.add(declaration);
}
}
}
|
package dr.evomodel.branchratemodel;
import dr.evolution.alignment.PatternList;
import dr.evolution.parsimony.FitchParsimony;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.evolution.tree.TreeTrait;
import dr.evolution.tree.TreeTraitProvider;
import dr.evolution.util.TaxonList;
import dr.evomodel.tree.TreeModel;
import dr.inference.model.Model;
import dr.inference.model.Parameter;
import dr.inference.model.Variable;
import dr.xml.*;
import java.util.logging.Logger;
/**
* This Branch Rate Model takes a ancestral state likelihood and
* gives the rate for each branch of the tree based on the child state (for now).
*
* @author Alexei Drummond
* @author Marc Suchard
*/
public class DiscreteTraitBranchRateModel extends AbstractBranchRateModel {
enum Mode {
NODE_STATES,
DWELL_TIMES,
PARSIMONY
}
public static final String DISCRETE_TRAIT_BRANCH_RATE_MODEL = "discreteTraitRateModel";
private TreeTrait trait = null;
private Parameter rateParameter;
private Parameter relativeRatesParameter;
private Parameter indicatorParameter;
private int traitIndex;
private boolean normKnown = false;
private boolean storedNormKnown = false;
private double norm = 1.0;
private double storedNorm = 1.0;
private FitchParsimony fitchParsimony;
private boolean treeChanged = true;
private boolean shouldRestoreTree = false;
private Mode mode;
// private int treeInitializeCounter = 0;
/**
* A constructor for the (crude) parsimony reconstruction form of this class.
* @param treeModel
* @param patternList
* @param traitIndex
* @param ratesParameter
*/
public DiscreteTraitBranchRateModel(TreeModel treeModel, PatternList patternList, int traitIndex, Parameter ratesParameter) {
this(treeModel, traitIndex, ratesParameter, null, null);
if (!TaxonList.Utils.getTaxonListIdSet(treeModel).equals(TaxonList.Utils.getTaxonListIdSet(patternList))) {
throw new IllegalArgumentException("Tree model and pattern list must have the same list of taxa!");
}
fitchParsimony = new FitchParsimony(patternList, false);
mode = Mode.PARSIMONY;
}
/**
* A constructor for a node-sampled discrete trait
* @param treeModel
* @param trait
* @param traitIndex
* @param rateParameter
* @param relativeRatesParameter
* @param indicatorParameter
*/
public DiscreteTraitBranchRateModel(TreeModel treeModel, TreeTrait trait, int traitIndex,
Parameter rateParameter, Parameter relativeRatesParameter, Parameter indicatorParameter) {
this(treeModel, traitIndex, rateParameter, relativeRatesParameter, indicatorParameter);
// if (trait.getTreeModel() != treeModel)
this.trait = trait;
if (trait.getTraitName().equals("states")) {
// Assume the trait is one or more discrete traits reconstructed at nodes
mode = Mode.NODE_STATES;
} else /*if (double[].class.isAssignableFrom(trait.getClass()))*/ {
// Assume the trait itself is the dwell times for the individual states on the branch above the node
mode = Mode.DWELL_TIMES;
if (trait instanceof Model) {
addModel((Model)trait);
}
}
private DiscreteTraitBranchRateModel(TreeModel treeModel, int traitIndex,
Parameter rateParameter, Parameter relativeRatesParameter, Parameter indicatorParameter) {
super(DISCRETE_TRAIT_BRANCH_RATE_MODEL);
addModel(treeModel);
this.traitIndex = traitIndex;
this.rateParameter = rateParameter;
addVariable(rateParameter);
this.relativeRatesParameter = relativeRatesParameter;
if (relativeRatesParameter != null) {
addVariable(relativeRatesParameter);
}
this.indicatorParameter = indicatorParameter;
if (indicatorParameter != null) {
addVariable(indicatorParameter);
}
// double[] dwellTimes = getDwellTimes(treeModel, treeModel.getExternalNode(0));
// if (indicatorParameter != null) {
// if (dwellTimes.length != indicatorParameter.getDimension()) {
// } else {
// if (dwellTimes.length != rateParameter.getDimension()) {
}
public void handleModelChangedEvent(Model model, Object object, int index) {
// TreeModel has changed...
normKnown = false;
if (model instanceof TreeModel) {
treeChanged = true;
shouldRestoreTree = true;
}
fireModelChanged();
}
protected final void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
// Rate Parameters have changed
//ratesCalculated = false;
normKnown = false;
fireModelChanged();
}
protected void storeState() {
storedNormKnown = normKnown;
storedNorm = norm;
shouldRestoreTree = false;
}
protected void restoreState() {
normKnown = storedNormKnown;
norm = storedNorm;
treeChanged = shouldRestoreTree;
}
protected void acceptState() {
// nothing to do
}
public double getBranchRate(final Tree tree, final NodeRef node) {
// if (!normKnown) {
// norm = calculateNorm(tree);
// normKnown = true;
// return getRawBranchRate(tree, node) / norm;
// AR - I am not sure the normalization is required here?
return getRawBranchRate(tree, node);
}
double calculateNorm(Tree tree) {
double time = 0.0;
double rateTime = 0.0;
for (int i = 0; i < tree.getNodeCount(); i++) {
NodeRef node = tree.getNode(i);
if (!tree.isRoot(node)) {
double branchTime = tree.getBranchLength(node);
rateTime += getRawBranchRate(tree, node) * branchTime;
time += branchTime;
}
}
return rateTime / time;
}
double getRawBranchRate(final Tree tree, final NodeRef node) {
double rate = 0.0;
double[] dwellTimes = getDwellTimes(tree, node);
double totalTime = 0;
if (indicatorParameter != null) {
double absRate = rateParameter.getParameterValue(0);
for (int i = 0; i < indicatorParameter.getDimension(); i++) {
int index = (int)indicatorParameter.getParameterValue(i);
if (index == 0) {
rate += absRate * dwellTimes[i];
} else {
rate += (absRate * (1.0 + relativeRatesParameter.getParameterValue(index - 1))) * dwellTimes[i];
}
totalTime += dwellTimes[i];
}
} else {
for (int i = 0; i < rateParameter.getDimension(); i++) {
rate += rateParameter.getParameterValue(i) * dwellTimes[i];
totalTime += dwellTimes[i];
}
}
rate /= totalTime;
return rate;
}
private double[] getDwellTimes(final Tree tree, final NodeRef node) {
double[] dwellTimes = null;
double branchTime = tree.getBranchLength(node);
if (mode == Mode.DWELL_TIMES) {
dwellTimes = (double[])trait.getTrait(tree, node);
} else if (mode == Mode.PARSIMONY) {
// an approximation to dwell times using parsimony, assuming
// the state changes midpoint on the tree. Does a weighted
// average of the equally parsimonious state reconstructions
// at the top and bottom of each branch.
if (treeChanged) {
fitchParsimony.initialize(tree);
// Debugging test to count work
// treeInitializeCounter += 1;
// if (treeInitializeCounter % 10 == 0) {
// System.err.println("Cnt: "+treeInitializeCounter);
treeChanged = false;
}
int[] states = fitchParsimony.getStates(tree, node);
int[] parentStates = fitchParsimony.getStates(tree, tree.getParent(node));
dwellTimes = new double[fitchParsimony.getPatterns().getStateCount()];
for (int state : states) {
dwellTimes[state] += branchTime / 2;
}
for (int state : parentStates) {
dwellTimes[state] += branchTime / 2;
}
for (int i = 0; i < dwellTimes.length; i++) {
// normalize by the number of equally parsimonious states at each end of the branch
// dwellTimes should add up to the total branch length
dwellTimes[i] /= (states.length + parentStates.length) / 2;
}
} else if (mode == Mode.NODE_STATES) {
if (indicatorParameter != null) {
dwellTimes = new double[indicatorParameter.getDimension()];
} else {
dwellTimes = new double[rateParameter.getDimension()];
}
// if the states are being sampled - then there is only one possible state at each
// end of the branch.
int state = ((int[])trait.getTrait(tree, node))[traitIndex];
dwellTimes[state] += branchTime / 2;
int parentState = ((int[])trait.getTrait(tree, node))[traitIndex];
dwellTimes[parentState] += branchTime / 2;
}
return dwellTimes;
}
}
|
package dr.evomodelxml.substmodel;
import dr.evolution.datatype.*;
import dr.evomodel.substmodel.*;
import dr.evoxml.util.DataTypeUtils;
import dr.inference.model.Parameter;
import dr.xml.*;
import java.util.logging.Logger;
/**
* Parses a GeneralSubstitutionModel or one of its more specific descendants.
*/
public class GeneralSubstitutionModelParser extends AbstractXMLObjectParser {
public static final String GENERAL_SUBSTITUTION_MODEL = "generalSubstitutionModel";
public static final String DATA_TYPE = "dataType";
public static final String RATES = "rates";
public static final String RELATIVE_TO = "relativeTo";
public static final String FREQUENCIES = "frequencies";
public static final String INDICATOR = "rateIndicator";
public static final String ROOT_FREQ = "rootFrequencies";
public String getParserName() {
return GENERAL_SUBSTITUTION_MODEL;
}
public String[] getParserNames() {
return new String[]{getParserName(), SVSGeneralSubstitutionModel.SVS_GENERAL_SUBSTITUTION_MODEL};
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
Parameter ratesParameter;
Parameter indicatorParameter;
XMLObject cxo = xo.getChild(FREQUENCIES);
FrequencyModel freqModel = (FrequencyModel) cxo.getChild(FrequencyModel.class);
DataType dataType = DataTypeUtils.getDataType(xo);
if (dataType == null) dataType = (DataType) xo.getChild(DataType.class);
// if (xo.hasAttribute(DataType.DATA_TYPE)) {
// String dataTypeStr = xo.getStringAttribute(DataType.DATA_TYPE);
// if (dataTypeStr.equals(Nucleotides.DESCRIPTION)) {
// dataType = Nucleotides.INSTANCE;
// } else if (dataTypeStr.equals(AminoAcids.DESCRIPTION)) {
// dataType = AminoAcids.INSTANCE;
// } else if (dataTypeStr.equals(Codons.DESCRIPTION)) {
// dataType = Codons.UNIVERSAL;
// } else if (dataTypeStr.equals(TwoStates.DESCRIPTION)) {
// dataType = TwoStates.INSTANCE;
if (dataType == null) dataType = freqModel.getDataType();
if (dataType != freqModel.getDataType()) {
throw new XMLParseException("Data type of " + getParserName() + " element does not match that of its frequencyModel.");
}
cxo = xo.getChild(RATES);
ratesParameter = (Parameter) cxo.getChild(Parameter.class);
int states = dataType.getStateCount();
Logger.getLogger("dr.evomodel").info(" General Substitution Model (stateCount=" + states + ")");
int rateCount = ((dataType.getStateCount() - 1) * dataType.getStateCount()) / 2;
if (xo.hasChildNamed(INDICATOR)) {// has indicator
if (ratesParameter.getDimension() != rateCount) {
throw new XMLParseException("Rates parameter in " + getParserName() + " element should have " + (rateCount)
+ " dimensions. However parameter dimension is " + ratesParameter.getDimension());
}
if (cxo.hasAttribute(RELATIVE_TO)) {
throw new XMLParseException(RELATIVE_TO + " attribute is not allowed in SVS general substitution model.");
}
cxo = xo.getChild(INDICATOR);
indicatorParameter = (Parameter) cxo.getChild(Parameter.class);
if (indicatorParameter == null || ratesParameter == null || indicatorParameter.getDimension() != ratesParameter.getDimension())
throw new XMLParseException("Rates and indicator parameters in " + getParserName() + " element must be the same dimension.");
if (xo.hasChildNamed(ROOT_FREQ)) {
cxo = xo.getChild(ROOT_FREQ);
FrequencyModel rootFreq = (FrequencyModel) cxo.getChild(FrequencyModel.class);
if (dataType != rootFreq.getDataType()) {
throw new XMLParseException("Data type of " + getParserName() + " element does not match that of its rootFrequencyModel.");
}
Logger.getLogger("dr.evomodel").info(" SVS Irreversible Substitution Model is applied with "
+ INDICATOR + " " + indicatorParameter.getParameterName() + " and " + ROOT_FREQ + " " + rootFreq.getId());
return new SVSIrreversibleSubstitutionModel(dataType, freqModel, rootFreq, ratesParameter, indicatorParameter);
}
Logger.getLogger("dr.evomodel").info(" SVS General Substitution Model is applied with "
+ INDICATOR + " " + indicatorParameter.getParameterName());
return new SVSGeneralSubstitutionModel(dataType, freqModel, ratesParameter, indicatorParameter);
} else if (xo.getName().equalsIgnoreCase(GENERAL_SUBSTITUTION_MODEL)) {// no indicator
if (!cxo.hasAttribute(RELATIVE_TO)) {
throw new XMLParseException("The index of the implicit rate (value 1.0) that all other rates are relative to."
+ " In DNA this is usually G<->T (6)");
}
int relativeTo = cxo.getIntegerAttribute(RELATIVE_TO) - 1;
if (relativeTo < 0) {
throw new XMLParseException(RELATIVE_TO + " must be 1 or greater");
} else {
int t = relativeTo;
int s = states - 1;
int row = 0;
while (t >= s) {
t -= s;
s -= 1;
row += 1;
}
int col = t + row + 1;
Logger.getLogger("dr.evomodel").info(" Rates relative to "
+ dataType.getCode(row) + "<->" + dataType.getCode(col));
}
if (ratesParameter == null) {
if (rateCount == 1) {
// simplest model for binary traits...
} else {
throw new XMLParseException("No rates parameter found in " + getParserName());
}
} else if (ratesParameter.getDimension() != (rateCount - 1)) {
throw new XMLParseException("Rates parameter in " + getParserName() + " element should have ("
+ rateCount + "- 1) dimensions because one of dimensions is fixed.");
}
return new GeneralSubstitutionModel(dataType, freqModel, ratesParameter, relativeTo);
} else {
throw new XMLParseException(SVSGeneralSubstitutionModel.SVS_GENERAL_SUBSTITUTION_MODEL
+ " needs " + INDICATOR + " !");
}
}
|
package dr.inference.operators.hmc;
import dr.inference.hmc.PathGradient;
import dr.inference.hmc.GradientWrtParameterProvider;
import dr.inference.model.Likelihood;
import dr.inference.model.Parameter;
import dr.inference.operators.AbstractCoercableOperator;
import dr.inference.operators.CoercionMode;
import dr.inference.operators.GeneralOperator;
import dr.math.MultivariateFunction;
import dr.math.NumericalDerivative;
import dr.math.matrixAlgebra.ReadableVector;
import dr.math.matrixAlgebra.WrappedVector;
import dr.inference.operators.PathDependent;
import dr.math.MathUtils;
import dr.util.Transform;
/**
* @author Max Tolkoff
* @author Marc A. Suchard
*/
public class HamiltonianMonteCarloOperator extends AbstractCoercableOperator
implements GeneralOperator, PathDependent {
final GradientWrtParameterProvider gradientProvider;
protected double stepSize;
final LeapFrogEngine leapFrogEngine;
private final Parameter parameter;
final MassPreconditioner preconditioning;
private final Options runtimeOptions;
protected final double[] mask;
protected final Transform transform;
HamiltonianMonteCarloOperator(CoercionMode mode, double weight, GradientWrtParameterProvider gradientProvider,
Parameter parameter, Transform transform, Parameter mask,
double stepSize, int nSteps,
double randomStepCountFraction,
double gradientCheckTolerance) {
this(mode, weight, gradientProvider,
parameter, transform, mask,
new Options(stepSize, nSteps, randomStepCountFraction,
0, 0, 0, gradientCheckTolerance,
10, 0.1),
MassPreconditioner.Type.NONE
);
}
public HamiltonianMonteCarloOperator(CoercionMode mode, double weight,
GradientWrtParameterProvider gradientProvider,
Parameter parameter, Transform transform, Parameter maskParameter,
Options runtimeOptions,
MassPreconditioner.Type preconditioningType) {
super(mode);
setWeight(weight);
setTargetAcceptanceProbability(0.8); // Stan default
this.gradientProvider = gradientProvider;
this.runtimeOptions = runtimeOptions;
this.stepSize = runtimeOptions.initialStepSize;
this.preconditioning = preconditioningType.factory(gradientProvider, transform);
this.parameter = parameter;
this.mask = buildMask(maskParameter);
this.transform = transform;
this.leapFrogEngine = (transform != null ?
new LeapFrogEngine.WithTransform(parameter, transform,
getDefaultInstabilityHandler(), preconditioning, mask) :
new LeapFrogEngine.Default(parameter,
getDefaultInstabilityHandler(), preconditioning, mask));
}
@Override
public String getPerformanceSuggestion() {
return null;
}
@Override
public String getOperatorName() {
return "Vanilla HMC operator";
}
private boolean shouldUpdatePreconditioning() {
return ((runtimeOptions.preconditioningUpdateFrequency > 0)
&& (((getCount() % runtimeOptions.preconditioningUpdateFrequency == 0)
&& (getCount() > runtimeOptions.preconditioningDelay))
|| (getCount() == runtimeOptions.preconditioningDelay)));
}
private static double[] buildMask(Parameter maskParameter) {
if (maskParameter == null) return null;
double[] mask = new double[maskParameter.getDimension()];
for (int i = 0; i < mask.length; ++i) {
mask[i] = (maskParameter.getParameterValue(i) == 0.0) ? 0.0 : 1.0;
}
return mask;
}
@Override
public double doOperation() {
throw new RuntimeException("Should not be executed");
}
@Override
public double doOperation(Likelihood joint) {
if (shouldCheckStepSize()) {
checkStepSize();
}
if (shouldCheckGradient()) {
checkGradient(joint);
}
if (shouldUpdatePreconditioning()) {
preconditioning.updateMass();
}
try {
return leapFrog();
} catch (NumericInstabilityException e) {
return Double.NEGATIVE_INFINITY;
}
}
@Override
public void setPathParameter(double beta) {
if (gradientProvider instanceof PathGradient) {
((PathGradient) gradientProvider).setPathParameter(beta);
}
}
private boolean shouldCheckStepSize() {
return getCount() < 1 && getMode() == CoercionMode.COERCION_ON;
}
private void checkStepSize() {
double[] initialPosition = parameter.getParameterValues();
int iterations = 0;
boolean acceptableSize = false;
while (!acceptableSize && iterations < runtimeOptions.checkStepSizeMaxIterations) {
try {
leapFrog();
double logLikelihood = gradientProvider.getLikelihood().getLogLikelihood();
if (!Double.isNaN(logLikelihood) && !Double.isInfinite(logLikelihood)) {
acceptableSize = true;
}
} catch (AssertionError error) {
// Do nothing
} catch (Exception exception) {
// Do nothing
}
if (!acceptableSize) {
stepSize *= runtimeOptions.checkStepSizeReductionFactor;
}
ReadableVector.Utils.setParameter(initialPosition, parameter); // Restore initial position
++iterations;
}
if (!acceptableSize) {
throw new RuntimeException("Unable to find acceptable initial HMC step-size");
}
}
private boolean shouldCheckGradient() {
return getCount() < runtimeOptions.gradientCheckCount;
}
private void checkGradient(final Likelihood joint) {
if (parameter.getDimension() != gradientProvider.getDimension()) {
throw new RuntimeException("Unequal dimensions");
}
MultivariateFunction numeric = new MultivariateFunction() {
@Override
public double evaluate(double[] argument) {
if (transform == null) {
ReadableVector.Utils.setParameter(argument, parameter);
return joint.getLogLikelihood();
} else {
double[] untransformedValue = transform.inverse(argument, 0, argument.length);
ReadableVector.Utils.setParameter(untransformedValue, parameter);
return joint.getLogLikelihood() - transform.getLogJacobian(untransformedValue, 0, untransformedValue.length);
}
}
@Override
public int getNumArguments() {
return parameter.getDimension();
}
@Override
public double getLowerBound(int n) {
return parameter.getBounds().getLowerLimit(n);
}
@Override
public double getUpperBound(int n) {
return parameter.getBounds().getUpperLimit(n);
}
};
double[] analyticalGradientOriginal = gradientProvider.getGradientLogDensity();
double[] restoredParameterValue = parameter.getParameterValues();
if (transform == null) {
double[] numericGradientOriginal = NumericalDerivative.gradient(numeric, parameter.getParameterValues());
if (!MathUtils.isClose(analyticalGradientOriginal, numericGradientOriginal, runtimeOptions.gradientCheckTolerance)) {
String sb = "Gradients do not match:\n" +
"\tAnalytic: " + new WrappedVector.Raw(analyticalGradientOriginal) + "\n" +
"\tNumeric : " + new WrappedVector.Raw(numericGradientOriginal) + "\n";
throw new RuntimeException(sb);
}
} else {
double[] transformedParameter = transform.transform(parameter.getParameterValues(), 0,
parameter.getParameterValues().length);
double[] numericGradientTransformed = NumericalDerivative.gradient(numeric, transformedParameter);
double[] analyticalGradientTransformed = transform.updateGradientLogDensity(analyticalGradientOriginal,
parameter.getParameterValues(), 0, parameter.getParameterValues().length);
if (!MathUtils.isClose(analyticalGradientTransformed, numericGradientTransformed, runtimeOptions.gradientCheckTolerance)) {
String sb = "Transformed Gradients do not match:\n" +
"\tAnalytic: " + new WrappedVector.Raw(analyticalGradientTransformed) + "\n" +
"\tNumeric : " + new WrappedVector.Raw(numericGradientTransformed) + "\n";
throw new RuntimeException(sb);
}
}
ReadableVector.Utils.setParameter(restoredParameterValue, parameter);
}
static double[] mask(double[] vector, double[] mask) {
assert (mask == null || mask.length == vector.length);
if (mask != null) {
for (int i = 0; i < vector.length; ++i) {
vector[i] *= mask[i];
}
}
return vector;
}
static WrappedVector mask(WrappedVector vector, double[] mask) {
assert (mask == null || mask.length == vector.getDim());
if (mask != null) {
for (int i = 0; i < vector.getDim(); ++i) {
vector.set(i, vector.get(i) * mask[i]);
}
}
return vector;
}
private static final boolean DEBUG = false;
public static class Options {
final double initialStepSize;
final int nSteps;
final double randomStepCountFraction;
final int preconditioningUpdateFrequency;
final int preconditioningDelay;
final int gradientCheckCount;
final double gradientCheckTolerance;
final int checkStepSizeMaxIterations;
final double checkStepSizeReductionFactor;
public Options(double initialStepSize, int nSteps, double randomStepCountFraction, int preconditioningUpdateFrequency,
int preconditioningDelay, int gradientCheckCount, double gradientCheckTolerance,
int checkStepSizeMaxIterations, double checkStepSizeReductionFactor) {
this.initialStepSize = initialStepSize;
this.nSteps = nSteps;
this.randomStepCountFraction = randomStepCountFraction;
this.preconditioningUpdateFrequency = preconditioningUpdateFrequency;
this.preconditioningDelay = preconditioningDelay;
this.gradientCheckCount = gradientCheckCount;
this.gradientCheckTolerance = gradientCheckTolerance;
this.checkStepSizeMaxIterations = checkStepSizeMaxIterations;
this.checkStepSizeReductionFactor = checkStepSizeReductionFactor;
}
}
static class NumericInstabilityException extends Exception { }
private int getNumberOfSteps() {
int count = runtimeOptions.nSteps;
if (runtimeOptions.randomStepCountFraction > 0.0) {
double draw = count * (1.0 + runtimeOptions.randomStepCountFraction * (MathUtils.nextDouble() - 0.5));
count = Math.max(1, (int) draw);
}
return count;
}
double getKineticEnergy(ReadableVector momentum) {
final int dim = momentum.getDim();
double energy = 0.0;
for (int i = 0; i < dim; i++) {
energy += momentum.get(i) * preconditioning.getVelocity(i, momentum);
}
return energy / 2.0;
}
private double leapFrog() throws NumericInstabilityException {
if (DEBUG) {
System.err.println("HMC step size: " + stepSize);
}
final double[] position = leapFrogEngine.getInitialPosition();
final WrappedVector momentum = mask(preconditioning.drawInitialMomentum(), mask);
final double prop = getKineticEnergy(momentum) +
leapFrogEngine.getParameterLogJacobian();
leapFrogEngine.updateMomentum(position, momentum.getBuffer(),
mask(gradientProvider.getGradientLogDensity(), mask), stepSize / 2);
int nStepsThisLeap = getNumberOfSteps();
for (int i = 0; i < nStepsThisLeap; i++) { // Leap-frog
leapFrogEngine.updatePosition(position, momentum, stepSize);
if (i < (nStepsThisLeap - 1)) {
leapFrogEngine.updateMomentum(position, momentum.getBuffer(),
mask(gradientProvider.getGradientLogDensity(), mask), stepSize);
}
}
leapFrogEngine.updateMomentum(position, momentum.getBuffer(),
mask(gradientProvider.getGradientLogDensity(), mask), stepSize / 2);
final double res = getKineticEnergy(momentum) +
leapFrogEngine.getParameterLogJacobian();
return prop - res; //hasting ratio
}
@Override
public double getCoercableParameter() {
return Math.log(stepSize);
}
@Override
public void setCoercableParameter(double value) {
stepSize = Math.exp(value);
}
@Override
public double getRawParameter() {
return stepSize;
}
enum InstabilityHandler {
REJECT {
@Override
void checkValue(double x) throws NumericInstabilityException {
if (Double.isNaN(x)) throw new NumericInstabilityException();
}
},
DEBUG {
@Override
void checkValue(double x) throws NumericInstabilityException {
if (Double.isNaN(x)) {
System.err.println("Numerical instability in HMC momentum; throwing exception");
throw new NumericInstabilityException();
}
}
},
IGNORE {
@Override
void checkValue(double x) {
// Do nothing
}
};
abstract void checkValue(double x) throws NumericInstabilityException;
}
@Override
public void accept(double deviation) {
super.accept(deviation);
preconditioning.storeSecant(
new WrappedVector.Raw(leapFrogEngine.getLastGradient()),
new WrappedVector.Raw(leapFrogEngine.getLastPosition())
);
}
protected InstabilityHandler getDefaultInstabilityHandler() {
if (DEBUG) {
return InstabilityHandler.DEBUG;
} else {
return InstabilityHandler.REJECT;
}
}
interface LeapFrogEngine {
double[] getInitialPosition();
double getParameterLogJacobian();
void updateMomentum(final double[] position,
final double[] momentum,
final double[] gradient,
final double functionalStepSize) throws NumericInstabilityException;
void updatePosition(final double[] position,
final ReadableVector momentum,
final double functionalStepSize);
void setParameter(double[] position);
double[] getLastGradient();
double[] getLastPosition();
class Default implements LeapFrogEngine {
final protected Parameter parameter;
final private InstabilityHandler instabilityHandler;
final private MassPreconditioner preconditioning;
final double[] mask;
double[] lastGradient;
double[] lastPosition;
protected Default(Parameter parameter, InstabilityHandler instabilityHandler,
MassPreconditioner preconditioning,
double[] mask) {
this.parameter = parameter;
this.instabilityHandler = instabilityHandler;
this.preconditioning = preconditioning;
this.mask = mask;
}
@Override
public double[] getInitialPosition() {
return parameter.getParameterValues();
}
@Override
public double getParameterLogJacobian() {
return 0;
}
@Override
public double[] getLastGradient() {
return lastGradient;
}
@Override
public double[] getLastPosition() {
return lastPosition;
}
@Override
public void updateMomentum(double[] position, double[] momentum, double[] gradient,
double functionalStepSize) throws NumericInstabilityException {
final int dim = momentum.length;
for (int i = 0; i < dim; ++i) {
momentum[i] += functionalStepSize * gradient[i];
instabilityHandler.checkValue(momentum[i]);
}
lastGradient = gradient;
lastPosition = position;
}
@Override
public void updatePosition(double[] position, ReadableVector momentum,
double functionalStepSize) {
final int dim = momentum.getDim();
for (int i = 0; i < dim; i++) {
position[i] += functionalStepSize * preconditioning.getVelocity(i, momentum);
}
setParameter(position);
}
public void setParameter(double[] position) {
ReadableVector.Utils.setParameter(position, parameter); // May not work with MaskedParameter?
}
}
class WithTransform extends Default {
final private Transform transform;
double[] unTransformedPosition;
private WithTransform(Parameter parameter, Transform transform,
InstabilityHandler instabilityHandler,
MassPreconditioner preconditioning,
double[] mask) {
super(parameter, instabilityHandler, preconditioning, mask);
this.transform = transform;
}
@Override
public double getParameterLogJacobian() {
return transform.getLogJacobian(unTransformedPosition, 0, unTransformedPosition.length);
}
@Override
public double[] getInitialPosition() {
unTransformedPosition = super.getInitialPosition();
return transform.transform(unTransformedPosition, 0, unTransformedPosition.length);
}
@Override
public void updateMomentum(double[] position, double[] momentum, double[] gradient,
double functionalStepSize) throws NumericInstabilityException {
gradient = transform.updateGradientLogDensity(gradient, unTransformedPosition,
0, unTransformedPosition.length);
mask(gradient, mask);
super.updateMomentum(position, momentum, gradient, functionalStepSize);
}
@Override
public void setParameter(double[] position) {
unTransformedPosition = transform.inverse(position, 0, position.length);
super.setParameter(unTransformedPosition);
}
}
}
}
|
/// TODO : consider symbols that don't appear in the SRS?
package logicrepository.plugins.srs;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Iterator;
import java.util.Set;
//This uses a slightly modified Aho-Corasick automaton
public class PatternMatchAutomaton extends LinkedHashMap<State, HashMap<Symbol, ActionState>> {
private State s0 = new State(0);
private ArrayList<Set<State>> depthMap = new ArrayList<Set<State>>();
private HashMap<State, State> fail;
public PatternMatchAutomaton(SRS srs){
mkGotoMachine(srs, srs.getTerminals());
addFailureTransitions(srs.getTerminals());
}
public PatternMatchAutomaton(SRS srs, Set<Symbol> extraTerminals){
Set<Symbol> terminals = new HashSet<Symbol>();
terminals.addAll(srs.getTerminals());
terminals.addAll(extraTerminals);
mkGotoMachine(srs, terminals);
addFailureTransitions(terminals);
}
private void mkGotoMachine(SRS srs, Set<Symbol> terminals){
State currentState;
put(s0, new HashMap<Symbol, ActionState>());
Set<State> depthStates = new HashSet<State>();
depthStates.add(s0);
depthMap.add(depthStates);
//compute one path through the tree for each lhs
for(Rule r : srs){
currentState = s0;
Sequence pattern = r.getLhs();
int patternRemaining = pattern.size() - 1;
for(Symbol s : pattern){
HashMap<Symbol, ActionState> transition = get(currentState);
ActionState nextActionState = transition.get(s);
State nextState;
if(nextActionState == null){
int nextDepth = currentState.getDepth() + 1;
nextState =
new State(nextDepth);
nextActionState = new ActionState(0, nextState);
transition.put(s, nextActionState);
put(nextState, new HashMap<Symbol, ActionState>());
if(nextDepth == depthMap.size()){
depthStates = new HashSet<State>();
depthMap.add(depthStates);
}
else{
depthStates = depthMap.get(nextDepth);
}
depthStates.add(nextState);
}
else{
nextState = nextActionState.getState();
}
if(patternRemaining == 0){
nextState.setMatch(r);
}
currentState = nextState;
--patternRemaining;
}
}
//now add self transitions on s0 for any symbols that don't
//exit from s0 already
HashMap<Symbol, ActionState> s0transition = get(s0);
for(Symbol s : terminals){
if(!s0transition.containsKey(s)){
s0transition.put(s, new ActionState(0, s0));
}
}
}
private void addFailureTransitions(Set<Symbol> terminals){
fail = new HashMap<State, State>();
if(depthMap.size() == 1) return;
//handle all depth 1
for(State state : depthMap.get(1)){
HashMap<Symbol, ActionState> transition = get(state);
fail.put(state, s0);
for(Symbol symbol : terminals){
if(!transition.containsKey(symbol)){
transition.put(symbol, new ActionState(1, s0));
}
}
}
if(depthMap.size() == 2) return;
//handle depth d > 1
for(int i = 2; i < depthMap.size(); ++i){
for(State state : depthMap.get(i)){
HashMap<Symbol, ActionState> transition = get(state);
for(Symbol symbol : terminals){
if(!transition.containsKey(symbol)){
State failState = findState(state, depthMap.get(i - 1), fail,
terminals);
transition.put(symbol,
new ActionState(state.getDepth() - failState.getDepth(),
failState));
fail.put(state, failState);
}
}
}
}
//System.out.println("!!!!!!!!!!");
//System.out.println(fail);
//System.out.println("!!!!!!!!!!");
}
private State findState(State state, Set<State> shallowerStates,
HashMap<State, State> fail, Set<Symbol> terminals){
for(State shallowerState : shallowerStates){
HashMap<Symbol, ActionState> transition = get(shallowerState);
for(Symbol symbol : terminals){
ActionState destination = transition.get(symbol);
if(destination.getState() == state){
// System.out.println(state + " " + destination.getState());
State failState = fail.get(shallowerState);
while(failState != s0 && get(failState).get(symbol).getAction() != 0){
failState = fail.get(failState);
}
return get(failState).get(symbol).getState();
}
}
}
return s0;
}
public void rewrite(SinglyLinkedList<Symbol> l){
System.out.println("rewriting:");
System.out.println(" " + l + "\n=========================================");
if(l.size() == 0) return;
Iterator<Symbol> first = l.iterator();
first.next(); //make sure first points to an element
Iterator<Symbol> second = l.iterator();
Iterator<Symbol> lastRepl;
State currentState = s0;
ActionState as;
Symbol symbol = second.next();
while(true){
as = get(currentState).get(symbol);
System.out.println("*" + symbol + "
//adjust the first pointer
if(currentState == s0 && as.getState() == s0){
System.out.println("false 0 transition");
if(!first.hasNext()) break;
first.next();
}
else {
for(int i = 0; i < as.getAction(); ++i){
first.next();
}
}
if(as.getState().getMatch() != null){
AbstractSequence repl = as.getState().getMatch().getRhs();
if(repl instanceof Fail){
System.out.println("Fail!");
return;
}
if(repl instanceof Succeed){
System.out.println("Succeed!");
return;
}
if(repl instanceof Sequence){
System.out.println("==========Replacing==============" + first);
System.out.println("==========Replacing==============" + second);
System.out.println("in: " + l);
l.nonDestructiveReplace(first, second, (Sequence) repl);
if(l.isEmpty()) break;
first = l.iterator();
System.out.println("out: " + l);
System.out.println("out: " + first);
//lastRepl = l.iterator(second);
//System.out.println("lastRepl: " + lastRepl);
symbol = first.next();
second = l.iterator(first);
//System.out.println("first: " + first);
//System.out.println("second: " + second);
currentState = s0;
continue;
}
}
if(!second.hasNext()) break;
currentState = as.getState();
//normal transition
if(as.getAction() == 0){
symbol = second.next();
}
//fail transition, need to reconsider he same symbol in next state
}
System.out.println("substituted form = " + l.toString());
}
public void rewrite(SpliceList<Symbol> l){
System.out.println("rewriting:");
System.out.println(" " + l + "\n=========================================");
if(l.isEmpty()) return;
SLIterator<Symbol> first;
SLIterator<Symbol> second;
SLIterator<Symbol> lastRepl = null;
State currentState;
ActionState as;
Symbol symbol;
boolean changed;
boolean atOrPastLastChange;
DONE:
do {
currentState = s0;
atOrPastLastChange = false;
changed = false;
first = l.head();
second = l.head();
symbol = second.get();
System.out.println("******************outer*****");
while(true){
as = get(currentState).get(symbol);
System.out.println("*" + symbol + "
//adjust the first pointer
if(currentState == s0 && as.getState() == s0){
System.out.println("false 0 transition");
if(!first.next()) break;
}
else {
for(int i = 0; i < as.getAction(); ++i){
first.next();
}
}
if(as.getState().getMatch() != null){
AbstractSequence repl = as.getState().getMatch().getRhs();
if(repl instanceof Fail){
System.out.println("Fail!");
return;
}
if(repl instanceof Succeed){
System.out.println("Succeed!");
return;
}
if(repl instanceof Sequence){
changed = true;
atOrPastLastChange = false;
System.out.println("==========Replacing==============" + first);
System.out.println("==========Replacing==============" + second);
System.out.println("in: " + l);
first.nonDestructiveSplice(second, (Sequence) repl);
if(l.isEmpty()) break DONE;
System.out.println("out: " + l);
System.out.println("out: " + first);
lastRepl = second;
System.out.println("lastRepl: " + lastRepl);
second = first.copy();
System.out.println("first: " + first);
System.out.println("second: " + second);
currentState = s0;
symbol = second.get();
if(symbol == null) break;
continue;
}
}
currentState = as.getState();
//normal transition
if(as.getAction() == 0){
if(!second.next()) break;
System.out.println("*********first " + second);
System.out.println("*********second " + second);
System.out.println("*********lastRepl " + lastRepl);
if(!changed){
if(second.equals(lastRepl)){
atOrPastLastChange = true;
}
if(atOrPastLastChange && currentState == s0){
System.out.println("early exit at symbol " + second);
break DONE;
}
}
symbol = second.get();
}
//fail transition, need to reconsider he same symbol in next state
}
} while(changed);
System.out.println("substituted form = " + l.toString());
}
@Override public String toString(){
StringBuilder sb = new StringBuilder();
for(State state : keySet()){
sb.append(state);
sb.append("\n[");
HashMap<Symbol, ActionState> transition = get(state);
for(Symbol symbol : transition.keySet()){
sb.append(" ");
sb.append(symbol);
sb.append(" -> ");
sb.append(transition.get(symbol));
sb.append("\n");
}
sb.append("]\n");
}
return sb.toString();
}
public String toDotString(){
StringBuilder sb = new StringBuilder("digraph A");
sb.append((long) (Math.random()* 2e61d));
sb.append("{\n rankdir=LR;\n node [shape=circle];\n");
// sb.append(" edge [style=\">=stealth' ,shorten >=1pt\"];\n");
for(State state : keySet()){
sb.append(" ");
sb.append(state.toFullDotString());
sb.append("\n");
}
for(State state : keySet()){
HashMap<Symbol, ActionState> transition = get(state);
sb.append(transitionToDotString(state, transition));
}
sb.append("}");
return sb.toString();
}
public StringBuilder transitionToDotString(State state, Map<Symbol, ActionState> transition){
Map<ActionState, ArrayList<Symbol>> edgeCondensingMap = new
LinkedHashMap<ActionState, ArrayList<Symbol>>();
for(Symbol symbol : transition.keySet()){
ActionState next = transition.get(symbol);
ArrayList<Symbol> edges = edgeCondensingMap.get(next);
if(edges == null){
edges = new ArrayList<Symbol>();
edgeCondensingMap.put(next, edges);
}
edges.add(symbol);
}
// System.out.println(edgeCondensingMap);
// if(true) throw new RuntimeException();
StringBuilder sb = new StringBuilder();
for(ActionState next : edgeCondensingMap.keySet()){
sb.append(" ");
sb.append(state.toNameDotString());
sb.append(" -> ");
sb.append(next.getState().toNameDotString());
sb.append(" [label=\"");
StringBuilder label = new StringBuilder();
for(Symbol symbol : edgeCondensingMap.get(next)){
label.append(symbol.toString());
label.append(", ");
}
label.setCharAt(label.length() - 1, '/');
label.setCharAt(label.length() - 2, ' ');
label.append(" ");
label.append(next.getAction());
sb.append(label);
sb.append("\"];\n");
}
return sb;
// for(Symbol symbol : transition.keySet()){
// sb.append(" ");
// sb.append(state.toNameDotString());
// sb.append(" -> ");
// ActionState next = transition.get(symbol);
// sb.append(next.getState().toNameDotString());
// sb.append(" [texlbl=\"$");
// sb.append(symbol.toDotString());
// sb.append(" / ");
// sb.append(next.getAction());
// sb.append("$\"];\n");
}
}
class ActionState {
private int action;
private State state;
public int getAction(){
return action;
}
public State getState(){
return state;
}
public ActionState(int action, State state){
this.action = action;
this.state = state;
}
@Override public String toString(){
return "[" + action + "] " + state.toString();
}
@Override
public int hashCode(){
return action ^ state.hashCode();
}
@Override
public boolean equals(Object o){
if(this == o) return true;
if(!(o instanceof ActionState)) return false;
ActionState as = (ActionState) o;
return(as.action == action && state.equals(as.state));
}
}
class State {
private static int counter = 0;
private int number;
private int depth;
private Rule matchedRule = null;
public State(int depth){
number = counter++;
this.depth = depth;
}
public int getNumber(){
return number;
}
public int getDepth(){
return depth;
}
public Rule getMatch(){
return matchedRule;
}
public void setMatch(Rule r){
matchedRule = r;
}
//matched rule must always be equal if number is equal
//ditto with depth
@Override
public int hashCode(){
return number;
}
@Override
public boolean equals(Object o){
if(this == o) return true;
if(!(o instanceof State)) return false;
State s = (State) o;
return s.number == number;
}
@Override
public String toString(){
return "<" + number
+ " @ "
+ depth
+ ((matchedRule == null)?
""
: " matches " + matchedRule.toString()
)
+ ">";
}
public String toFullDotString(){
String name = toNameDotString();
String texlbl= number
+ ((matchedRule == null)?
""
: "(" + matchedRule.toDotString() + ")"
);
return name + " [texlbl=\"$" + texlbl + "$\" label=\"" + mkSpaces(Math.max(texlbl.length() - 14, 6)) + "\"];";
}
static String mkSpaces(int len){
StringBuilder sb = new StringBuilder();
for(; len > 0; --len){
sb.append(' ');
}
return sb.toString();
}
public String toNameDotString(){
return "s_" + number;
}
}
|
package com.jpetrak.miscfastcompact.graph;
import com.jpetrak.miscfastcompact.store.StoreOfInts;
import it.unimi.dsi.fastutil.ints.IntArrayList;
import it.unimi.dsi.fastutil.objects.Object2IntAVLTreeMap;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
/**
* Simple Graph store. Just a first attempt to create a graph store, WIP...
* @author Johann Petrak
*/
public class GraphStore implements Serializable {
// The store consists of the following parts:
// = a map from URI-String to Uri-id (an int, sequential 0...(n-1)
// = an array that maps URI id to the out edge chunk index or -1 if no edge exists (yet)
// = an array that maps URI id to the in edge chunk index or -1 if no edge exists (yet)
// = out-edge store and in-edge store: two separate stores where we store,
// at position chunk-index, a variable block of edge-data. Edge data
// is a table with two integers per row: first the id or count of the edg
// second the id of the to/from node
private StoreOfInts outEdges;
private StoreOfInts inEdges;
private Object2IntAVLTreeMap<String> uri2idMap;
//private HashMap<String,Integer> uri2idMap;
private IntArrayList id2OutEdgeChunk;
private IntArrayList id2InEdgeChunk;
private int nextId = 0;
public GraphStore() {
uri2idMap = new Object2IntAVLTreeMap<String>();
//uri2idMap = new HashMap<String,Integer>();
outEdges = new StoreOfInts();
inEdges = new StoreOfInts();
id2OutEdgeChunk = new IntArrayList();
id2InEdgeChunk = new IntArrayList();
}
/**
* Add a node to the node list and return the id (unless it already exists,
* then just return the id).
* @param uri
* @return
*/
public int addNode(String uri) {
if(uri2idMap.containsKey(uri)) {
return uri2idMap.get(uri);
} else {
int usedId = nextId;
uri2idMap.put(uri, nextId);
id2InEdgeChunk.add(-1);
id2OutEdgeChunk.add(-1);
nextId++;
return usedId;
}
}
// return the id or -1 if not found
public int getNodeId(String uri) {
if(uri2idMap.containsKey(uri)) {
return uri2idMap.get(uri);
} else {
return -1;
}
}
// TO LOAD A GRAPH:
// First, add all the known nodes: addNode(uri) for all different uris
// Then for each node that has outgoing edges, add all the outgoing edges
// at once: addOutEdges(nodeId, listOfEdgeData, listOfNodeIds)
// Then for each node that has incoming edges, add all the incoming edges
// at once: addInEdges(nodeId, listOfEdgeData, listOfNodeIds)
// This could be achieved by reading in three files: one with just the
// URIs, one sorted by first uri, one sorted by second uri, and the
// loading program gathers all the information for blocks of identical
// first or second uris
/**
* Add all the incoming edges for a node. This assumes that all the nodes
* have already been added! For each node, this must only be called once!
* Also, the list MUST already be sorted by increasing Edge.nodeId!
* Node that all edge data must be != Integer.MIN_VALUE, but this is not
* checked!
* @param nodeId
* @param edgeData
* @param nodeIds
*/
public void addSortedInEdges(int nodeId, List<Edge> edges) {
int[] chunk = edgesList2Chunk(edges);
int chunkIndex = inEdges.addData(chunk);
id2InEdgeChunk.set(nodeId, chunkIndex);
}
public void addInEdges(int nodeId, List<Edge> edges) {
Collections.sort(edges);
addSortedInEdges(nodeId,edges);
}
public void addSortedOutEdges(int nodeId, List<Edge> edges) {
int[] chunk = edgesList2Chunk(edges);
int chunkIndex = outEdges.addData(chunk);
id2OutEdgeChunk.set(nodeId, chunkIndex);
}
public void addOutEdges(int nodeId, List<Edge> edges) {
Collections.sort(edges);
addSortedOutEdges(nodeId,edges);
}
private int[] edgesList2Chunk(List<Edge> edges) {
int size = edges.size();
int[] chunk = new int[size*2];
for(int i=0; i<size; i++) {
chunk[2*i] = edges.get(i).nodeId;
chunk[2*i+1] = edges.get(i).edgeData;
}
return chunk;
}
// find the edge data of the first or only edge between two nodes or Integer.MIN_VALUE if
// no edge was found
public int getFirstEdgeData(int nodeId1, int nodeId2) {
// first check the sizes of the two edge chunks and pick the
// smaller one for finding the edge!
int chunkIndex1 = id2OutEdgeChunk.get(nodeId1);
if(chunkIndex1<0) { return Integer.MIN_VALUE; }
int chunkIndex2 = id2InEdgeChunk.get(nodeId2);
if(chunkIndex2<0) { return Integer.MIN_VALUE; }
int size1 = outEdges.getSize(chunkIndex1);
int size2 = inEdges.getSize(chunkIndex2);
//System.out.println("Node1="+nodeId1+", node2="+nodeId2+", size1="+size1+", size2="+size2);
int ret = Integer.MIN_VALUE;
int chunk[];
int index;
if(size1 < size2) {
// find in the outgoing edges
chunk = outEdges.getData(chunkIndex1);
index = binarySearchInEntries(chunk, nodeId2, 0);
} else {
// find in the incoming edges
chunk = inEdges.getData(chunkIndex2);
index = binarySearchInEntries(chunk, nodeId1, 0);
}
if(index >= 0) {
ret = chunk[index+1]; // we found the index of the nodeId, the data is behind that
}
return ret;
}
public int getSumEdgeDataSharedParent(int nodeId1, int nodeId2) {
// = check which edge list is smaller, use that one
// = for each edge in the smaller list, try to find the edge data
// in the other list. The search routine returns the index if found
// or the smallest index for a node id larger than the wanted (negated)
// if not found. We use that index as the starting point for the search
// in the next iteration.
int chunkIndex1 = id2InEdgeChunk.get(nodeId1);
if(chunkIndex1<0) {
//System.out.println("DEBUG: no in edges: "+nodeId1);
return 0;
}
int chunkIndex2 = id2InEdgeChunk.get(nodeId2);
if(chunkIndex2<0) {
//System.out.println("DEBUG: no in edges: "+nodeId1);
return 0;
}
int size1 = inEdges.getSize(chunkIndex1);
int size2 = inEdges.getSize(chunkIndex2);
int sumData = 0;
int[] chunk1, chunk2;
int index, startIndex, sizeToSearch;
if(size1 < size2) {
chunk1 = inEdges.getData(chunkIndex1);
chunk2 = inEdges.getData(chunkIndex2);
sizeToSearch = size2;
} else {
chunk1 = inEdges.getData(chunkIndex2);
chunk2 = inEdges.getData(chunkIndex1);
sizeToSearch = size1;
}
startIndex = 0;
//System.out.println("DEBUG: size1="+size1+", size2="+size2);
// go through the edges in chunk1 and get the other node, then
// try to find the other node in the other chunk and adjust the
// starting search position for the next iteration.
//System.out.println("DEBUG: dump of chunk1 edges:");
//debugDumpEdges(chunk1);
//System.out.println("DEBUG: dump of chunk2 edges:");
//debugDumpEdges(chunk2);
for(int i=0; i<chunk1.length/2; i++) {
int otherNodeId = chunk1[2*i];
index = binarySearchInEntries(chunk2, otherNodeId, startIndex);
//System.out.println("DEBUG: checked otherNode="+otherNodeId+" with start="+startIndex+", index="+index);
// if we found something, we should add the edgeData of both edges to the sum
// in any case, set the startIndex to point to the node which is greater
// than the one we just found (because we go through our own nodes in
// increasing order)
if(index >= 0) { // found it
//System.out.println("DEBUG: found at index="+index+", this count="+chunk1[2*i+1]+" other="+chunk2[index+1]);
sumData += chunk1[2*i+1] + chunk2[index+1];
startIndex = index+2;
} else { // did not find the other Node
startIndex = (-index)-2;
if(startIndex > sizeToSearch) {
break;
}
}
}
return sumData;
}
public int getSumEdgeDataSharedChild(int nodeId1, int nodeId2) {
// = check which edge list is smaller, use that one
// = for each edge in the smaller list, try to find the edge data
// in the other list. The search routine returns the index if found
// or the smallest index for a node id larger than the wanted (negated)
// if not found. We use that index as the starting point for the search
// in the next iteration.
int chunkIndex1 = id2OutEdgeChunk.get(nodeId1);
if(chunkIndex1<0) { return 0; }
int chunkIndex2 = id2OutEdgeChunk.get(nodeId2);
if(chunkIndex2<0) { return 0; }
int size1 = outEdges.getSize(chunkIndex1);
int size2 = outEdges.getSize(chunkIndex2);
int sumData = 0;
int[] chunk1, chunk2;
int index, startIndex;
if(size1 < size2) {
chunk1 = outEdges.getData(chunkIndex1);
chunk2 = outEdges.getData(chunkIndex2);
} else {
chunk1 = outEdges.getData(chunkIndex2);
chunk2 = outEdges.getData(chunkIndex1);
}
startIndex = 0;
// go through the edges in chunk1 and get the other node, then
// try to find the other node in the other chunk and adjust the
// starting search position for the next iteration.
for(int i=0; i<chunk1.length/2; i++) {
int otherNodeId = chunk1[2*i];
index = binarySearchInEntries(chunk2, otherNodeId, startIndex);
// if we found something, we should add the edgeData of both edges to the sum
// in any case, set the startIndex to point to the node which is greater
// than the one we just found (because we go through our own nodes in
// increasing order)
if(index >= 0) { // found it
sumData += chunk1[2*i+1] + chunk2[index+1];
startIndex = index+2;
} else { // did not find the other Node
startIndex = (-index)-2;
}
}
return sumData;
}
public int getSumEdgeDataSequence(int nodeId1, int nodeId2) {
// = check which edge list is smaller, use that one
// = for each edge in the smaller list, try to find the edge data
// in the other list. The search routine returns the index if found
// or the smallest index for a node id larger than the wanted (negated)
// if not found. We use that index as the starting point for the search
// in the next iteration.
int chunkIndex1 = id2OutEdgeChunk.get(nodeId1);
if(chunkIndex1<0) { return 0; }
int chunkIndex2 = id2InEdgeChunk.get(nodeId2);
if(chunkIndex2<0) { return 0; }
int size1 = outEdges.getSize(chunkIndex1);
int size2 = inEdges.getSize(chunkIndex2);
int sumData = 0;
int[] chunk1, chunk2;
int index, startIndex;
if(size1 < size2) {
chunk1 = outEdges.getData(chunkIndex1);
chunk2 = inEdges.getData(chunkIndex2);
} else {
chunk1 = inEdges.getData(chunkIndex2);
chunk2 = outEdges.getData(chunkIndex1);
}
startIndex = 0;
// go through the edges in chunk1 and get the other node, then
// try to find the other node in the other chunk and adjust the
// starting search position for the next iteration.
for(int i=0; i<chunk1.length/2; i++) {
int otherNodeId = chunk1[2*i];
index = binarySearchInEntries(chunk2, otherNodeId, startIndex);
// if we found something, we should add the edgeData of both edges to the sum
// in any case, set the startIndex to point to the node which is greater
// than the one we just found (because we go through our own nodes in
// increasing order)
if(index >= 0) { // found it
sumData += chunk1[2*i+1] + chunk2[index+1];
startIndex = index+2;
} else { // did not find the other Node
startIndex = (-index)-2;
}
}
return sumData;
}
/**
* Given an otherNode id and a chunk of edges, find the index of the first
* edge that matches the node id or return -1 if not found.
* @param nodeId
* @param chunk
* @return
*/
public int findFirstNodeIndex(int nodeId, int[] chunk) {
// we use our own version of binary sort to find the node
return binarySearchInEntries(chunk, nodeId, 0);
}
// A modification of binary search that only looks at the indices
// 0, 2, 4, .... in the array
// This searches the entries array to find the key in one of these positions
// and returns the index (>= 0) if found or the insertion point as a negative int
// if not found.
// NOTE: start must be an even number, i.e. start always must be the index
// if a nodeId!!
protected int linearSearchInEntries(int[] entries, int find, int start) {
for(int i=start/2;i<entries.length/2;i++) {
if(entries[2*i]>find) {
return -(2*i)-2;
} else if(entries[2*i]==find) {
return 2*i;
}
}
return -entries.length-4;
}
protected int binarySearchInEntries(int[] entries, int find, int start) {
if(start > (entries.length-2)) {
return -start;
}
int nrentries = (entries.length) / 2 - start/2;
int low = start/2;
int high = low+(nrentries - 1);
while (low <= high) {
int mid = (low + high)/2;
int midVal = entries[mid*2];
if (midVal < find)
low = mid + 1;
else if (midVal > find)
high = mid - 1;
else
return (mid*2); // key found
}
return 2*(-low)-2; // key not found.
}
public void debugDumpEdges(int[] chunk) {
for(int i=0;i<chunk.length/2;i++) {
System.out.println("Edge nodeId="+chunk[2*i]+" edgedata="+chunk[2*i+1]);
}
}
public void debugDumpOutEdges(String node) {
int nodeId = getNodeId(node);
int chunkIndex = id2OutEdgeChunk.getInt(nodeId);
if(chunkIndex < 0) {
System.out.println("No out Edges for "+node);
} else {
int[] chunk = outEdges.getData(chunkIndex);
debugDumpEdges(chunk);
}
}
public void debugDumpInEdges(String node) {
int nodeId = getNodeId(node);
int chunkIndex = id2InEdgeChunk.getInt(nodeId);
if(chunkIndex < 0) {
System.out.println("No in edges for "+node);
} else {
int[] chunk = inEdges.getData(chunkIndex);
debugDumpEdges(chunk);
}
}
// for debugging mainly
public void debugPrintEdges(String uri) {
int id = getNodeId(uri);
if(id == -1) {
System.out.println("Node not known: "+uri);
} else {
System.out.println("Finding edges for node "+id);
}
// get the chunk for the in edges for uri
int inChunk = id2InEdgeChunk.get(id);
if(inChunk == -1) {
System.out.println("No in edges for "+uri);
} else {
System.out.println("Chunk index for in edges "+inChunk);
int[] chunk = inEdges.getData(inChunk);
int size = chunk.length/2;
System.out.println("Got in edges "+size);
for(int i=0; i<size; i++) {
int relData = chunk[2*i+1];
int nodeId = chunk[2*i];
System.out.println("In Edge "+i+": nodeid="+nodeId+", data="+relData);
}
}
int outChunk = id2OutEdgeChunk.get(id);
if(outChunk == -1) {
System.out.println("No out edges for "+uri);
} else {
System.out.println("Chunk index for out edges "+outChunk);
int[] chunk = outEdges.getData(outChunk);
int size = chunk.length/2;
System.out.println("Got out edges "+size);
for(int i=0; i<size; i++) {
int relData = chunk[2*i+1];
int nodeId = chunk[2*i];
System.out.println("Out Edge "+i+": nodeid="+nodeId+", data="+relData);
}
}
}
public int debugGetInEdgesSize() {
return inEdges.size();
}
public int debugGetOutEdgesSize() {
return outEdges.size();
}
public int debugGetInId2ChunkSize() {
return id2InEdgeChunk.size();
}
public int debugGetOutId2ChunkSize() {
return id2OutEdgeChunk.size();
}
public static void main(String[] args) {
System.out.println("Running main ...");
GraphStore gstore = new GraphStore();
NodeNameStore nstore = new NodeNameStore();
gstore.addNode("uri1");
nstore.addNode("uri1");
gstore.addNode("uri2");
nstore.addNode("uri2");
gstore.addNode("uri3");
nstore.addNode("uri3");
gstore.addNode("uri4");
nstore.addNode("uri4");
gstore.addNode("uri5");
nstore.addNode("uri5");
gstore.addNode("uri6");
nstore.addNode("uri6");
ArrayList<Edge> edges = new ArrayList<Edge>();
edges.add(new Edge(22,gstore.getNodeId("uri2")));
edges.add(new Edge(23,gstore.getNodeId("uri3")));
gstore.addOutEdges(gstore.getNodeId("uri1"), edges);
edges = new ArrayList<Edge>();
edges.add(new Edge(24,gstore.getNodeId("uri3")));
edges.add(new Edge(23,gstore.getNodeId("uri4")));
gstore.addOutEdges(gstore.getNodeId("uri2"), edges);
edges = new ArrayList<Edge>();
edges.add(new Edge(22,gstore.getNodeId("uri1")));
gstore.addInEdges(gstore.getNodeId("uri2"), edges);
edges = new ArrayList<Edge>();
edges.add(new Edge(23,gstore.getNodeId("uri1")));
edges.add(new Edge(24,gstore.getNodeId("uri2")));
gstore.addInEdges(gstore.getNodeId("uri3"), edges);
edges = new ArrayList<Edge>();
edges.add(new Edge(23,gstore.getNodeId("uri2")));
gstore.addInEdges(gstore.getNodeId("uri4"), edges);
gstore.debugPrintEdges("uri1");
gstore.debugPrintEdges("uri2");
gstore.debugPrintEdges("uri3");
gstore.debugPrintEdges("uri4");
System.out.println("InEdgesSize="+gstore.debugGetInEdgesSize());
System.out.println("OutEdgesSize="+gstore.debugGetOutEdgesSize());
System.out.println("Name for id 1: "+nstore.getNodeName(1));
System.out.println("Name for id 2: "+nstore.getNodeName(2));
System.out.println("Edge between uri1 and uri2: "+gstore.getFirstEdgeData(gstore.getNodeId("uri1"), gstore.getNodeId("uri2")));
System.out.println("Edge between uri1 and uri3: "+gstore.getFirstEdgeData(gstore.getNodeId("uri1"), gstore.getNodeId("uri3")));
System.out.println("Edge between uri1 and uri4: "+gstore.getFirstEdgeData(gstore.getNodeId("uri1"), gstore.getNodeId("uri4")));
System.out.println("Parent sum uri3, uri2: "+gstore.getSumEdgeDataSharedParent(gstore.getNodeId("uri3"), gstore.getNodeId("uri2")));
System.out.println("Finishing main ....");
}
}
|
package gov.nih.nci.calab.ui.particle;
/**
* This class sets up input form for size characterization.
*
* @author pansu
*/
/* CVS $Id: NanoparticleFunctionAction.java,v 1.12 2007-12-20 16:25:53 pansu Exp $ */
import gov.nih.nci.calab.dto.common.UserBean;
import gov.nih.nci.calab.dto.function.AgentBean;
import gov.nih.nci.calab.dto.function.AgentTargetBean;
import gov.nih.nci.calab.dto.function.FunctionBean;
import gov.nih.nci.calab.dto.function.LinkageBean;
import gov.nih.nci.calab.dto.particle.ParticleBean;
import gov.nih.nci.calab.exception.CaNanoLabSecurityException;
import gov.nih.nci.calab.exception.ParticleFunctionException;
import gov.nih.nci.calab.service.particle.NanoparticleFunctionService;
import gov.nih.nci.calab.service.particle.NanoparticleService;
import gov.nih.nci.calab.service.util.CaNanoLabConstants;
import gov.nih.nci.calab.service.util.StringUtils;
import gov.nih.nci.calab.ui.core.AbstractDispatchAction;
import gov.nih.nci.calab.ui.core.InitSessionSetup;
import gov.nih.nci.calab.ui.security.InitSecuritySetup;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.validator.DynaValidatorForm;
public class NanoparticleFunctionAction extends AbstractDispatchAction {
/**
* Add or update the data to database
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward create(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward forward = null;
DynaValidatorForm theForm = (DynaValidatorForm) form;
ParticleBean particle = (ParticleBean) theForm.get("particle");
FunctionBean function = (FunctionBean) theForm.get("function");
String functionId = request.getParameter("functionId");
if (functionId != null && functionId.length() > 0) {
function.setId((String) theForm.get("functionId"));
}
// validate agent target
for (LinkageBean linkageBean : function.getLinkages()) {
for (AgentTargetBean agentTargetBean : linkageBean.getAgent()
.getAgentTargets()) {
if (agentTargetBean.getType().length() == 0) {
throw new ParticleFunctionException(
"Agent target type can not be empty");
}
}
}
NanoparticleFunctionService service = new NanoparticleFunctionService();
service.addParticleFunction(particle.getSampleId(), function);
ActionMessages msgs = new ActionMessages();
ActionMessage msg = new ActionMessage("message.addFunction");
msgs.add("message", msg);
saveMessages(request, msgs);
forward = mapping.findForward("success");
request.getSession().setAttribute("newFunctionCreated", true);
InitParticleSetup.getInstance().setSideParticleMenu(request,
particle.getSampleId());
request.setAttribute("theParticle", particle);
return forward;
}
/**
* Set up the input forms for adding data
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setup(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
HttpSession session = request.getSession();
// clear session data from the input forms
clearMap(session, theForm, mapping);
initSetup(request, theForm);
return mapping.getInputForward();
}
private void clearMap(HttpSession session, DynaValidatorForm theForm,
ActionMapping mapping) throws Exception {
// clear session data from the input forms
theForm.set("particle", new ParticleBean());
theForm.set("function", new FunctionBean());
}
private void initSetup(HttpServletRequest request, DynaValidatorForm theForm)
throws Exception {
HttpSession session = request.getSession();
String particleId = request.getParameter("particleId");
UserBean user = (UserBean) request.getSession().getAttribute("user");
NanoparticleService searchNanoparticleService = new NanoparticleService();
ParticleBean particle = searchNanoparticleService.getParticleInfo(
particleId, user);
String submitType = request.getParameter("submitType");
String functionId = request.getParameter("functionId");
FunctionBean functionBean = null;
if (functionId != null) {
NanoparticleFunctionService service = new NanoparticleFunctionService();
functionBean = service.getFunctionBy(functionId);
theForm.set("function", functionBean);
} else {
functionBean = (FunctionBean) theForm.get("function");
}
functionBean.setDisplayType(StringUtils
.getOneWordLowerCaseFirstLetter(submitType));
theForm.set("particle", particle);
InitParticleSetup.getInstance().setSideParticleMenu(request,
particle.getSampleId());
InitSessionSetup.getInstance().setStaticDropdowns(session);
InitParticleSetup.getInstance().setAllFunctionDropdowns(session);
}
/**
* Set up the form for updating existing characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupUpdate(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
initSetup(request, theForm);
return mapping.findForward("setup");
}
/**
* Prepare the form for viewing existing characterization
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward setupView(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
return setupUpdate(mapping, form, request, response);
}
public ActionForward addLinkage(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
FunctionBean function = (FunctionBean) theForm.get("function");
List<LinkageBean> origLinkages = function.getLinkages();
int origNum = (origLinkages == null) ? 0 : origLinkages.size();
List<LinkageBean> linkages = new ArrayList<LinkageBean>();
for (int i = 0; i < origNum; i++) {
linkages.add(origLinkages.get(i));
}
// add a new one
linkages.add(new LinkageBean());
function.setLinkages(linkages);
ParticleBean particle = (ParticleBean) theForm.get("particle");
InitParticleSetup.getInstance().setSideParticleMenu(request,
particle.getSampleId());
return input(mapping, form, request, response);
}
public ActionForward removeLinkage(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String linkageIndex = request.getParameter("compInd");
int ind = Integer.parseInt(linkageIndex);
DynaValidatorForm theForm = (DynaValidatorForm) form;
FunctionBean function = (FunctionBean) theForm.get("function");
List<LinkageBean> origLinkages = function.getLinkages();
int origNum = (origLinkages == null) ? 0 : origLinkages.size();
List<LinkageBean> linkages = new ArrayList<LinkageBean>();
for (int i = 0; i < origNum; i++) {
linkages.add(origLinkages.get(i));
}
// remove the one at the index
if (origNum > 0) {
linkages.remove(ind);
}
function.setLinkages(linkages);
ParticleBean particle = (ParticleBean) theForm.get("particle");
InitParticleSetup.getInstance().setSideParticleMenu(request,
particle.getSampleId());
return input(mapping, form, request, response);
}
public ActionForward addTarget(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
String linkageIndex = request.getParameter("compInd");
int ind = Integer.parseInt(linkageIndex);
DynaValidatorForm theForm = (DynaValidatorForm) form;
FunctionBean function = (FunctionBean) theForm.get("function");
AgentBean agent = function.getLinkages().get(ind).getAgent();
List<AgentTargetBean> origTargets = agent.getAgentTargets();
int origNum = (origTargets == null) ? 0 : origTargets.size();
List<AgentTargetBean> targets = new ArrayList<AgentTargetBean>();
for (int i = 0; i < origNum; i++) {
targets.add(origTargets.get(i));
}
// add a new one
targets.add(new AgentTargetBean());
agent.setAgentTargets(targets);
ParticleBean particle = (ParticleBean) theForm.get("particle");
InitParticleSetup.getInstance().setSideParticleMenu(request,
particle.getSampleId());
return input(mapping, form, request, response);
}
public ActionForward removeTarget(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
String linkageIndex = request.getParameter("compInd");
int ind = Integer.parseInt(linkageIndex);
String targetIndex = request.getParameter("childCompInd");
int tInd = Integer.parseInt(targetIndex);
FunctionBean function = (FunctionBean) theForm.get("function");
AgentBean agent = function.getLinkages().get(ind).getAgent();
List<AgentTargetBean> origTargets = agent.getAgentTargets();
int origNum = (origTargets == null) ? 0 : origTargets.size();
List<AgentTargetBean> targets = new ArrayList<AgentTargetBean>();
for (int i = 0; i < origNum; i++) {
targets.add(origTargets.get(i));
}
// remove the one at the index
if (origNum > 0) {
targets.remove(tInd);
}
agent.setAgentTargets(targets);
ParticleBean particle = (ParticleBean) theForm.get("particle");
InitParticleSetup.getInstance().setSideParticleMenu(request,
particle.getSampleId());
return input(mapping, form, request, response);
}
public ActionForward input(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
DynaValidatorForm theForm = (DynaValidatorForm) form;
// update editable dropdowns
FunctionBean function = (FunctionBean) theForm.get("function");
HttpSession session = request.getSession();
updateEditables(session, function);
return mapping.findForward("setup");
}
private void updateEditables(HttpSession session, FunctionBean function)
throws Exception {
// update bondType editable dropdowns
for (LinkageBean linkage : function.getLinkages()) {
if (linkage.getType() != null
&& linkage.getType().equals(CaNanoLabConstants.ATTACHMENT)) {
InitSessionSetup.getInstance().updateEditableDropdown(session,
linkage.getBondType(), "allBondTypes");
}
if (linkage.getAgent() != null
&& linkage.getAgent().getType() != null
&& linkage.getAgent().getType().equals(
CaNanoLabConstants.IMAGE_CONTRAST_AGENT)) {
InitSessionSetup.getInstance().updateEditableDropdown(session,
linkage.getAgent().getImageContrastAgent().getType(),
"allImageContrastAgentTypes");
}
}
}
public boolean loginRequired() {
return true;
}
public boolean canUserExecute(UserBean user)
throws CaNanoLabSecurityException {
return InitSecuritySetup.getInstance().userHasCreatePrivilege(user,
CaNanoLabConstants.CSM_PG_PARTICLE);
}
}
|
package ameba.security.shiro.cache;
import com.google.common.collect.Maps;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
/**
* @author icode
*/
public class DefaultCache<K, V> implements Cache<K, V> {
private static final String CACHE_PRE_KEY = DefaultCache.class.getName() + ".";
private String cacheName;
private Map<K, V> caches;
public DefaultCache(String name) {
cacheName = CACHE_PRE_KEY + name;
caches = ameba.cache.Cache.get(cacheName);
if (caches == null) {
caches = Maps.newLinkedHashMap();
}
}
@Override
public V get(K key) throws CacheException {
return caches.get(key);
}
@Override
public V put(K key, V value) throws CacheException {
try {
return caches.put(key, value);
} finally {
flush();
}
}
@Override
public V remove(K key) throws CacheException {
try {
return caches.remove(key);
} finally {
flush();
}
}
protected void flush() {
ameba.cache.Cache.syncSet(cacheName, caches);
}
@Override
public void clear() throws CacheException {
caches.clear();
ameba.cache.Cache.delete(cacheName);
}
@Override
public int size() {
return caches.size();
}
@Override
public Set<K> keys() {
return caches.keySet();
}
@Override
public Collection<V> values() {
return caches.values();
}
}
|
package application.controllers;
import application.fxobjects.cell.Cell;
import application.fxobjects.cell.layout.GraphLayout;
import core.graph.Graph;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import javafx.embed.swing.SwingFXUtils;
import javafx.geometry.Rectangle2D;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javafx.scene.input.ScrollEvent;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Screen;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
@SuppressWarnings("PMD.UnusedPrivateField")
public class GraphController extends Controller<ScrollPane> {
private Graph graph;
private ZoomController zoomController;
private GraphMouseHandling graphMouseHandling;
private Rectangle2D screenSize;
private int maxWidth;
private int maxHeight;
private String position;
/**
* Constructor method for this class.
*
* @param g the graph.
* @param ref the reference string.
* @param m the mainController.
* @param depth the depth to draw.
*/
@SuppressFBWarnings("URF_UNREAD_FIELD")
public GraphController(Graph g, Object ref, MainController m, int depth) {
super(new ScrollPane());
this.graph = g;
this.zoomController = new ZoomController(this);
this.maxWidth = 0;
this.graphMouseHandling = new GraphMouseHandling(m);
this.screenSize = Screen.getPrimary().getVisualBounds();
this.maxHeight = (int) screenSize.getHeight();
this.getRoot().setHbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);
this.getRoot().setVbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);
this.position = "";
this.getRoot().addEventFilter(ScrollEvent.SCROLL, event -> {
if (event.getDeltaY() != 0) {
event.consume();
}
});
try {
init(ref, depth);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Getter method for the graph.
*
* @return the graph.
*/
public Graph getGraph() {
return graph;
}
/**
* Getter method for the ZoomController
* @return the ZoomController
*/
public ZoomController getZoomController() {
return zoomController;
}
@Override
public void initialize(URL location, ResourceBundle resources) {
}
/**
* Init method for this class.
*
* @param ref the reference string.
* @param depth the depth to draw.
* @throws IOException Throw exception on read GFA read failure.
*/
public void init(Object ref, int depth) throws IOException {
AnchorPane root = new AnchorPane();
graph.addGraphComponents(ref, depth);
// add components to graph pane
root.getChildren().addAll(graph.getModel().getAddedEdges());
root.getChildren().addAll(graph.getModel().getAddedCells());
List<Cell> list = graph.getModel().getAddedCells();
for (Cell c : list) {
graphMouseHandling.setMouseHandling(c);
}
graph.endUpdate();
GraphLayout layout = new GraphLayout(graph.getModel(), 20,
(int) (screenSize.getHeight() - 25) / 2);
layout.execute();
maxWidth = (int) layout.getMaxWidth();
this.getRoot().setContent(root);
}
/**
* Method to attach the keyHandler to the root of the Controller
*/
public void initKeyHandler() {
this.getRoot().setOnKeyPressed(zoomController.getZoomBox().getKeyHandler());
}
/**
* Getter method for the genomes.
*
* @return the list of genomes.
*/
public List<String> getGenomes() {
return graph.getGenomes();
}
/**
* Getter method for the position of the generated
* snapshot
* @return the position of the snapshot
*/
public String getPosition() {
return position;
}
/**
* Method take a snapshot of the current graph.
*
* @throws IOException Throw exception on write failure.
*/
public Image takeSnapshot() throws IOException {
// try {
WritableImage image = new WritableImage(maxWidth + 50,
(int) screenSize.getHeight());
WritableImage snapshot = this.getRoot().getContent().snapshot(
new SnapshotParameters(), image);
String filePath = System.getProperty("user.home") + "/AppData/Local/Temp";
File output = new File(filePath);
// File temp = File.createTempFile("snapshot", ".png", output);
//ImageIO.write(SwingFXUtils.fromFXImage(snapshot, null), "png", temp);
// position = temp.getName();
// temp.deleteOnExit();
return snapshot;
// } catch (IOException e) {
// e.printStackTrace();
// return null;
}
}
|
package br.com.tupinikimtecnologia.http;
import br.com.tupinikimtecnologia.constants.GeralConstants;
import br.com.tupinikimtecnologia.utils.Utils;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Flooder Object, it's there that will send post and get requests
*/
public class Flooder implements Runnable {
private String targetUrl, targetUrlNew;
private String userAgent;
private int method;
private boolean randomAgent;
private String postData, postDataNew;
private boolean randomData = false;
private int delay;
private int lastResponseCode;
private boolean running = true;
private HttpURLConnection con;
public Flooder(){}
/**
* Set the Flooder to send GET requests
* @param targetUrl the target URL
*/
public Flooder(String targetUrl) {
this.targetUrl = targetUrl.trim();
this.method = 0;
}
/**
* Set the Flooder to send POST requests
* @param targetUrl the target URL
* @param postData the POST data
*/
public Flooder(String targetUrl, String postData) {
this.targetUrl = targetUrl.trim();
this.postData = postData;
this.method = 1;
}
@Override
public void run() {
while(running){
try {
if(method==0){
if(delay!=0){
Thread.sleep(delay*1000);
}
sendGet();
}else if(method==1){
if(delay!=0){
Thread.sleep(delay*1000);
}
sendPost();
}
} catch (Exception e) {
e.printStackTrace();
//this.running = false;
}
}
}
/**
* Send post requests on the target URL
* @throws Exception
*/
private void sendPost() throws Exception {
if(isRandomAgent()){
userAgent = Utils.randomUserAgent();
}
String urlParameters;
if(isRandomData()){
urlParameters = postData.replace(GeralConstants.RandomData.RAND_NAME_FIRST, Utils.randomFirstName());
urlParameters = urlParameters.replace(GeralConstants.RandomData.RAND_NAME_LAST, Utils.randomLastName());
urlParameters = urlParameters.replace(GeralConstants.RandomData.RAND_NAME_FULL, Utils.randomFullName());
urlParameters = urlParameters.replace(GeralConstants.RandomData.RAND_AGE, Utils.randomAge());
urlParameters = urlParameters.replace(GeralConstants.RandomData.RAND_EMAIL, Utils.randomEmail());
urlParameters = urlParameters.replace(GeralConstants.RandomData.RAND_ADDRESS, Utils.randomAddress());
urlParameters = urlParameters.replace(GeralConstants.RandomData.RAND_CITY, Utils.randomCity());
urlParameters = urlParameters.replace(GeralConstants.RandomData.RAND_COUNTRY, Utils.randomCountry());
urlParameters = urlParameters.replace(GeralConstants.RandomData.RAND_PASSWORD, Utils.randomPassword());
urlParameters = urlParameters.replace(GeralConstants.RandomData.RAND_LATITUDE, Utils.randomLatitude());
urlParameters = urlParameters.replace(GeralConstants.RandomData.RAND_LONGITUDE, Utils.randomLongitude());
urlParameters = urlParameters.replace(GeralConstants.RandomData.RAND_SENTENCE, Utils.randomSentence());
}else{
urlParameters = postData;
}
URL obj = new URL(targetUrl);
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", userAgent);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
this.lastResponseCode = con.getResponseCode();
if(GeralConstants.Debug.HTTP_REQUEST_SHOW){
System.out.println("\nPOST URL: " + targetUrl);
System.out.println("Post: " + urlParameters);
System.out.println("Response Code: " + this.lastResponseCode);
System.out.println("Agent: "+this.userAgent);
}
}
/**
* Send post requests on the target URL
* @throws Exception
*/
private void sendGet() throws Exception {
if(isRandomAgent()){
this.userAgent = Utils.randomUserAgent();
}
String url;
if(isRandomData()){
url = targetUrl.replace(GeralConstants.RandomData.RAND_NAME_FIRST, Utils.randomFirstName());
url = url.replace(GeralConstants.RandomData.RAND_NAME_LAST, Utils.randomLastName());
url = url.replace(GeralConstants.RandomData.RAND_NAME_FULL, Utils.randomFullName());
url = url.replace(GeralConstants.RandomData.RAND_AGE, Utils.randomAge());
url = url.replace(GeralConstants.RandomData.RAND_EMAIL, Utils.randomEmail());
url = url.replace(GeralConstants.RandomData.RAND_ADDRESS, Utils.randomAddress());
url = url.replace(GeralConstants.RandomData.RAND_CITY, Utils.randomCity());
url = url.replace(GeralConstants.RandomData.RAND_COUNTRY, Utils.randomCountry());
url = url.replace(GeralConstants.RandomData.RAND_LATITUDE, Utils.randomLatitude());
url = url.replace(GeralConstants.RandomData.RAND_LONGITUDE, Utils.randomLongitude());
url = url.replace(GeralConstants.RandomData.RAND_SENTENCE, Utils.randomSentence());
}else{
url = targetUrl;
}
URL obj = new URL(url);
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("User-Agent", this.userAgent);
this.lastResponseCode = con.getResponseCode();
if(GeralConstants.Debug.HTTP_REQUEST_SHOW){
System.out.println("\nGET URL: " + url);
System.out.println("Response Code: " + this.lastResponseCode);
System.out.println("Agent: "+this.userAgent);
}
}
/**
* Stop the thread
*/
public void stop(){
this.running = false;
}
public void setTargetUrl(String targetUrl) {
this.targetUrl = targetUrl;
}
public String getTargetUrl() {
return targetUrl;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
public String getUserAgent() {
return userAgent;
}
public void setMethod(int method) {
this.method = method;
}
public int getMethod() {
return method;
}
public void setRandomAgent(boolean randomAgent) {
this.randomAgent = randomAgent;
}
public boolean isRandomAgent() {
return randomAgent;
}
public void setPostData(String postData) {
this.postData = postData;
}
public String getPostData() {
return postData;
}
public void setRandomData(boolean randomData) {
this.randomData = randomData;
}
public boolean isRandomData() {
return randomData;
}
public void setDelay(int delay) {
this.delay = delay;
}
public int getDelay() {
return delay;
}
public void setLastResponseCode(int lastResponseCode) {
this.lastResponseCode = lastResponseCode;
}
public int getLastResponseCode() {
return lastResponseCode;
}
public void setRunning(boolean started) {
this.running = started;
}
public boolean isRunning() {
return running;
}
}
|
package com.commafeed.backend.feed;
import java.util.Collections;
import java.util.Map;
import com.google.common.collect.Maps;
public class HtmlEntities {
public static final Map<String, String> NUMERIC_MAPPING = Collections.unmodifiableMap(loadMap());
private static synchronized Map<String, String> loadMap() {
Map<String, String> map = Maps.newLinkedHashMap();
map.put("Á", "Á");
map.put("á", "á");
map.put("Â", "Â");
map.put("â", "â");
map.put("´", "´");
map.put("Æ", "Æ");
map.put("æ", "æ");
map.put("À", "À");
map.put("à", "à");
map.put("ℵ", "ℵ");
map.put("Α", "Α");
map.put("α", "α");
map.put("&", "&
map.put("∧", "∧");
map.put("∠", "∠");
map.put("Å", "Å");
map.put("å", "å");
map.put("≈", "≈");
map.put("Ã", "Ã");
map.put("ã", "ã");
map.put("Ä", "Ä");
map.put("ä", "ä");
map.put("„", "„");
map.put("Β", "Β");
map.put("β", "β");
map.put("¦", "¦");
map.put("•", "•");
map.put("∩", "∩");
map.put("Ç", "Ç");
map.put("ç", "ç");
map.put("¸", "¸");
map.put("¢", "¢");
map.put("Χ", "Χ");
map.put("χ", "χ");
map.put("ˆ", "ˆ");
map.put("♣", "♣");
map.put("≅", "≅");
map.put("©", "©");
map.put("↵", "↵");
map.put("∪", "∪");
map.put("¤", "¤");
map.put("†", "†");
map.put("‡", "‡");
map.put("↓", "↓");
map.put("⇓", "⇓");
map.put("°", "°");
map.put("Δ", "Δ");
map.put("δ", "δ");
map.put("♦", "♦");
map.put("÷", "÷");
map.put("É", "É");
map.put("é", "é");
map.put("Ê", "Ê");
map.put("ê", "ê");
map.put("È", "È");
map.put("è", "è");
map.put("∅", "∅");
map.put(" ", " ");
map.put(" ", " ");
map.put("Ε", "Ε");
map.put("ε", "ε");
map.put("≡", "≡");
map.put("Η", "Η");
map.put("η", "η");
map.put("Ð", "Ð");
map.put("ð", "ð");
map.put("Ë", "Ë");
map.put("ë", "ë");
map.put("€", "€");
map.put("∃", "∃");
map.put("ƒ", "ƒ");
map.put("∀", "∀");
map.put("½", "½");
map.put("¼", "¼");
map.put("¾", "¾");
map.put("⁄", "⁄");
map.put("Γ", "Γ");
map.put("γ", "γ");
map.put("≥", "≥");
map.put("↔", "↔");
map.put("⇔", "⇔");
map.put("♥", "♥");
map.put("…", "…");
map.put("Í", "Í");
map.put("í", "í");
map.put("Î", "Î");
map.put("î", "î");
map.put("¡", "¡");
map.put("Ì", "Ì");
map.put("ì", "ì");
map.put("ℑ", "ℑ");
map.put("∞", "∞");
map.put("∫", "∫");
map.put("Ι", "Ι");
map.put("ι", "ι");
map.put("¿", "¿");
map.put("∈", "∈");
map.put("Ï", "Ï");
map.put("ï", "ï");
map.put("Κ", "Κ");
map.put("κ", "κ");
map.put("Λ", "Λ");
map.put("λ", "λ");
map.put("⟨", "〈");
map.put("«", "«");
map.put("←", "←");
map.put("⇐", "⇐");
map.put("⌈", "⌈");
map.put("“", "“");
map.put("≤", "≤");
map.put("⌊", "⌊");
map.put("∗", "∗");
map.put("◊", "◊");
map.put("‎", "‎");
map.put("‹", "‹");
map.put("‘", "‘");
map.put("¯", "¯");
map.put("—", "—");
map.put("µ", "µ");
map.put("·", "·");
map.put("−", "−");
map.put("Μ", "Μ");
map.put("μ", "μ");
map.put("∇", "∇");
map.put(" ", " ");
map.put("–", "–");
map.put("≠", "≠");
map.put("∋", "∋");
map.put("¬", "¬");
map.put("∉", "∉");
map.put("⊄", "⊄");
map.put("Ñ", "Ñ");
map.put("ñ", "ñ");
map.put("Ν", "Ν");
map.put("ν", "ν");
map.put("Ó", "Ó");
map.put("ó", "ó");
map.put("Ô", "Ô");
map.put("ô", "ô");
map.put("Œ", "Œ");
map.put("œ", "œ");
map.put("Ò", "Ò");
map.put("ò", "ò");
map.put("‾", "‾");
map.put("Ω", "Ω");
map.put("ω", "ω");
map.put("Ο", "Ο");
map.put("ο", "ο");
map.put("⊕", "⊕");
map.put("∨", "∨");
map.put("ª", "ª");
map.put("º", "º");
map.put("Ø", "Ø");
map.put("ø", "ø");
map.put("Õ", "Õ");
map.put("õ", "õ");
map.put("⊗", "⊗");
map.put("Ö", "Ö");
map.put("ö", "ö");
map.put("¶", "¶");
map.put("∂", "∂");
map.put("‰", "‰");
map.put("⊥", "⊥");
map.put("Φ", "Φ");
map.put("φ", "φ");
map.put("Π", "Π");
map.put("π", "π");
map.put("ϖ", "ϖ");
map.put("±", "±");
map.put("£", "£");
map.put("′", "′");
map.put("″", "″");
map.put("∏", "∏");
map.put("∝", "∝");
map.put("Ψ", "Ψ");
map.put("ψ", "ψ");
map.put(""", "&
map.put("√", "√");
map.put("⟩", "〉");
map.put("»", "»");
map.put("→", "→");
map.put("⇒", "⇒");
map.put("⌉", "⌉");
map.put("”", "”");
map.put("ℜ", "ℜ");
map.put("®", "®");
map.put("⌋", "⌋");
map.put("Ρ", "Ρ");
map.put("ρ", "ρ");
map.put("‏", "‏");
map.put("›", "›");
map.put("’", "’");
map.put("‚", "‚");
map.put("Š", "Š");
map.put("š", "š");
map.put("⋅", "⋅");
map.put("§", "§");
map.put("­", "­");
map.put("Σ", "Σ");
map.put("σ", "σ");
map.put("ς", "ς");
map.put("∼", "∼");
map.put("♠", "♠");
map.put("⊂", "⊂");
map.put("⊆", "⊆");
map.put("∑", "∑");
map.put("¹", "¹");
map.put("²", "²");
map.put("³", "³");
map.put("⊃", "⊃");
map.put("⊇", "⊇");
map.put("ß", "ß");
map.put("Τ", "Τ");
map.put("τ", "τ");
map.put("∴", "∴");
map.put("Θ", "Θ");
map.put("θ", "θ");
map.put("ϑ", "ϑ");
map.put(" ", " ");
map.put("Þ", "Þ");
map.put("þ", "þ");
map.put("˜", "˜");
map.put("×", "×");
map.put("™", "™");
map.put("Ú", "Ú");
map.put("ú", "ú");
map.put("↑", "↑");
map.put("⇑", "⇑");
map.put("Û", "Û");
map.put("û", "û");
map.put("Ù", "Ù");
map.put("ù", "ù");
map.put("¨", "¨");
map.put("ϒ", "ϒ");
map.put("Υ", "Υ");
map.put("υ", "υ");
map.put("Ü", "Ü");
map.put("ü", "ü");
map.put("℘", "℘");
map.put("Ξ", "Ξ");
map.put("ξ", "ξ");
map.put("Ý", "Ý");
map.put("ý", "ý");
map.put("¥", "¥");
map.put("ÿ", "ÿ");
map.put("Ÿ", "Ÿ");
map.put("Ζ", "Ζ");
map.put("ζ", "ζ");
map.put("‍", "‍");
map.put("‌", "‌");
return map;
}
}
|
package com.jaeksoft.searchlib.scheduler.task;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import javax.naming.NamingException;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermEnum;
import com.jaeksoft.searchlib.Client;
import com.jaeksoft.searchlib.ClientCatalog;
import com.jaeksoft.searchlib.ClientCatalogItem;
import com.jaeksoft.searchlib.Logging;
import com.jaeksoft.searchlib.SearchLibException;
import com.jaeksoft.searchlib.config.Config;
import com.jaeksoft.searchlib.index.IndexDocument;
import com.jaeksoft.searchlib.scheduler.TaskAbstract;
import com.jaeksoft.searchlib.scheduler.TaskProperties;
import com.jaeksoft.searchlib.scheduler.TaskPropertyDef;
import com.jaeksoft.searchlib.scheduler.TaskPropertyType;
import com.jaeksoft.searchlib.schema.SchemaField;
import com.jaeksoft.searchlib.user.Role;
import com.jaeksoft.searchlib.user.User;
import com.jaeksoft.searchlib.util.StringUtils;
public class TaskPullTerms extends TaskAbstract {
final private TaskPropertyDef propSourceIndex = new TaskPropertyDef(
TaskPropertyType.comboBox, "Index source", 100);
final private TaskPropertyDef propLogin = new TaskPropertyDef(
TaskPropertyType.textBox, "Login (Index target)", 20);
final private TaskPropertyDef propApiKey = new TaskPropertyDef(
TaskPropertyType.password, "API Key (Index target)", 50);
final private TaskPropertyDef propSourceField = new TaskPropertyDef(
TaskPropertyType.textBox, "Source field name", 50);
final private TaskPropertyDef propTermField = new TaskPropertyDef(
TaskPropertyType.textBox, "Term field name", 50);
final private TaskPropertyDef propFreqField = new TaskPropertyDef(
TaskPropertyType.textBox, "Frequency field name", 50);
final private TaskPropertyDef propFreqMin = new TaskPropertyDef(
TaskPropertyType.textBox, "Minimum frequency", 20);
final private TaskPropertyDef propFreqPadSize = new TaskPropertyDef(
TaskPropertyType.textBox, "Frequency pad", 20);
final private TaskPropertyDef[] taskPropertyDefs = { propSourceField,
propSourceIndex, propLogin, propApiKey, propTermField,
propFreqField, propFreqMin, propFreqPadSize };
@Override
public String getName() {
return "Pull terms";
}
@Override
public TaskPropertyDef[] getPropertyList() {
return taskPropertyDefs;
}
@Override
public String[] getPropertyValues(Config config, TaskPropertyDef propertyDef)
throws SearchLibException {
List<String> values = new ArrayList<String>(0);
if (propertyDef == propSourceIndex) {
for (ClientCatalogItem item : ClientCatalog.getClientCatalog(null)) {
String v = item.getIndexName();
if (!v.equals(config.getIndexName()))
values.add(v);
}
} else if (propertyDef == propSourceField) {
for (SchemaField field : config.getSchema().getFieldList()
.getList()) {
if (field.isIndexed())
values.add(field.getName());
}
}
if (values.size() == 0)
return null;
String[] valueArray = new String[values.size()];
values.toArray(valueArray);
return valueArray;
}
@Override
public String getDefaultValue(Config config, TaskPropertyDef propertyDef) {
if (propertyDef == propFreqPadSize)
return "9";
if (propertyDef == propFreqMin)
return "2";
return null;
}
final private static void indexBuffer(List<IndexDocument> buffer,
Client target) throws SearchLibException, NoSuchAlgorithmException,
IOException, URISyntaxException, InstantiationException,
IllegalAccessException, ClassNotFoundException {
if (buffer.size() == 0)
return;
target.updateDocuments(buffer);
buffer.clear();
}
@Override
public void execute(Client client, TaskProperties properties)
throws SearchLibException {
String sourceIndex = properties.getValue(propSourceIndex);
String sourceField = properties.getValue(propSourceField);
String login = properties.getValue(propLogin);
String apiKey = properties.getValue(propApiKey);
String[] targetTermFields = properties.getValue(propTermField).split(
",");
for (int i = 0; i < targetTermFields.length; i++)
targetTermFields[i] = targetTermFields[i].trim();
int freqPadSize = Integer
.parseInt(properties.getValue(propFreqPadSize));
int freqMin = Integer.parseInt(properties.getValue(propFreqMin));
String[] targetFreqFields = properties.getValue(propFreqField).split(
",");
for (int i = 0; i < targetFreqFields.length; i++)
targetFreqFields[i] = targetFreqFields[i].trim();
int bufferSize = 50;
TermEnum termEnum = null;
try {
if (!ClientCatalog.getUserList().isEmpty()) {
User user = ClientCatalog.authenticateKey(login, apiKey);
if (user == null)
throw new SearchLibException("Authentication failed");
if (!user.hasAnyRole(sourceIndex, Role.GROUP_INDEX))
throw new SearchLibException("Not enough right");
}
Client sourceClient = ClientCatalog.getClient(sourceIndex);
if (sourceClient == null)
throw new SearchLibException("Client not found: " + sourceIndex);
SchemaField sourceTermField = sourceClient.getSchema()
.getFieldList().get(sourceField);
if (sourceTermField == null)
throw new SearchLibException("Source field not found: "
+ sourceField);
String sourceFieldName = sourceTermField.getName();
termEnum = sourceClient.getIndex().getTermEnum(sourceFieldName, "");
Term term = null;
String text;
List<IndexDocument> buffer = new ArrayList<IndexDocument>(
bufferSize);
while ((term = termEnum.term()) != null) {
if (!sourceFieldName.equals(term.field()))
break;
IndexDocument indexDocument = new IndexDocument();
text = term.text();
int freq = termEnum.docFreq();
if (freq >= freqMin) {
for (String targetTermField : targetTermFields)
indexDocument.addString(targetTermField, text);
text = StringUtils.leftPad(freq, freqPadSize);
for (String targetFreqField : targetFreqFields)
indexDocument.addString(targetFreqField, text);
buffer.add(indexDocument);
if (buffer.size() == bufferSize)
indexBuffer(buffer, client);
}
if (!termEnum.next())
break;
}
indexBuffer(buffer, client);
} catch (NoSuchAlgorithmException e) {
throw new SearchLibException(e);
} catch (IOException e) {
throw new SearchLibException(e);
} catch (URISyntaxException e) {
throw new SearchLibException(e);
} catch (InstantiationException e) {
throw new SearchLibException(e);
} catch (IllegalAccessException e) {
throw new SearchLibException(e);
} catch (ClassNotFoundException e) {
throw new SearchLibException(e);
} catch (NamingException e) {
throw new SearchLibException(e);
} finally {
if (termEnum != null) {
try {
termEnum.close();
} catch (IOException e) {
Logging.warn(e);
}
termEnum = null;
}
}
}
}
|
package com.foomoo.awf.onedrive;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.foomoo.awf.config.AppOneDriveConfig;
import com.foomoo.awf.oauth2.AccessTokenRepository;
import com.foomoo.awf.oauth2.PersistableDefaultOAuth2AccessToken;
import org.springframework.http.*;
import org.springframework.security.oauth2.client.DefaultOAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails;
import org.springframework.security.oauth2.common.AuthenticationScheme;
import org.springframework.web.client.HttpClientErrorException;
import java.net.URI;
import java.util.Collections;
import java.util.List;
public class OneDriveService {
private static final int PERSISTED_TOKEN_ID = 1;
private volatile OAuth2RestTemplate oAuth2RestTemplate;
private final AppOneDriveConfig oneDriveConfig;
private final AccessTokenRepository accessTokenRepository;
/**
* Construct the service based on the given configuration.
* Loads the application's access token from the given {@link AccessTokenRepository}.
*
* @param oneDriveConfig
*/
public OneDriveService(AppOneDriveConfig oneDriveConfig, AccessTokenRepository accessTokenRepository,
final OAuth2ProtectedResourceDetails details) {
this.oneDriveConfig = oneDriveConfig;
this.accessTokenRepository = accessTokenRepository;
final ClientOnlyAuthorisationCodeResourceDetails wrappedDetails =
new ClientOnlyAuthorisationCodeResourceDetails((AuthorizationCodeResourceDetails) details);
final PersistableDefaultOAuth2AccessToken accessToken = accessTokenRepository.findOne(PERSISTED_TOKEN_ID);
this.oAuth2RestTemplate = new OAuth2RestTemplate(wrappedDetails, new DefaultOAuth2ClientContext(accessToken));
}
public String testConnection(final OAuth2RestTemplate oAuth2RestTemplate) {
final String driveRoot =
oAuth2RestTemplate.getForObject(oneDriveConfig.getBaseUri().resolve("root"), String.class);
final PersistableDefaultOAuth2AccessToken accessToken = new PersistableDefaultOAuth2AccessToken(oAuth2RestTemplate.getAccessToken());
accessToken.id = PERSISTED_TOKEN_ID;
final PersistableDefaultOAuth2AccessToken persistedAccessToken = accessTokenRepository.save(accessToken);
final ClientOnlyAuthorisationCodeResourceDetails wrappedDetails =
new ClientOnlyAuthorisationCodeResourceDetails((AuthorizationCodeResourceDetails) oAuth2RestTemplate.getResource());
this.oAuth2RestTemplate = new OAuth2RestTemplate(wrappedDetails,
new DefaultOAuth2ClientContext(persistedAccessToken));
return driveRoot;
}
public void ensureFolderExists() {
final ObjectMapper mapper = new ObjectMapper();
final String folderName = oneDriveConfig.getFolder();
final FolderDriveItem folderDriveItem = new FolderDriveItem(folderName);
final URI driveRootChildrenUri = oneDriveConfig.getBaseUri().resolve("root/children");
try {
final ResponseEntity<FolderDriveItem> response = oAuth2RestTemplate.postForEntity(driveRootChildrenUri, folderDriveItem, FolderDriveItem.class);
} catch (HttpClientErrorException clientError) {
if (HttpStatus.CONFLICT == clientError.getStatusCode()) {
System.out.println("Folder already exists. Looking up DriveItem.");
} else {
throw clientError;
}
}
}
/**
* Write the given file content into OneDrive at a path relative the folder specified in the OneDrive configuration.
*
* @param relativePath The path to the file to write to in OneDrive.
* @param content The content of the file.
*/
public void writeFile(final String relativePath, byte[] content) {
if (null == oAuth2RestTemplate) {
throw new IllegalStateException("No access configured for OneDrive");
}
final String folderName = oneDriveConfig.getFolder();
final String uriString = oneDriveConfig.getBaseUri().toString() + "root:/" + folderName + "/" + relativePath + ":/createUploadSession";
final String encodedUriString = uriString.replaceAll(" ", "%20");
final URI createUploadSessionUri = URI.create(encodedUriString);
final ResponseEntity<UploadSession> uploadSessionResponse = oAuth2RestTemplate.postForEntity(createUploadSessionUri, Collections.emptyMap(), UploadSession.class);
final URI uploadUrl = uploadSessionResponse.getBody().getUploadUrl();
final HttpHeaders headers = new HttpHeaders();
headers.set("Content-Range", "bytes 0-" + (content.length - 1) + "/" + content.length);
final HttpEntity<byte[]> httpRequest = new HttpEntity<byte[]>(content, headers);
oAuth2RestTemplate.exchange(uploadUrl, HttpMethod.PUT, httpRequest, String.class);
}
@JsonIgnoreProperties(ignoreUnknown = true)
private static class UploadSession {
@JsonProperty
private URI uploadUrl;
public void setUploadUrl(URI uploadUrl) {
this.uploadUrl = uploadUrl;
}
public URI getUploadUrl() {
return uploadUrl;
}
}
/**
* Wrap an {@link org.springframework.security.oauth2.client.token.grant.code.AuthorizationCodeResourceDetails} object to report it as being client only. This
* allows credentials to be cached and renewed without the user being present.
*/
private static class ClientOnlyAuthorisationCodeResourceDetails extends AuthorizationCodeResourceDetails {
private final AuthorizationCodeResourceDetails delegate;
public ClientOnlyAuthorisationCodeResourceDetails(final AuthorizationCodeResourceDetails delegate) {
this.delegate = delegate;
}
@Override
public String getId() {
return delegate.getId();
}
@Override
public String getClientId() {
return delegate.getClientId();
}
@Override
public String getAccessTokenUri() {
return delegate.getAccessTokenUri();
}
@Override
public boolean isScoped() {
return delegate.isScoped();
}
@Override
public List<String> getScope() {
return delegate.getScope();
}
@Override
public boolean isAuthenticationRequired() {
return delegate.isAuthenticationRequired();
}
@Override
public String getClientSecret() {
return delegate.getClientSecret();
}
@Override
public AuthenticationScheme getClientAuthenticationScheme() {
return delegate.getClientAuthenticationScheme();
}
@Override
public String getGrantType() {
return delegate.getGrantType();
}
@Override
public AuthenticationScheme getAuthenticationScheme() {
return delegate.getAuthenticationScheme();
}
@Override
public String getTokenName() {
return delegate.getTokenName();
}
@Override
public boolean isClientOnly() {
return true;
}
}
}
|
package fr.paris.lutece.portal.service.portal;
import fr.paris.lutece.portal.business.style.Theme;
import fr.paris.lutece.portal.service.content.PageData;
import fr.paris.lutece.portal.service.database.AppConnectionService;
import fr.paris.lutece.portal.service.i18n.I18nService;
import fr.paris.lutece.portal.service.plugin.Plugin;
import fr.paris.lutece.portal.service.plugin.PluginService;
import fr.paris.lutece.portal.service.spring.SpringContextService;
import fr.paris.lutece.portal.service.util.AppLogService;
import fr.paris.lutece.portal.service.util.AppPropertiesService;
import fr.paris.lutece.util.ReferenceItem;
import fr.paris.lutece.util.ReferenceList;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.CannotLoadBeanClassException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Locale;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* ThemesService
*/
public final class ThemesService
{
public static final String GLOBAL_THEME = "default";
private static final String THEME_PLUGIN_NAME = "theme";
private static final String BEAN_THEME_SERVICE = "theme.themeService";
private static final String COOKIE_NAME = "theme";
private static final String THEME_TEST = "theme_test";
// PROPERTIES
private static final String PROPERTY_USE_GLOBAL_THEME = "portal.style.label.useGlobalTheme";
private static final String PROPERTY_DEFAULT_CODE_THEME = "themes.default.code";
private static final String PROPERTY_DEFAULT_PATH_CSS = "themes.default.css";
private static final String PROPERTY_DEFAULT_PATH_JS = "themes.default.js";
private static final String PROPERTY_DEFAULT_PATH_IMAGE = "themes.default.images";
private static final String PROPERTY_DEFAULT_AUTHOR_URL = "themes.default.author_url";
private static final String PROPERTY_DEFAULT_AUTHOR = "themes.default.author";
private static final String PROPERTY_DEFAULT_LICENCE = "themes.default.licence";
private static final String PROPERTY_DEFAULT_DESCRIPTION = "themes.default.name";
private static final String PROPERTY_DEFAULT_VERSION = "themes.default.version";
// MESSAGES
private static final String MESSAGE_THEME_NOT_AVAILABLE = "Theme service not available.";
/**
* Private constructor
*/
private ThemesService( )
{
}
/**
* Get the theme code depending of the different priorities. The priorities are :
* <ol>
* <li>the theme of test (in case you want to test a page with a specific theme)</li>
* <li>the theme choosen by the user</li>
* <li>the global theme : the one choosen in the back office for the whole site</li>
* <li>the page theme : a theme specified for a page</li>
* </ol>
*
* @param data
* The PageData object
* @param request
* The HttpServletRequest
* @return the theme
*/
public static Theme getTheme( PageData data, HttpServletRequest request )
{
String strTheme = StringUtils.EMPTY;
// The code_theme of the page
String strPageTheme = data.getTheme( );
if ( ( strPageTheme != null ) && ( strPageTheme.compareToIgnoreCase( GLOBAL_THEME ) != 0 ) )
{
strTheme = strPageTheme;
}
// The theme of the user
String strUserTheme = getUserTheme( request );
if ( strUserTheme != null )
{
strTheme = strUserTheme;
}
// the test theme (choosen for a page to test the different theme from the backoffice theme section)
String themeTest = request.getParameter( THEME_TEST );
if ( themeTest != null )
{
strTheme = themeTest;
}
Theme theme = getGlobalTheme( strTheme );
return theme;
}
/**
* Gets the theme selected by the user
*
* @param request
* The HTTP request
* @return The theme if available otherwise null
*/
public static String getUserTheme( HttpServletRequest request )
{
try
{
IThemeService themeService = getThemeService( );
return themeService.getUserTheme( request );
}
catch( ThemeNotAvailableException e )
{
return null;
}
}
/**
* Sets the users theme using a cookie
*
* @param request
* The HTTP request
* @param response
* The HTTP response
* @param strTheme
* The Theme code
*/
public static void setUserTheme( HttpServletRequest request, HttpServletResponse response, String strTheme )
{
if( isValid( strTheme ))
{
Cookie cookie = new Cookie( COOKIE_NAME, strTheme );
cookie.setSecure( true );
response.addCookie( cookie );
}
}
/**
* Check if a given theme code is among valid known theme codes
* @param strTheme The theme
* @return true if valid
*/
private static boolean isValid( String strTheme )
{
for( ReferenceItem item : getThemes( ))
{
if( item.getCode().equals( strTheme ))
{
return true;
}
}
return false;
}
/**
* Returns the global theme
*
* @return the global theme
*/
public static String getGlobalTheme( )
{
Theme theme = getGlobalTheme( StringUtils.EMPTY );
return theme.getCodeTheme( );
}
/**
* Returns the global theme Object
*
* @return the global theme Object
*/
public static Theme getGlobalThemeObject( )
{
return getGlobalTheme( StringUtils.EMPTY );
}
/**
* Returns the global theme
*
* @param strTheme
* The theme
* @return the global theme
*/
public static Theme getGlobalTheme( String strTheme )
{
Theme theme = null;
try
{
IThemeService themeService = getThemeService( );
if ( StringUtils.isBlank( strTheme ) )
{
theme = themeService.getGlobalTheme( );
}
else
{
theme = themeService.getTheme( strTheme );
}
}
catch( ThemeNotAvailableException e )
{
theme = getDefaultTheme( );
}
return theme;
}
/**
* Sets the global theme
*
* @param strGlobalTheme
* The global theme
*/
public static void setGlobalTheme( String strGlobalTheme )
{
IThemeService themeService;
try
{
themeService = getThemeService( );
themeService.setGlobalTheme( strGlobalTheme );
}
catch( ThemeNotAvailableException e )
{
AppLogService.info( MESSAGE_THEME_NOT_AVAILABLE );
}
}
/**
* Returns a reference list which contains all the themes
*
* @param locale
* The Locale
* @return a reference list
*/
public static ReferenceList getPageThemes( Locale locale )
{
ReferenceList listThemes = new ReferenceList( );
try
{
IThemeService themeService = getThemeService( );
listThemes = themeService.getThemes( );
}
catch( ThemeNotAvailableException e )
{
AppLogService.info( MESSAGE_THEME_NOT_AVAILABLE );
}
String strGlobalTheme = I18nService.getLocalizedString( PROPERTY_USE_GLOBAL_THEME, locale );
listThemes.addItem( GLOBAL_THEME, strGlobalTheme );
return listThemes;
}
/**
* Get the theme service
*
* @return the theme service
* @throws ThemeNotAvailableException
* If the theme is not available
*/
private static IThemeService getThemeService( ) throws ThemeNotAvailableException
{
IThemeService themeService = null;
if ( !isAvailable( ) )
{
throw new ThemeNotAvailableException( );
}
try
{
themeService = SpringContextService.getBean( BEAN_THEME_SERVICE );
}
catch( BeanDefinitionStoreException e )
{
throw new ThemeNotAvailableException( );
}
catch( NoSuchBeanDefinitionException e )
{
throw new ThemeNotAvailableException( );
}
catch( CannotLoadBeanClassException e )
{
throw new ThemeNotAvailableException( );
}
return themeService;
}
/**
* Return the default theme in properties
*
* @return the default theme
*/
private static Theme getDefaultTheme( )
{
Theme theme = new Theme( );
String strCodeTheme = AppPropertiesService.getProperty( PROPERTY_DEFAULT_CODE_THEME );
String strPathCss = AppPropertiesService.getProperty( PROPERTY_DEFAULT_PATH_CSS );
String strPathImages = AppPropertiesService.getProperty( PROPERTY_DEFAULT_PATH_IMAGE );
String strPathJs = AppPropertiesService.getProperty( PROPERTY_DEFAULT_PATH_JS );
String strThemeAuthor = AppPropertiesService.getProperty( PROPERTY_DEFAULT_AUTHOR );
String strThemeAuthorUrl = AppPropertiesService.getProperty( PROPERTY_DEFAULT_AUTHOR_URL );
String strThemeDescription = AppPropertiesService.getProperty( PROPERTY_DEFAULT_DESCRIPTION );
String strThemeLicence = AppPropertiesService.getProperty( PROPERTY_DEFAULT_LICENCE );
String strThemeVersion = AppPropertiesService.getProperty( PROPERTY_DEFAULT_VERSION );
theme.setCodeTheme( strCodeTheme );
theme.setPathCss( strPathCss );
theme.setPathImages( strPathImages );
theme.setPathJs( strPathJs );
theme.setThemeAuthor( strThemeAuthor );
theme.setThemeAuthorUrl( strThemeAuthorUrl );
theme.setThemeDescription( strThemeDescription );
theme.setThemeLicence( strThemeLicence );
theme.setThemeVersion( strThemeVersion );
return theme;
}
/**
* Check if the theme service is available. It must have the following requirement to be available :
* <ul>
* <li>The <code>plugin-theme</code> is activated</li>
* <li>The pool of the <code>plugin-theme</code> is defined</li>
* </ul>
*
* @return true if it is available, false otherwise
*/
public static boolean isAvailable( )
{
Plugin pluginTheme = PluginService.getPlugin( THEME_PLUGIN_NAME );
return PluginService.isPluginEnable( THEME_PLUGIN_NAME ) && ( pluginTheme.getDbPoolName( ) != null )
&& !AppConnectionService.NO_POOL_DEFINED.equals( pluginTheme.getDbPoolName( ) );
}
/**
* Create a new theme
*
* @param theme
* the theme
* @return The theme
*/
public static Theme create( Theme theme )
{
try
{
IThemeService themeService = getThemeService( );
return themeService.create( theme );
}
catch( ThemeNotAvailableException e )
{
AppLogService.info( MESSAGE_THEME_NOT_AVAILABLE );
return null;
}
}
/**
* Update a theme
*
* @param theme
* the theme to update
* @return The updated theme
*/
public static Theme update( Theme theme )
{
try
{
IThemeService themeService = getThemeService( );
return themeService.update( theme );
}
catch( ThemeNotAvailableException e )
{
AppLogService.info( MESSAGE_THEME_NOT_AVAILABLE );
return null;
}
}
/**
* Remove a theme
*
* @param strCodeTheme
* the code theme
*/
public static void remove( String strCodeTheme )
{
try
{
IThemeService themeService = getThemeService( );
themeService.remove( strCodeTheme );
}
catch( ThemeNotAvailableException e )
{
AppLogService.info( MESSAGE_THEME_NOT_AVAILABLE );
}
}
/**
* Get a collection of themes
*
* @return a collection of themes
*/
public static Collection<Theme> getThemesList( )
{
Collection<Theme> listThemes = new ArrayList<Theme>( );
try
{
IThemeService themeService = getThemeService( );
listThemes = themeService.getThemesList( );
}
catch( ThemeNotAvailableException e )
{
Theme theme = getDefaultTheme( );
listThemes.add( theme );
}
return listThemes;
}
/**
* Get the list of themes as a {@link ReferenceList}
*
* @return a {@link ReferenceList}
*/
public static ReferenceList getThemes( )
{
ReferenceList listThemes = new ReferenceList( );
try
{
IThemeService themeService = getThemeService( );
listThemes = themeService.getThemes( );
}
catch( ThemeNotAvailableException e )
{
Theme theme = getDefaultTheme( );
listThemes.addItem( theme.getCodeTheme( ), theme.getThemeDescription( ) );
}
return listThemes;
}
/**
* Check if the theme is valid
*
* @param strCodeTheme
* the code theme
* @return true if it is valid, false otherwise
*/
public static boolean isValidTheme( String strCodeTheme )
{
boolean bIsValidTheme = false;
try
{
IThemeService themeService = getThemeService( );
bIsValidTheme = themeService.isValidTheme( strCodeTheme );
}
catch( ThemeNotAvailableException e )
{
Theme theme = getDefaultTheme( );
bIsValidTheme = theme.getCodeTheme( ).equals( strCodeTheme );
}
return bIsValidTheme;
}
}
|
package org.apache.commons.lang;
import java.util.Arrays;
/**
* <p>Thrown to indicate an incomplete argument to a method.</p>
*
* @author Matthew Hawthorne
* @since 2.0
* @version $Id: IncompleteArgumentException.java,v 1.5 2004/01/10 01:59:40 fredrik Exp $
*/
public class IncompleteArgumentException extends IllegalArgumentException {
/**
* <p>Instantiates with the specified description.</p>
*
* @param argName a description of the incomplete argument
*/
public IncompleteArgumentException(String argName) {
super(argName + " is incomplete.");
}
/**
* <p>Instantiates with the specified description.</p>
*
* @param argName a description of the incomplete argument
* @param items an array describing the arguments missing
*/
public IncompleteArgumentException(String argName, String[] items) {
super(
argName
+ " is missing the following items: "
+ safeArrayToString(items));
}
/**
* <p>Converts an array to a string without throwing an exception.</p>
*
* @param array an array
* @return the array as a string
*/
private static final String safeArrayToString(Object[] array) {
return array == null ? null : Arrays.asList(array).toString();
}
}
|
package com.fulmicoton.multiregexp;
import dk.brics.automaton.Automaton;
import dk.brics.automaton.RegExp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MultiPattern {
private final List<String> patterns;
private MultiPattern(List<String> patterns) {
this.patterns = new ArrayList<>(patterns);
}
public static MultiPattern of(List<String> patterns) {
return new MultiPattern(patterns);
}
public static MultiPattern of(String... patterns) {
return new MultiPattern(Arrays.asList(patterns));
}
public MultiPatternAutomaton makeAutomatonWithPrefix(String prefix) {
final List<Automaton> automata = new ArrayList<>();
for (String ptn: this.patterns) {
final String prefixedPattern = prefix + ptn;
final Automaton automaton = new RegExp(prefixedPattern).toAutomaton();
automaton.minimize();
automata.add(automaton);
}
return MultiPatternAutomaton.make(automata);
}
/**
* Equivalent of Pattern.compile, but the result is only valid for pattern search.
* The searcher will return the first occurrence of a pattern.
*
* This operation is costly, make sure to cache its result when performing
* search with the same patterns against the different strings.
*
* @return A searcher object
*/
public MultiPatternSearcher searcher() {
final MultiPatternAutomaton searcherAutomaton = makeAutomatonWithPrefix(".*");
final List<Automaton> indidivualAutomatons = new ArrayList<>();
for (final String pattern: this.patterns) {
final Automaton automaton = new RegExp(pattern).toAutomaton();
automaton.minimize();
automaton.determinize();
indidivualAutomatons.add(automaton);
}
return new MultiPatternSearcher(searcherAutomaton, indidivualAutomatons);
}
/**
* Equivalent of Pattern.compile, but the result is only valid for full string matching.
*
* If more than one pattern are matched, with a match ending at the same offset,
* return all of the pattern ids in a sorted array.
*
* This operation is costly, make sure to cache its result when performing
* search with the same patterns against the different strings.
*
* @return A searcher object
*/
public MultiPatternMatcher matcher() {
final MultiPatternAutomaton matcherAutomaton = makeAutomatonWithPrefix("");
return new MultiPatternMatcher(matcherAutomaton);
}
}
|
package com.github.andriell.gui.process;
import com.github.andriell.processor.ManagerInterface;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
public class Process extends JPanel {
private static final int P = 5;
private static final int TW;
private static final int TH = 20;
private static final int W13 = 90;
private static final int W24 = 60;
private static final int H = 20;
private static final Dimension size;
private static final Font fontTitle = new Font("Arial", Font.PLAIN, 16);
private static final Border border = BorderFactory.createLineBorder(Color.black);
//private static final Border border2 = BorderFactory.createLineBorder(Color.YELLOW);
private static final Border border2 = null;
static {
TW = W13 * 2 + W24 * 2 + P * 3;
size = new Dimension(TW + P * 2, TH + P * 2 + (H + P) * 2);
}
private JLabel inQueue;
private JLabel timeLeft;
private JLabel runProcess;
private JSpinner limit;
private ManagerInterface manager;
private int startCount = 0;
private long startTime = 0L;
public Process(ManagerInterface manager) {
this.manager = manager;
setLayout(null);
setPreferredSize(size);
setBorder(border);
JLabel title = new JLabel(manager.getProcessBeanId(), JLabel.CENTER);
title.setSize(TW, TH);
title.setLocation(P, P);
title.setFont(fontTitle);
title.setBorder(border2);
add(title);
JLabel label = new JLabel("In queue:");
label.setSize(W13, H);
label.setLocation(P, TH + P * 2);
label.setBorder(border2);
add(label);
inQueue = new JLabel("0");
inQueue.setSize(W24, H);
inQueue.setLocation(W13 + P * 2, TH + P * 2);
inQueue.setBorder(border2);
add(inQueue);
label = new JLabel("Run process:");
label.setSize(W13, H);
label.setLocation(W13 + W24 + P * 3, TH + P * 2);
label.setBorder(border2);
add(label);
runProcess = new JLabel("0");
runProcess.setSize(W24, H);
runProcess.setLocation(W13 * 2 + W24 + P * 4, TH + P * 2);
runProcess.setBorder(border2);
add(runProcess);
label = new JLabel("Limit process:");
label.setSize(W13, H);
label.setLocation(P, TH + H + P * 3);
label.setBorder(border2);
add(label);
limit = new JSpinner();
limit.setSize(40, H);
limit.setLocation(W13 + P * 2, TH + H + P * 3);
add(limit);
label = new JLabel("Time left:");
label.setSize(W13, H);
label.setLocation(W13 + W24 + P * 3, TH + H + P * 3);
label.setBorder(border2);
add(label);
timeLeft = new JLabel("00:00:00");
timeLeft.setSize(W24, H);
timeLeft.setLocation(W13 * 2 + W24 + P * 4, TH + H + P * 3);
timeLeft.setBorder(border2);
add(timeLeft);
}
private static String secToTime(int totalSecs) {
int hours = totalSecs / 3600;
int minutes = (totalSecs % 3600) / 60;
int seconds = totalSecs % 60;
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
}
public void update() {
int count = manager.getProcessInQueue();
long time = System.currentTimeMillis();
inQueue.setText(Integer.toString(count));
runProcess.setText(Integer.toString(manager.getRunningProcesses()));
limit.setValue(manager.getLimitProcess());
if (count > 10 && startTime > 0) {
float inTime = (startCount - count) / ((time - startTime) / 1000);
if (inTime > 0) {
timeLeft.setText(secToTime(Math.round((count / inTime))));
}
} else {
startTime = time;
startCount = count;
}
}
}
|
package org.drools.gorm.session;
import java.util.Collections;
import java.util.Date;
import java.util.IdentityHashMap;
import java.util.Map;
import org.drools.KnowledgeBase;
import org.drools.RuleBase;
import org.drools.SessionConfiguration;
import org.drools.command.Command;
import org.drools.command.Context;
import org.drools.command.impl.ContextImpl;
import org.drools.command.impl.GenericCommand;
import org.drools.command.impl.KnowledgeCommandContext;
import org.drools.common.EndOperationListener;
import org.drools.common.InternalKnowledgeRuntime;
import org.drools.gorm.GrailsIntegration;
import org.drools.gorm.session.marshalling.GormSessionMarshallingHelper;
import org.drools.impl.KnowledgeBaseImpl;
import org.drools.persistence.session.JpaJDKTimerService;
import org.drools.process.instance.WorkItemManager;
import org.drools.runtime.Environment;
import org.drools.runtime.KnowledgeSessionConfiguration;
import org.drools.runtime.StatefulKnowledgeSession;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
public class SingleSessionCommandService
implements
org.drools.command.SingleSessionCommandService {
private SessionInfo sessionInfo;
private GormSessionMarshallingHelper marshallingHelper;
private StatefulKnowledgeSession ksession;
private Environment env;
private KnowledgeCommandContext kContext;
private volatile boolean doRollback;
public void checkEnvironment(Environment env) {
}
public SingleSessionCommandService(RuleBase ruleBase,
SessionConfiguration conf,
Environment env) {
this( new KnowledgeBaseImpl( ruleBase ),
conf,
env );
}
public SingleSessionCommandService(int sessionId,
RuleBase ruleBase,
SessionConfiguration conf,
Environment env) {
this( sessionId,
new KnowledgeBaseImpl( ruleBase ),
conf,
env );
}
public SingleSessionCommandService(KnowledgeBase kbase,
KnowledgeSessionConfiguration conf,
Environment env) {
if ( conf == null ) {
conf = new SessionConfiguration();
}
this.env = env;
checkEnvironment( this.env );
this.sessionInfo = GrailsIntegration.getGormDomainService().getNewSessionInfo();
// create session but bypass command service
this.ksession = kbase.newStatefulKnowledgeSession(conf, this.env);
this.kContext = new KnowledgeCommandContext( new ContextImpl( "ksession",
null ),
null,
null,
this.ksession,
null );
((JpaJDKTimerService) ((InternalKnowledgeRuntime) ksession).getTimerService()).setCommandService( this );
this.marshallingHelper = new GormSessionMarshallingHelper( this.ksession,
conf );
this.sessionInfo.setMarshallingHelper( this.marshallingHelper );
((InternalKnowledgeRuntime) this.ksession).setEndOperationListener( new EndOperationListenerImpl() );
// Use the App scoped EntityManager if the user has provided it, and it is open.
PlatformTransactionManager txManager = GrailsIntegration.getTransactionManager();
DefaultTransactionDefinition txDef = new DefaultTransactionDefinition();
txDef.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus status = txManager.getTransaction(txDef);
try {
this.env.set(SessionInfo.SAFE_GORM_COMMIT_STATE, false);
registerRollbackSync();
GrailsIntegration.getGormDomainService().saveDomain(this.sessionInfo);
this.env.set(SessionInfo.SAFE_GORM_COMMIT_STATE, true);
txManager.commit(status);
} catch ( Exception t1 ) {
try {
txManager.rollback(status);
} catch ( Throwable t2 ) {
throw new RuntimeException( "Could not commit session or rollback",
t2 );
}
throw new RuntimeException( "Could not commit session",
t1 );
}
// update the session id to be the same as the session info id
((InternalKnowledgeRuntime) ksession).setId( this.sessionInfo.getId() );
}
public SingleSessionCommandService(int sessionId,
KnowledgeBase kbase,
KnowledgeSessionConfiguration conf,
Environment env) {
if ( conf == null ) {
conf = new SessionConfiguration();
}
this.env = env;
checkEnvironment( this.env );
initKsession( sessionId,
kbase,
conf );
}
public void initKsession(int sessionId,
KnowledgeBase kbase,
KnowledgeSessionConfiguration conf) {
if ( !doRollback && this.ksession != null ) {
return;
// nothing to initialise
}
this.doRollback = false;
try {
this.sessionInfo = GrailsIntegration.getGormDomainService().getSessionInfo(sessionId);
} catch ( Exception e ) {
throw new RuntimeException( "Could not find session data for id " + sessionId,
e );
}
if ( sessionInfo == null ) {
throw new RuntimeException( "Could not find session data for id " + sessionId );
}
if ( this.marshallingHelper == null ) {
// this should only happen when this class is first constructed
this.marshallingHelper = new GormSessionMarshallingHelper( kbase,
conf,
env );
}
this.sessionInfo.setMarshallingHelper( this.marshallingHelper );
// if this.ksession is null, it'll create a new one, else it'll use the existing one
this.ksession = this.marshallingHelper.loadSnapshot( this.sessionInfo.getData(),
this.ksession );
// update the session id to be the same as the session info id
((InternalKnowledgeRuntime) ksession).setId( this.sessionInfo.getId() );
((InternalKnowledgeRuntime) this.ksession).setEndOperationListener( new EndOperationListenerImpl() );
((JpaJDKTimerService) ((InternalKnowledgeRuntime) ksession).getTimerService()).setCommandService( this );
if ( this.kContext == null ) {
// this should only happen when this class is first constructed
this.kContext = new KnowledgeCommandContext( new ContextImpl( "ksession",
null ),
null,
null,
this.ksession,
null );
}
}
public class EndOperationListenerImpl implements EndOperationListener {
public void endOperation(InternalKnowledgeRuntime kruntime) {
SingleSessionCommandService.this.sessionInfo.setLastModificationDate( new Date( kruntime.getLastIdleTimestamp() ) );
}
}
public Context getContext() {
return this.kContext;
}
public synchronized <T> T execute(Command<T> command) {
PlatformTransactionManager txManager = GrailsIntegration.getTransactionManager();
DefaultTransactionDefinition txDef = new DefaultTransactionDefinition();
txDef.setPropagationBehavior(DefaultTransactionDefinition.PROPAGATION_REQUIRED);
TransactionStatus status = txManager.getTransaction(txDef);
try {
this.env.set(SessionInfo.SAFE_GORM_COMMIT_STATE, false);
initKsession( this.sessionInfo.getId(),
this.marshallingHelper.getKbase(),
this.marshallingHelper.getConf() );
registerRollbackSync();
T result = ((GenericCommand<T>) command).execute( this.kContext );
this.env.set(SessionInfo.SAFE_GORM_COMMIT_STATE, true);
txManager.commit(status);
return result;
} catch (RuntimeException e){
status.setRollbackOnly();
throw e;
} catch ( Exception e ) {
status.setRollbackOnly();
throw new RuntimeException("Wrapped exception see cause", e);
}
}
public void dispose() {
if ( ksession != null ) {
ksession.dispose();
}
}
public int getSessionId() {
return sessionInfo.getId();
}
@SuppressWarnings("unchecked")
private Map<Object, Object> getSyncronizationMap() {
Map<Object, Object> map = (Map<Object, Object>) env.get("synchronizations");
if ( map == null ) {
map = Collections.synchronizedMap( new IdentityHashMap<Object, Object>() );
env.set("synchronizations", map);
}
return map;
}
private void registerRollbackSync() throws IllegalStateException {
Map<Object, Object> map = getSyncronizationMap();
if (!map.containsKey( this )) {
TransactionSynchronizationManager.registerSynchronization(new SynchronizationImpl());
map.put(this, this);
}
}
private class SynchronizationImpl
implements TransactionSynchronization {
@Override
public void suspend() {}
@Override
public void resume() {}
@Override
public void flush() {}
@Override
public void beforeCommit(boolean readOnly) {}
@Override
public void beforeCompletion() {}
@Override
public void afterCommit() {}
@Override
public void afterCompletion(int status) {
try {
if (status != TransactionSynchronization.STATUS_COMMITTED) {
SingleSessionCommandService.this.rollback();
}
// clean up cached process and work item instances
StatefulKnowledgeSession ksession = SingleSessionCommandService.this.ksession;
if (ksession != null) {
((InternalKnowledgeRuntime) ksession).getProcessRuntime().clearProcessInstances();
((WorkItemManager) ksession.getWorkItemManager()).clear();
}
} finally {
SingleSessionCommandService.this.getSyncronizationMap().remove(SingleSessionCommandService.this);
}
}
}
private void rollback() {
this.doRollback = true;
}
}
|
package com.github.anno4j.querying;
import com.github.anno4j.model.Annotation;
import com.github.anno4j.model.ontologies.*;
import com.github.anno4j.querying.evaluation.EvalQuery;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.sparql.algebra.Algebra;
import com.hp.hpl.jena.sparql.algebra.Op;
import com.hp.hpl.jena.sparql.algebra.OpAsQuery;
import org.apache.marmotta.ldpath.parser.ParseException;
import org.openrdf.model.vocabulary.OWL;
import org.openrdf.model.vocabulary.RDFS;
import org.openrdf.model.vocabulary.SKOS;
import org.openrdf.query.MalformedQueryException;
import org.openrdf.query.QueryEvaluationException;
import org.openrdf.repository.RepositoryException;
import org.openrdf.repository.object.ObjectConnection;
import org.openrdf.repository.object.ObjectQuery;
import org.openrdf.repository.object.ObjectRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The QueryService allows to query the MICO triple stores by using criteria. Furthermore
* this is provided by simple classes. This is why the user does not need to write SPARQL queries
* by himself.
*
* @param <T>
* @author Andreas Eisenkolb
*/
public class QueryService<T extends Annotation> {
private final Logger logger = LoggerFactory.getLogger(QueryService.class);
/**
* The type of the result set.
*/
private Class<T> type;
/**
* The repository needed for the actual querying
*/
private ObjectRepository objectRepository;
/**
* LDPath for the shortcut method setBodyCriteria
*/
private final String BODY_PREFIX = "oa:hasBody/";
/**
* LDPath for the shortcut method setTargetCriteria
*/
private final String TARGET_PREFIX = "oa:hasTarget/";
/**
* LDPath for the shortcut method setSourceCriteria
*/
private final String SOURCE_PREFIX = TARGET_PREFIX + "oa:hasSource/";
/**
* LDPath for the shortcut method setSelectorCriteria
*/
private final String SELECTOR_PREFIX = TARGET_PREFIX + "oa:hasSelector/";
/**
* All user defined name spaces
*/
private Map<String, String> prefixes = new HashMap<String, String>();
/**
* All user defined criteria
*/
private ArrayList<Criteria> criteria = new ArrayList<Criteria>();
/**
* Specifies the ordering of the result set
*/
private Order order = null;
/**
* Limit value of the query
*/
private Integer limit = null;
/**
* Offset value for the query
*/
private Integer offset = null;
/**
* Required to have an ongoing variable name when creating the SPARQL query
*/
private int varIndex = 0;
public QueryService(Class<T> type, ObjectRepository objectRepository) {
this.type = type;
this.objectRepository = objectRepository;
// Setting some standard name spaces
addPrefix(OADM.PREFIX, OADM.NS);
addPrefix(CNT.PREFIX, CNT.NS);
addPrefix(DC.PREFIX, DC.NS);
addPrefix(DCTERMS.PREFIX, DCTERMS.NS);
addPrefix(DCTYPES.PREFIX, DCTYPES.NS);
addPrefix(FOAF.PREFIX, FOAF.NS);
addPrefix(PROV.PREFIX, PROV.NS);
addPrefix(RDF.PREFIX, RDF.NS);
addPrefix(OWL.PREFIX, OWL.NAMESPACE);
addPrefix(RDFS.PREFIX, RDFS.NAMESPACE);
addPrefix(SKOS.PREFIX, SKOS.NAMESPACE);
}
/**
* Setting a criteria for filtering eu.mico.platform.persistence.impl.BodyImpl.* objects.
*
* @param ldpath Syntax similar to XPath. Beginning from the Body object
* @param comparison The comparison mode, e.g. Comparison.EQ (=)
* @param value The constraint value
* @return itself to allow chaining.
*/
public QueryService setBodyCriteria(String ldpath, String value, Comparison comparison) {
criteria.add(new Criteria(BODY_PREFIX + ldpath, value, comparison));
return this;
}
/**
* Setting a criteria for filtering eu.mico.platform.persistence.impl.BodyImpl.* objects.
*
* @param ldpath Syntax similar to XPath. Beginning from the Body object
* @param comparison The comparison mode, e.g. Comparison.EQ (=)
* @param value The constraint value
* @return itself to allow chaining.
*/
public QueryService setBodyCriteria(String ldpath, Number value, Comparison comparison) {
criteria.add(new Criteria(BODY_PREFIX + ldpath, value, comparison));
return this;
}
/**
* Setting a criteria for filtering eu.mico.platform.persistence.impl.BodyImpl.* objects. Compared to the
* other <i>setBodyCriteria</i> function, this function does not need a <b>Comparison</b> statement. Hence,
* the Comparison.EQ statement ("=") will be used automatically.
*
* @param ldpath Syntax similar to XPath. Beginning from the Body object
* @param value The constraint value
* @return itself to allow chaining.
*/
public QueryService setBodyCriteria(String ldpath, String value) {
return setBodyCriteria(ldpath, value, Comparison.EQ);
}
/**
* Setting a criteria for filtering eu.mico.platform.persistence.impl.BodyImpl.* objects. Compared to the
* other <i>setBodyCriteria</i> function, this function does not need a <b>Comparison</b> statement. Hence,
* the Comparison.EQ statement ("=") will be used automatically.
*
* @param ldpath Syntax similar to XPath. Beginning from the Body object
* @param value The constraint value
* @return itself to allow chaining.
*/
public QueryService setBodyCriteria(String ldpath, Number value) {
return setBodyCriteria(ldpath, value, Comparison.EQ);
}
/**
* Setting a criteria for filtering eu.mico.platform.persistence.impl.BodyImpl.* objects.
*
* @param ldpath Syntax similar to XPath. Beginning from the Body object
* @return itself to allow chaining.
*/
public QueryService setBodyCriteria(String ldpath) {
criteria.add(new Criteria(BODY_PREFIX + ldpath, Comparison.EQ));
return this;
}
/**
* Setting a criteria for filtering eu.mico.platform.persistence.impl.AnnotationImpl objects.
*
* @param ldpath Syntax similar to XPath. Beginning from the Annotation object
* @param comparison The comparison mode, e.g. Comparison.EQ (=)
* @param value The constraint value
* @return itself to allow chaining.
*/
public QueryService setAnnotationCriteria(String ldpath, String value, Comparison comparison) {
criteria.add(new Criteria(ldpath, value, comparison));
return this;
}
/**
* Setting a criteria for filtering eu.mico.platform.persistence.impl.AnnotationImpl objects.
*
* @param ldpath Syntax similar to XPath. Beginning from the Annotation object
* @param comparison The comparison mode, e.g. Comparison.EQ (=)
* @param value The constraint value
* @return itself to allow chaining.
*/
public QueryService setAnnotationCriteria(String ldpath, Number value, Comparison comparison) {
criteria.add(new Criteria(ldpath, value, comparison));
return this;
}
/**
* Setting a criteria for filtering eu.mico.platform.persistence.impl.AnnotationImpl objects. Compared to the
* other <i>setAnnotationCriteria</i> function, this function does not need a Comparison statement. Hence, the
* <b>Comparison.EQ</b> statement ("=") will be used automatically.
*
* @param ldpath Syntax similar to XPath. Beginning from the Annotation object
* @param value The constraint value
* @return itself to allow chaining.
*/
public QueryService setAnnotationCriteria(String ldpath, String value) {
return setAnnotationCriteria(ldpath, value, Comparison.EQ);
}
/**
* Setting a criteria for filtering eu.mico.platform.persistence.impl.AnnotationImpl objects. Compared to the
* other <i>setAnnotationCriteria</i> function, this function does not need a Comparison statement. Hence, the
* <b>Comparison.EQ</b> statement ("=") will be used automatically.
*
* @param ldpath Syntax similar to XPath. Beginning from the Annotation object
* @param value The constraint value
* @return itself to allow chaining.
*/
public QueryService setAnnotationCriteria(String ldpath, Number value) {
return setAnnotationCriteria(ldpath, value, Comparison.EQ);
}
/**
* Setting a criteria for filtering eu.mico.platform.persistence.impl.AnnotationImpl objects.
*
* @param ldpath Syntax similar to XPath. Beginning from the Annotation object
* @return itself to allow chaining.
*/
public QueryService setAnnotationCriteria(String ldpath) {
criteria.add(new Criteria(ldpath, Comparison.EQ));
return this;
}
/**
* Setting a criteria for filtering eu.mico.platform.persistence.impl.SelectorImpl.* objects.
*
* @param ldpath Syntax similar to XPath. Beginning from the Selector object
* @param comparison The comparison mode, e.g. Comparison.EQ (=)
* @param value The constraint value
* @return itself to allow chaining.
*/
public QueryService setSelectorCriteria(String ldpath, String value, Comparison comparison) {
criteria.add(new Criteria(SELECTOR_PREFIX + ldpath, value, comparison));
return this;
}
/**
* Setting a criteria for filtering eu.mico.platform.persistence.impl.SelectorImpl.* objects.
*
* @param ldpath Syntax similar to XPath. Beginning from the Selector object
* @param comparison The comparison mode, e.g. Comparison.EQ (=)
* @param value The constraint value
* @return itself to allow chaining.
*/
public QueryService setSelectorCriteria(String ldpath, Number value, Comparison comparison) {
criteria.add(new Criteria(SELECTOR_PREFIX + ldpath, value, comparison));
return this;
}
/**
* Setting a criteria for filtering eu.mico.platform.persistence.impl.SelectorImpl.* objects. Compared to the
* other <i>setSelectorCriteria</i> function, this function does not need a Comparison statement. Hence, the
* <b>Comparison.EQ</b> statement ("=") will be used automatically.
*
* @param ldpath Syntax similar to XPath. Beginning from the Selector object
* @param value The constraint value
* @return itself to allow chaining.
*/
public QueryService setSelectorCriteria(String ldpath, String value) {
return setSelectorCriteria(ldpath, value, Comparison.EQ);
}
/**
* Setting a criteria for filtering eu.mico.platform.persistence.impl.SelectorImpl.* objects. Compared to the
* other <i>setSelectorCriteria</i> function, this function does not need a Comparison statement. Hence, the
* <b>Comparison.EQ</b> statement ("=") will be used automatically.
*
* @param ldpath Syntax similar to XPath. Beginning from the Selector object
* @param value The constraint value
* @return itself to allow chaining.
*/
public QueryService setSelectorCriteria(String ldpath, Number value) {
return setSelectorCriteria(ldpath, value, Comparison.EQ);
}
/**
* Setting a criteria for filtering eu.mico.platform.persistence.impl.SelectorImpl.* objects.
*
* @param ldpath Syntax similar to XPath. Beginning from the Selector object
* @return itself to allow chaining.
*/
public QueryService setSelectorCriteria(String ldpath) {
criteria.add(new Criteria(SELECTOR_PREFIX + ldpath, Comparison.EQ));
return this;
}
/**
* @param ldpath Syntax similar to XPath. Beginning from the Source object
* @param value The constraint value
* @param comparison The comparison mode, e.g. Comparison.EQ (=)
* @return itself to allow chaining.
*/
public QueryService setSourceCriteria(String ldpath, String value, Comparison comparison) {
criteria.add(new Criteria(SOURCE_PREFIX + ldpath, value, comparison));
return this;
}
/**
* @param ldpath Syntax similar to XPath. Beginning from the Source object
* @param value The constraint value
* @param comparison The comparison mode, e.g. Comparison.EQ (=)
* @return itself to allow chaining.
*/
public QueryService setSourceCriteria(String ldpath, Number value, Comparison comparison) {
criteria.add(new Criteria(SOURCE_PREFIX + ldpath, value, comparison));
return this;
}
/**
* @param ldpath Syntax similar to XPath. Beginning from the Source object
* @param value The constraint value
* @return itself to allow chaining.
*/
public QueryService setSourceCriteria(String ldpath, String value) {
return setSourceCriteria(ldpath, value, Comparison.EQ);
}
/**
* @param ldpath Syntax similar to XPath. Beginning from the Source object
* @param value The constraint value
* @return itself to allow chaining.
*/
public QueryService setSourceCriteria(String ldpath, Number value) {
return setSourceCriteria(ldpath, value, Comparison.EQ);
}
/**
* @param ldpath Syntax similar to XPath. Beginning from the Source object
* @return itself to allow chaining.
*/
public QueryService setSourceCriteria(String ldpath) {
criteria.add(new Criteria(SOURCE_PREFIX + ldpath, Comparison.EQ));
return this;
}
/**
* Setting shortcut names for URI prefixes.
*
* @param label The label of the namespace, e.g. foaf
* @param url The URL
* @return itself to allow chaining.
*/
public QueryService addPrefix(String label, String url) {
this.prefixes.put(label, url);
return this;
}
/**
* Setting multiple names for URI prefixes.
*
* @param prefixes HashMap with multiple namespaces.
* @return itself to allow chaining.
*/
public QueryService addPrefixes(HashMap<String, String> prefixes) {
this.prefixes.putAll(prefixes);
return this;
}
/**
* Defines the ordering of the result set.
*
* @param order Defines the order of the result set.
* @return itself to allow chaining.
*/
public QueryService orderBy(Order order) {
this.order = order;
return this;
}
/**
* Setting the limit value.
*
* @param limit The limit value.
* @return itself to allow chaining.
*/
public QueryService limit(Integer limit) {
this.limit = limit;
return this;
}
/**
* Setting the offset value.
*
* @param offset The offset value.
* @return itself to allow chaining.
*/
public QueryService offset(Integer offset) {
this.offset = offset;
return this;
}
/**
* Creates and executes the SPARQL query according to the
* criteria specified by the user.
*
* @param <T>
* @return the result set
*/
public <T> List<T> execute() throws ParseException, RepositoryException, MalformedQueryException, QueryEvaluationException {
ObjectConnection con = objectRepository.getConnection();
String sparql = EvalQuery.evaluate(criteria, prefixes);
logger.info("Created query:\n" + prettyPrint(sparql));
ObjectQuery query = con.prepareObjectQuery(sparql);
return (List<T>) query.evaluate(this.type).asList();
}
/**
* Reformats the SPARQL query for logging purpose
*
* @param sparql The generated SPARQL query
*
* @return Formatted query
*/
public String prettyPrint(String sparql) {
return OpAsQuery.asQuery(Algebra.compile(QueryFactory.create(sparql))).serialize();
}
}
|
package org.burroloco.butcher.fixture.http;
import au.net.netstorm.boost.bullet.primordial.Primordial;
import java.util.HashMap;
import java.util.Map;
public final class HttpRequest extends Primordial {
Map<String, String> params = new HashMap<String, String>();
String payload;
public HttpRequest(Map<String, String> params, String payload) {
this.params = params;
this.payload = payload;
}
public Map<String, String> getParams() {
return params;
}
public String getPayload() {
return payload;
}
}
|
package com.github.ansell.csv.sum;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.stream.Stream;
import org.apache.commons.io.output.NullWriter;
import com.fasterxml.jackson.databind.SequenceWriter;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;
import com.github.ansell.csv.stream.CSVStream;
import com.github.ansell.csv.stream.CSVStreamException;
import com.github.ansell.csv.util.ValueMapping;
import com.github.ansell.jdefaultdict.JDefaultDict;
import joptsimple.OptionException;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
/**
* Summarises CSV files to easily debug and identify likely parse issues before
* pushing them through a more heavy tool or process.
*
* @author Peter Ansell p_ansell@yahoo.com
*/
public final class CSVSummariser {
/**
* The default number of samples to include for each field in the summarised
* CSV.
*/
public static final int DEFAULT_SAMPLE_COUNT = 20;
/**
* Private constructor for static only class
*/
private CSVSummariser() {
}
public static void main(String... args) throws Exception {
final OptionParser parser = new OptionParser();
final OptionSpec<Void> help = parser.accepts("help").forHelp();
final OptionSpec<File> input = parser.accepts("input").withRequiredArg().ofType(File.class).required()
.describedAs("The input CSV file to be summarised.");
final OptionSpec<File> overrideHeadersFile = parser.accepts("override-headers-file").withRequiredArg()
.ofType(File.class).describedAs(
"A file whose first line contains the headers to use, to override those found in the file.");
final OptionSpec<Integer> headerLineCount = parser.accepts("header-line-count").withRequiredArg()
.ofType(Integer.class)
.describedAs(
"The number of header lines present in the file. Can be used in conjunction with override-headers-file to substitute a different set of headers")
.defaultsTo(1);
final OptionSpec<File> output = parser.accepts("output").withRequiredArg().ofType(File.class)
.describedAs("The output file, or the console if not specified.");
final OptionSpec<File> outputMappingTemplate = parser.accepts("output-mapping").withRequiredArg()
.ofType(File.class).describedAs("The output mapping template file if it needs to be generated.");
final OptionSpec<Integer> samplesToShow = parser.accepts("samples").withRequiredArg().ofType(Integer.class)
.defaultsTo(DEFAULT_SAMPLE_COUNT).describedAs(
"The maximum number of sample values for each field to include in the output, or -1 to dump all sample values for each field.");
final OptionSpec<Boolean> showSampleCounts = parser.accepts("show-sample-counts").withRequiredArg()
.ofType(Boolean.class).defaultsTo(Boolean.FALSE)
.describedAs("Set to true to add counts for each of the samples shown after the sample display value.");
final OptionSpec<Boolean> debug = parser.accepts("debug").withRequiredArg().ofType(Boolean.class)
.defaultsTo(Boolean.FALSE).describedAs("Set to true to debug.");
OptionSet options = null;
try {
options = parser.parse(args);
} catch (final OptionException e) {
System.out.println(e.getMessage());
parser.printHelpOn(System.out);
throw e;
}
if (options.has(help)) {
parser.printHelpOn(System.out);
return;
}
final Path inputPath = input.value(options).toPath();
if (!Files.exists(inputPath)) {
throw new FileNotFoundException("Could not find input CSV file: " + inputPath.toString());
}
final Path outputMappingPath = options.has(outputMappingTemplate)
? outputMappingTemplate.value(options).toPath() : null;
if (options.has(outputMappingTemplate) && Files.exists(outputMappingPath)) {
throw new FileNotFoundException(
"Output mapping template file already exists: " + outputMappingPath.toString());
}
final Writer writer;
if (options.has(output)) {
writer = Files.newBufferedWriter(output.value(options).toPath());
} else {
writer = new BufferedWriter(new OutputStreamWriter(System.out));
}
int samplesToShowInt = samplesToShow.value(options);
int headerLineCountInt = headerLineCount.value(options);
boolean debugBoolean = debug.value(options);
// Defaults to null, with any strings in the file overriding that
AtomicReference<List<String>> overrideHeadersList = new AtomicReference<>();
if (options.has(overrideHeadersFile)) {
try (final BufferedReader newBufferedReader = Files
.newBufferedReader(overrideHeadersFile.value(options).toPath());) {
CSVStream.parse(newBufferedReader, h -> {
overrideHeadersList.set(h);
}, (h, l) -> {
return l;
}, l -> {
}, null, CSVStream.DEFAULT_HEADER_COUNT);
}
}
if (debugBoolean) {
System.out.println("Running summarise on: " + inputPath + " samples=" + samplesToShowInt);
}
try (final BufferedReader newBufferedReader = Files.newBufferedReader(inputPath);
final Writer mappingWriter = options.has(outputMappingTemplate)
? Files.newBufferedWriter(outputMappingPath) : NullWriter.NULL_WRITER) {
runSummarise(newBufferedReader, writer, mappingWriter, samplesToShowInt, showSampleCounts.value(options),
debugBoolean, overrideHeadersList.get(), headerLineCountInt);
}
}
/**
* Summarise the CSV file from the input {@link Reader} and emit the summary
* CSV file to the output {@link Writer}, including the given maximum number
* of sample values in the summary for each field.
*
* @param input
* The input CSV file, as a {@link Reader}.
* @param output
* The output CSV file as a {@link Writer}.
* @param mappingOutput
* The output mapping template file as a {@link Writer}.
* @param maxSampleCount
* The maximum number of sample values in the summary for each
* field. Set to -1 to include all unique values for each field.
* @param showSampleCounts
* Show counts next to sample values
* @param debug
* Set to true to add debug statements.
* @throws IOException
* If there is an error reading or writing.
*/
public static void runSummarise(Reader input, Writer output, Writer mappingOutput, int maxSampleCount,
boolean showSampleCounts, boolean debug) throws IOException {
runSummarise(input, output, mappingOutput, maxSampleCount, showSampleCounts, debug, null,
CSVStream.DEFAULT_HEADER_COUNT);
}
public static void runSummarise(final Reader input, final Writer output, final Writer mappingOutput,
final int maxSampleCount, final boolean showSampleCounts, final boolean debug,
final List<String> overrideHeaders, final int headerLineCount) throws IOException {
final CsvMapper inputMapper = CSVStream.defaultMapper();
final CsvSchema inputSchema = CSVStream.defaultSchema();
runSummarise(input, inputMapper, inputSchema, output, mappingOutput, maxSampleCount, showSampleCounts, debug,
overrideHeaders, headerLineCount);
}
public static void runSummarise(final Reader input, final CsvMapper inputMapper, final CsvSchema inputSchema,
final Writer output, final Writer mappingOutput, final int maxSampleCount, final boolean showSampleCounts,
final boolean debug, final List<String> overrideHeaders, final int headerLineCount) throws IOException {
runSummarise(input, inputMapper, inputSchema, output, mappingOutput, maxSampleCount, showSampleCounts, debug,
overrideHeaders, Collections.emptyList(), headerLineCount);
}
public static void runSummarise(final Reader input, final CsvMapper inputMapper, final CsvSchema inputSchema,
final Writer output, final Writer mappingOutput, final int maxSampleCount, final boolean showSampleCounts,
final boolean debug, final List<String> overrideHeaders, final List<String> defaultValues,
final int headerLineCount) throws IOException {
final JDefaultDict<String, AtomicInteger> emptyCounts = new JDefaultDict<>(k -> new AtomicInteger());
final JDefaultDict<String, AtomicInteger> nonEmptyCounts = new JDefaultDict<>(k -> new AtomicInteger());
// Default to true, and set to false if a non-integer is detected. The
// special case of no values being found is handled in the write method
// and false is used
final JDefaultDict<String, AtomicBoolean> possibleIntegerFields = new JDefaultDict<>(
k -> new AtomicBoolean(true));
// Default to true, and set to false if a non-double is detected. The
// special case of no values being found is handled in the write method
// and false is used
final JDefaultDict<String, AtomicBoolean> possibleDoubleFields = new JDefaultDict<>(
k -> new AtomicBoolean(true));
final JDefaultDict<String, JDefaultDict<String, AtomicInteger>> valueCounts = new JDefaultDict<String, JDefaultDict<String, AtomicInteger>>(
k -> new JDefaultDict<>(l -> new AtomicInteger()));
final AtomicInteger rowCount = new AtomicInteger();
final List<String> headers = parseForSummarise(input, inputMapper, inputSchema, emptyCounts, nonEmptyCounts,
possibleIntegerFields, possibleDoubleFields, valueCounts, rowCount, overrideHeaders, headerLineCount);
writeForSummarise(maxSampleCount, emptyCounts, nonEmptyCounts, possibleIntegerFields, possibleDoubleFields,
valueCounts, headers, rowCount, showSampleCounts, output, mappingOutput);
}
/**
* Writes summary values and a stub mapping file based on the given
* {@link JDefaultDict}s.
*
* @param maxSampleCount
* The maximum number of samples to write out
* @param emptyCounts
* A {@link JDefaultDict} containing the empty counts for each
* field
* @param nonEmptyCounts
* A {@link JDefaultDict} containing the non-empty counts for
* each field
* @param possibleIntegerFields
* A {@link JDefaultDict} containing true if the field is
* possibly integer and false otherwise
* @param possibleDoubleFields
* A {@link JDefaultDict} containing true if the field is
* possibly double and false otherwise
* @param valueCounts
* A {@link JDefaultDict} containing values for each field and
* attached counts
* @param headers
* The headers that were either given or substituted
* @param rowCount
* The total row count from the input file, used to determine if
* the number of unique values matches the total number of rows
* @param showSampleCounts
* True to attach sample counts to the sample output, and false
* to omit it
* @param output
* The {@link Writer} to contain the summarised statistics
* @param mappingOutput
* The {@link Writer} to contain the stub mapping file
* @throws IOException
* If there is an error writing
*/
private static void writeForSummarise(final int maxSampleCount,
final JDefaultDict<String, AtomicInteger> emptyCounts,
final JDefaultDict<String, AtomicInteger> nonEmptyCounts,
final JDefaultDict<String, AtomicBoolean> possibleIntegerFields,
final JDefaultDict<String, AtomicBoolean> possibleDoubleFields,
final JDefaultDict<String, JDefaultDict<String, AtomicInteger>> valueCounts, final List<String> headers,
final AtomicInteger rowCount, final boolean showSampleCounts, final Writer output,
final Writer mappingOutput) throws IOException {
// This schema defines the fields and order for the columns in the
// summary CSV file
final CsvSchema summarySchema = getSummaryCsvSchema();
final CsvSchema mappingSchema = getMappingCsvSchema();
// Shared StringBuilder across fields for efficiency
// After each field the StringBuilder is truncated
final StringBuilder sampleValue = new StringBuilder();
final BiConsumer<? super String, ? super String> sampleHandler = (s, c) -> {
if (sampleValue.length() > 0) {
sampleValue.append(", ");
}
if (s.length() > 200) {
sampleValue.append(s.substring(0, 200));
sampleValue.append("...");
} else {
sampleValue.append(s);
}
if (showSampleCounts) {
sampleValue.append("(*" + c + ")");
}
};
try (final SequenceWriter csvWriter = CSVStream.newCSVWriter(output, summarySchema);
final SequenceWriter mappingWriter = CSVStream.newCSVWriter(mappingOutput, mappingSchema);) {
// Need to do this to get the header line written out in this case
if (rowCount.get() == 0) {
csvWriter.write(Arrays.asList());
mappingWriter.write(Arrays.asList());
}
headers.forEach(h -> {
try {
final int emptyCount = emptyCounts.get(h).get();
final int nonEmptyCount = nonEmptyCounts.get(h).get();
JDefaultDict<String, AtomicInteger> nextValueCount = valueCounts.get(h);
final int valueCount = nextValueCount.keySet().size();
final boolean possiblePrimaryKey = valueCount == nonEmptyCount && valueCount == rowCount.get();
boolean possiblyInteger = false;
boolean possiblyDouble = false;
// Only expose our numeric type guess if non-empty values
// found
// This is important, as it may default to true unless
// evidence to the contrary is found
if (nonEmptyCount > 0) {
possiblyInteger = possibleIntegerFields.get(h).get();
possiblyDouble = possibleDoubleFields.get(h).get();
}
final Stream<String> stream = nextValueCount.keySet().stream();
if (maxSampleCount > 0) {
stream.limit(maxSampleCount).sorted()
.forEach(s -> sampleHandler.accept(s, nextValueCount.get(s).toString()));
if (valueCount > maxSampleCount) {
sampleValue.append(", ...");
}
} else if (maxSampleCount < 0) {
stream.sorted().forEach(s -> sampleHandler.accept(s, nextValueCount.get(s).toString()));
}
csvWriter.write(Arrays.asList(h, emptyCount, nonEmptyCount, valueCount, possiblePrimaryKey,
possiblyInteger, possiblyDouble, sampleValue));
final String mappingFieldType = possiblyInteger ? "INTEGER" : possiblyDouble ? "DECIMAL" : "TEXT";
mappingWriter.write(Arrays.asList(h, h, "", ValueMapping.ValueMappingLanguage.DBSCHEMA.name(),
mappingFieldType));
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
// Very important to reset this shared StringBuilder after
// each row is written
sampleValue.setLength(0);
}
});
}
}
/**
* Parse the given inputs to in-memory maps to allow for summarisation.
*
* @param input
* The {@link Reader} containing the inputs to be summarised.
* @param inputMapper
* The CsvMapper to use to parse the file into memory
* @param inputSchema
* The CsvSchema to use to help the mapper parse the file into
* memory
* @param emptyCounts
* A {@link JDefaultDict} to be populated with empty counts for
* each field
* @param nonEmptyCounts
* A {@link JDefaultDict} to be populated with non-empty counts
* for each field
* @param possibleIntegerFields
* A {@link JDefaultDict} to be populated with false if a
* non-integer value is detected in a field
* @param possibleDoubleFields
* A {@link JDefaultDict} to be populated with false if a
* non-double value is detected in a field
* @param valueCounts
* A {@link JDefaultDict} to be populated with false if a
* non-integer value is detected in a field
* @param rowCount
* An {@link AtomicInteger} used to track the total number of
* rows processed.
* @param overrideHeaders
* Headers to use to override those in the file, or null to rely
* on the headers from the file
* @param headerLineCount
* The number of lines in the file that must be skipped, or 0 to
* not skip any headers and instead use overrideHeaders
* @return The list of headers that were either overridden or found in the
* file
* @throws IOException
* If there is an error reading from the file
* @throws CSVStreamException
* If there is a problem processing the CSV content
*/
private static List<String> parseForSummarise(final Reader input, final CsvMapper inputMapper,
final CsvSchema inputSchema, final JDefaultDict<String, AtomicInteger> emptyCounts,
final JDefaultDict<String, AtomicInteger> nonEmptyCounts,
final JDefaultDict<String, AtomicBoolean> possibleIntegerFields,
final JDefaultDict<String, AtomicBoolean> possibleDoubleFields,
final JDefaultDict<String, JDefaultDict<String, AtomicInteger>> valueCounts, final AtomicInteger rowCount,
final List<String> overrideHeaders, final int headerLineCount) throws IOException, CSVStreamException {
final long startTime = System.currentTimeMillis();
final List<String> headers = new ArrayList<>();
CSVStream.parse(input, h -> headers.addAll(h), (h, l) -> {
int nextLineNumber = rowCount.incrementAndGet();
if (nextLineNumber % 10000 == 0) {
double secondsSinceStart = (System.currentTimeMillis() - startTime) / 1000.0d;
System.out.printf("%d\tSeconds since start: %f\tRecords per second: %f%n", nextLineNumber,
secondsSinceStart, nextLineNumber / secondsSinceStart);
}
for (int i = 0; i < h.size(); i++) {
if (l.get(i).trim().isEmpty()) {
emptyCounts.get(h.get(i)).incrementAndGet();
} else {
nonEmptyCounts.get(h.get(i)).incrementAndGet();
valueCounts.get(h.get(i)).get(l.get(i)).incrementAndGet();
try {
Integer.parseInt(l.get(i));
} catch (NumberFormatException nfe) {
possibleIntegerFields.get(h.get(i)).set(false);
}
try {
Double.parseDouble(l.get(i));
} catch (NumberFormatException nfe) {
possibleDoubleFields.get(h.get(i)).set(false);
}
}
}
return l;
}, l -> {
// We are a streaming summariser, and do not store the raw original
// lines. Only unique, non-empty, values are stored in the
// valueCounts map for uniqueness summaries
}, overrideHeaders, headerLineCount, inputMapper, inputSchema);
return headers;
}
/**
* @return A {@link CsvSchema} representing the fields in the summary
* results file
*/
private static CsvSchema getSummaryCsvSchema() {
final CsvSchema summarySchema = CsvSchema.builder().addColumn("fieldName")
.addColumn("emptyCount", CsvSchema.ColumnType.NUMBER)
.addColumn("nonEmptyCount", CsvSchema.ColumnType.NUMBER)
.addColumn("uniqueValueCount", CsvSchema.ColumnType.NUMBER)
.addColumn("possiblePrimaryKey", CsvSchema.ColumnType.BOOLEAN)
.addColumn("possiblyInteger", CsvSchema.ColumnType.BOOLEAN)
.addColumn("possiblyFloatingPoint", CsvSchema.ColumnType.BOOLEAN).addColumn("sampleValues")
.setUseHeader(true).build();
return summarySchema;
}
/**
* @return A {@link CsvSchema} representing the fields in the mapping file
*/
private static CsvSchema getMappingCsvSchema() {
final CsvSchema mappingSchema = CsvSchema.builder()
.addColumn(ValueMapping.OLD_FIELD, CsvSchema.ColumnType.STRING)
.addColumn(ValueMapping.NEW_FIELD, CsvSchema.ColumnType.STRING)
.addColumn(ValueMapping.SHOWN, CsvSchema.ColumnType.STRING)
.addColumn(ValueMapping.LANGUAGE, CsvSchema.ColumnType.STRING)
.addColumn(ValueMapping.MAPPING, CsvSchema.ColumnType.STRING).setUseHeader(true).build();
return mappingSchema;
}
}
|
package com.github.ansell.csv.util;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import javax.script.Bindings;
import javax.script.Compilable;
import javax.script.CompiledScript;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import com.github.ansell.csv.stream.CSVStream;
import com.github.ansell.jdefaultdict.JDefaultDict;
/**
* A mapping definition from an original CSV field to an output CSV field.
*
* @author Peter Ansell p_ansell@yahoo.com
*/
public class ValueMapping {
private static final String NO = "no";
/**
* The default mapping if none is specified in the mapping file.
*/
protected static final String DEFAULT_MAPPING = "inputValue";
public enum ValueMappingLanguage {
DEFAULT(ValueMapping.DEFAULT_MAPPING),
JAVASCRIPT("return inputValue;"),
GROOVY("inputValue"),
LUA("return inputValue"),
ACCESS(""),
CSVJOIN(""),
DBSCHEMA(""),
;
private final String defaultMapping;
ValueMappingLanguage(String defaultMapping) {
this.defaultMapping = defaultMapping;
}
public String getDefaultMapping() {
return this.defaultMapping;
}
public boolean matchesDefaultMapping(String mapping) {
return this.getDefaultMapping().equals(mapping);
}
}
public static final String OLD_FIELD = "OldField";
public static final String NEW_FIELD = "NewField";
public static final String SHOWN = "Shown";
public static final String LANGUAGE = "Language";
public static final String MAPPING = "Mapping";
private static final ScriptEngineManager SCRIPT_MANAGER = new ScriptEngineManager();
private static final boolean DEBUG = false;
static {
if (DEBUG) {
System.out.println("Installed script engines:");
SCRIPT_MANAGER.getEngineFactories().stream().map(ScriptEngineFactory::getEngineName)
.forEach(System.out::println);
}
}
public static List<ValueMapping> extractMappings(Reader input) throws IOException {
List<ValueMapping> result = new ArrayList<>();
CSVStream.parse(input, h -> {
}, (h, l) -> {
return newMapping(l.get(h.indexOf(LANGUAGE)), l.get(h.indexOf(OLD_FIELD)), l.get(h.indexOf(NEW_FIELD)),
l.get(h.indexOf(MAPPING)), l.get(h.indexOf(SHOWN)));
}, l -> result.add(l));
return result;
}
public static List<String> mapLine(List<String> inputHeaders, List<String> line, List<String> previousLine,
List<String> previousMappedLine, List<ValueMapping> map, JDefaultDict<String, Set<String>> primaryKeys,
int lineNumber, int filteredLineNumber, BiConsumer<List<String>, List<String>> mapLineConsumer)
throws LineFilteredException {
HashMap<String, String> outputValues = new HashMap<>(map.size(), 0.75f);
List<String> outputHeaders = map.stream().filter(k -> k.getShown()).map(k -> k.getOutputField())
.collect(Collectors.toList());
map.forEach(nextMapping -> {
String mappedValue = nextMapping.apply(inputHeaders, line, previousLine, previousMappedLine, outputHeaders,
outputValues, primaryKeys, lineNumber, filteredLineNumber, mapLineConsumer);
outputValues.put(nextMapping.getOutputField(), mappedValue);
});
List<String> result = new ArrayList<>(outputHeaders.size());
outputHeaders.forEach(nextOutput -> result.add(outputValues.getOrDefault(nextOutput, "")));
outputValues.clear();
return result;
}
public static final ValueMapping newMapping(String language, String input, String output, String mapping,
String shownString) {
if (output == null || output.isEmpty()) {
throw new IllegalArgumentException("Output field must not be empty");
}
ValueMappingLanguage nextLanguage;
try {
nextLanguage = ValueMappingLanguage.valueOf(language.toUpperCase());
} catch (IllegalArgumentException e) {
nextLanguage = ValueMappingLanguage.DEFAULT;
}
String nextMapping;
// By default empty mappings do not change the input, and are
// efficiently dealt with as such
if (!mapping.isEmpty()) {
nextMapping = mapping;
} else {
nextMapping = nextLanguage.getDefaultMapping();
}
boolean shown = !NO.equalsIgnoreCase(shownString);
ValueMapping result = new ValueMapping(nextLanguage, input, output, nextMapping, shown);
result.init();
return result;
}
private final ValueMappingLanguage language;
private final String input;
private final String output;
private final String mapping;
private final boolean shown;
private final String[] destFields;
private final String[] sourceFields;
private transient ScriptEngine scriptEngine;
private transient CompiledScript compiledScript;
/**
* All creation of ValueMapping objects must be done through the
* {@link #newMapping(String, String, String, String)} method.
*/
private ValueMapping(ValueMappingLanguage language, String input, String output, String mapping, boolean shown) {
this.language = language;
this.input = input.intern();
this.output = output.intern();
this.mapping = mapping.intern();
this.shown = shown;
this.destFields = CSVUtil.COMMA_PATTERN.split(this.mapping);
this.sourceFields = CSVUtil.COMMA_PATTERN.split(this.input);
}
private String apply(List<String> inputHeaders, List<String> line, List<String> previousLine,
List<String> previousMappedLine, List<String> outputHeaders, Map<String, String> mappedLine,
JDefaultDict<String, Set<String>> primaryKeys, int lineNumber, int filteredLineNumber,
BiConsumer<List<String>, List<String>> mapLineConsumer) {
int indexOf = inputHeaders.indexOf(getInputField());
String nextInputValue;
if (indexOf >= 0) {
nextInputValue = line.get(indexOf);
} else {
// Provide a default input value for these cases. Likely the input
// field in this case was a set of fields and won't be directly
// relied upon
nextInputValue = "";
}
// Short circuit if the mapping is a default mapping
if (this.language == ValueMappingLanguage.DEFAULT || this.language.matchesDefaultMapping(this.mapping)) {
return nextInputValue;
}
if (this.language == ValueMappingLanguage.JAVASCRIPT || this.language == ValueMappingLanguage.GROOVY
|| this.language == ValueMappingLanguage.LUA) {
try {
if (scriptEngine instanceof Invocable) {
// evaluate script code and access the variable that results
// from the mapping
return (String) ((Invocable) scriptEngine).invokeFunction("mapFunction", inputHeaders,
this.getInputField(), nextInputValue, outputHeaders, this.getOutputField(), line,
mappedLine, previousLine, previousMappedLine, primaryKeys, lineNumber, filteredLineNumber,
mapLineConsumer);
} else if (compiledScript != null) {
Bindings bindings = scriptEngine.createBindings();
// inputHeaders, inputField, inputValue, outputField, line
bindings.put("inputHeaders", inputHeaders);
bindings.put("inputField", this.getInputField());
bindings.put("inputValue", nextInputValue);
bindings.put("outputHeaders", outputHeaders);
bindings.put("outputField", this.getOutputField());
bindings.put("line", line);
bindings.put("mapLine", mappedLine);
bindings.put("previousLine", previousLine);
bindings.put("previousMappedLine", previousMappedLine);
bindings.put("primaryKeys", primaryKeys);
bindings.put("lineNumber", lineNumber);
bindings.put("filteredLineNumber", filteredLineNumber);
bindings.put("mapLineConsumer", mapLineConsumer);
return (String) compiledScript.eval(bindings);
} else {
throw new UnsupportedOperationException(
"Cannot handle results from ScriptEngine.eval that are not Invocable or CompiledScript");
}
} catch (ScriptException e) {
if (e.getCause() != null) {
if (e.getCause().getMessage().contains(LineFilteredException.class.getCanonicalName())) {
throw new LineFilteredException(e);
}
}
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
} else if (this.language == ValueMappingLanguage.ACCESS) {
// Access is currently handled separately, before these mappings are
// applied, so make this a noop
return nextInputValue;
} else if (this.language == ValueMappingLanguage.CSVJOIN) {
// CSVJoin is currently handled separately, before these mappings
// are applied, so make this a noop
return nextInputValue;
} else {
throw new UnsupportedOperationException("Mapping language not supported: " + this.language);
}
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof ValueMapping)) {
return false;
}
ValueMapping other = (ValueMapping) obj;
if (input == null) {
if (other.input != null) {
return false;
}
} else if (!input.equals(other.input)) {
return false;
}
if (language != other.language) {
return false;
}
if (mapping == null) {
if (other.mapping != null) {
return false;
}
} else if (!mapping.equals(other.mapping)) {
return false;
}
if (output == null) {
if (other.output != null) {
return false;
}
} else if (!output.equals(other.output)) {
return false;
}
if (shown != other.shown) {
return false;
}
return true;
}
public String getInputField() {
return this.input;
}
public ValueMappingLanguage getLanguage() {
return this.language;
}
public String getMapping() {
return this.mapping;
}
public String getOutputField() {
return this.output;
}
public boolean getShown() {
return this.shown;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((input == null) ? 0 : input.hashCode());
result = prime * result + ((language == null) ? 0 : language.hashCode());
result = prime * result + ((mapping == null) ? 0 : mapping.hashCode());
result = prime * result + ((output == null) ? 0 : output.hashCode());
result = prime * result + (shown ? 1231 : 1237);
return result;
}
private void init() {
// Short circuit if the mapping is the default mapping and avoid
// creating an instance of nashorn/groovy/etc. for this mapping
if (this.language == ValueMappingLanguage.DEFAULT || this.language.matchesDefaultMapping(this.mapping)) {
return;
}
// precompile the function for this mapping for efficiency
if (this.language == ValueMappingLanguage.JAVASCRIPT) {
try {
scriptEngine = SCRIPT_MANAGER.getEngineByName("javascript");
StringBuilder javascriptFunction = new StringBuilder();
javascriptFunction
.append("var LFE = Java.type(\"com.github.ansell.csv.util.LineFilteredException\"); \n");
javascriptFunction.append("var Integer = Java.type('java.lang.Integer'); \n");
javascriptFunction.append("var Double = Java.type('java.lang.Double'); \n");
javascriptFunction.append("var Long = Java.type('java.lang.Long'); \n");
javascriptFunction.append("var LocalDate = Java.type('java.time.LocalDate'); \n");
javascriptFunction.append("var LocalDateTime = Java.type('java.time.LocalDateTime'); \n");
javascriptFunction.append("var LocalTime = Java.type('java.time.LocalTime'); \n");
javascriptFunction.append("var TimeUnit = Java.type('java.util.concurrent.TimeUnit'); \n");
javascriptFunction.append("var Locale = Java.type('java.util.Locale'); \n");
javascriptFunction.append("var Format = Java.type('java.time.format.DateTimeFormatter'); \n");
javascriptFunction.append(
"var DateTimeFormatterBuilder = Java.type('java.time.format.DateTimeFormatterBuilder'); \n");
javascriptFunction.append("var ChronoUnit = Java.type('java.time.temporal.ChronoUnit'); \n");
javascriptFunction.append("var Math = Java.type('java.lang.Math'); \n");
javascriptFunction.append("var String = Java.type('java.lang.String'); \n");
javascriptFunction.append("var MessageDigest = Java.type('java.security.MessageDigest'); \n");
javascriptFunction.append("var BigInteger = Java.type('java.math.BigInteger'); \n");
javascriptFunction.append("var Arrays = Java.type('java.util.Arrays'); \n");
javascriptFunction.append("var UTM = Java.type('com.github.ansell.shp.UTM'); \n");
javascriptFunction.append("var WGS84 = Java.type('com.github.ansell.shp.WGS84'); \n");
javascriptFunction.append("var JSONUtil = Java.type('com.github.ansell.csv.util.JSONUtil'); \n");
javascriptFunction.append("var Paths = Java.type('java.nio.file.Paths'); \n");
javascriptFunction.append("var JsonPointer = Java.type('com.fasterxml.jackson.core.JsonPointer'); \n");
javascriptFunction.append("var Thread = Java.type('java.lang.Thread'); \n");
javascriptFunction.append("var sleep = function(sleepTime) { Thread.sleep(sleepTime); }; \n");
javascriptFunction.append(
"var digest = function(value, algorithm, formatPattern) { if(!algorithm) { algorithm = \"SHA-256\"; } if(!formatPattern) { formatPattern = \"%064x\";} var md = MessageDigest.getInstance(algorithm); md.update(value.getBytes(\"UTF-8\")); var digestValue = md.digest(); return String.format(formatPattern, new BigInteger(1, digestValue));}; \n");
javascriptFunction.append(
"var newDateFormat = function(formatPattern) { return new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern(formatPattern).toFormatter(Locale.US); }; \n");
javascriptFunction.append(
"var dateMatches = function(dateValue, format) { try {\n format.parse(dateValue); \n return true; \n } catch(e) { } \n return false; }; \n");
javascriptFunction.append(
"var dateConvert = function(dateValue, inputFormat, outputFormat, parseClass) { if(!parseClass) { parseClass = LocalDate; } return parseClass.parse(dateValue, inputFormat).format(outputFormat); }; \n");
javascriptFunction.append("var filter = function() { throw new LFE(); }; \n");
javascriptFunction.append(
"var columnFunction = function(searchHeader, inputHeaders, line) { return inputHeaders.indexOf(searchHeader) >= 0 ? line.get(inputHeaders.indexOf(searchHeader)) : \"Could not find: \" + searchHeader; };\n");
javascriptFunction.append(
"var columnFunctionMap = function(searchHeader, mapLine) { return mapLine.get(searchHeader); };\n");
javascriptFunction.append(
"var mapFunction = function(inputHeaders, inputField, inputValue, outputHeaders, outputField, line, mapLine, previousLine, previousMappedLine, primaryKeys, lineNumber, filteredLineNumber, mapLineConsumer) { ");
javascriptFunction.append(
" var primaryKeyBoolean = function(nextPrimaryKey, primaryKeyField) { \n if(!primaryKeyField) { primaryKeyField = \"Primary\"; } \n return primaryKeys.get(primaryKeyField).add(nextPrimaryKey); }; \n ");
javascriptFunction.append(
" var primaryKeyFilter = function(nextPrimaryKey, primaryKeyField) { \n if(!primaryKeyField) { primaryKeyField = \"Primary\"; } \n return primaryKeys.get(primaryKeyField).add(nextPrimaryKey) ? nextPrimaryKey : filter(); }; \n ");
javascriptFunction.append(
" var col = function(searchHeader) { \n return columnFunction(searchHeader, inputHeaders, line); }; \n ");
javascriptFunction.append(
" var outCol = function(searchHeader) { \n return columnFunctionMap(searchHeader, mapLine); }; \n ");
javascriptFunction.append(this.mapping);
javascriptFunction.append(" \n }; \n");
scriptEngine.eval(javascriptFunction.toString());
} catch (ScriptException e) {
throw new RuntimeException(e);
}
} else if (this.language == ValueMappingLanguage.GROOVY) {
try {
scriptEngine = SCRIPT_MANAGER.getEngineByName("groovy");
scriptEngine
.eval("def mapFunction(inputHeaders, inputField, inputValue, outputHeaders, outputField, line, mapLine, previousLine, previousMappedLine, primaryKeys, lineNumber, filteredLineNumber, mapLineConsumer) { "
+ this.mapping + " }");
} catch (ScriptException e) {
throw new RuntimeException(e);
}
} else if (this.language == ValueMappingLanguage.LUA) {
try {
scriptEngine = SCRIPT_MANAGER.getEngineByName("lua");
compiledScript = ((Compilable) scriptEngine).compile(this.mapping);
} catch (ScriptException e) {
throw new RuntimeException(e);
}
} else if (this.language == ValueMappingLanguage.ACCESS) {
} else if (this.language == ValueMappingLanguage.CSVJOIN) {
} else if (this.language == ValueMappingLanguage.DBSCHEMA) {
} else {
throw new UnsupportedOperationException("Mapping language not supported: " + this.language);
}
}
@Override
public String toString() {
return "ValueMapping [language=" + language + ", input=" + input + ", output=" + output + ", mapping=" + mapping
+ ", shown=" + shown + "]";
}
public String[] getDestFields() {
return this.destFields;
}
public String[] getSourceFields() {
return this.sourceFields;
}
}
|
package com.github.rconner.util;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import com.google.common.base.Supplier;
import java.lang.ref.WeakReference;
/**
* A Supplier which caches the instance retrieved from a delegate Supplier in a {@link WeakReference}. If the reference
* is clear on a call to {@code get()}, it is retrieved again from the delegate. Note that the delegate Supplier cannot
* return null. Instances of this class are internally thread-safe and will never invoke the delegate concurrently.
* <p/>
* This class is not currently used, but was designed to help ImmutableStack.reverse() to be lazy, allow its value to
* be reused, and allow its value to be garbage collected.
*
* @param <T>
*/
@Beta
public final class CachingSupplier<T> implements Supplier<T> {
private final Supplier<T> delegate;
private volatile WeakReference<T> ref = new WeakReference<T>( null );
private final Object lock = new Object();
private CachingSupplier( final Supplier<T> delegate ) {
this.delegate = delegate;
}
public static <T> Supplier<T> of( final Supplier<T> delegate ) {
Preconditions.checkNotNull( delegate );
return delegate instanceof CachingSupplier ? delegate : new CachingSupplier<T>( delegate );
}
@Override
public T get() {
T value = ref.get();
if( value == null ) {
synchronized( lock ) {
value = ref.get();
if( value == null ) {
value = delegate.get();
Preconditions.checkState( value != null, "Value returned by delegate supplier cannot be null." );
ref = new WeakReference<T>( value );
}
}
}
return value;
}
}
|
package com.ircclouds.irc.api;
import java.io.*;
import org.slf4j.*;
import com.ircclouds.irc.api.comms.IConnection.EndOfStreamException;
import com.ircclouds.irc.api.domain.messages.ClientErrorMessage;
import com.ircclouds.irc.api.domain.messages.interfaces.*;
import com.ircclouds.irc.api.filters.*;
public abstract class AbstractApiDaemon extends Thread
{
private static final Logger LOG = LoggerFactory.getLogger(AbstractApiDaemon.class);
private IMessageReader reader;
private IMessageDispatcher dispatcher;
public AbstractApiDaemon(IMessageReader aReader, IMessageDispatcher aDispatcher)
{
super("ApiDaemon");
reader = aReader;
dispatcher = aDispatcher;
}
public void run()
{
try
{
while (reader.available())
{
IMessage _msg = reader.readMessage();
if (_msg != null)
{
dispatcher.dispatchToPrivateListeners(_msg);
if (getMessageFilter() != null)
{
MessageFilterResult _fr = getMessageFilter().filter(_msg);
if (_fr.getFilterStatus().equals(FilterStatus.PASS))
{
dispatcher.dispatch(_fr.getFilteredMessage(), getMessageFilter().getTargetListeners());
}
}
else
{
dispatcher.dispatch(_msg, TargetListeners.ALL);
}
}
}
}
catch (EndOfStreamException aExc)
{
LOG.debug("Received end of stream, closing connection", aExc);
}
catch (IOException aExc)
{
LOG.error(this.getName(), aExc);
signalExceptionToApi(aExc);
dispatcher.dispatch(new ClientErrorMessage(aExc), TargetListeners.ALL);
}
finally
{
LOG.debug("ApiDaemon Exiting..");
onExit();
}
}
protected abstract void signalExceptionToApi(Exception aExc);
protected abstract void onExit();
protected abstract IMessageFilter getMessageFilter();
}
|
package com.lordmau5.ffs.compat;
import com.lordmau5.ffs.tile.TileEntityTankFrame;
import com.lordmau5.ffs.tile.TileEntityValve;
import com.lordmau5.ffs.util.ExtendedBlock;
import com.lordmau5.ffs.util.GenericUtil;
import cpw.mods.fml.common.Optional;
import cpw.mods.fml.common.event.FMLInterModComms;
import mcp.mobius.waila.api.IWailaConfigHandler;
import mcp.mobius.waila.api.IWailaDataAccessor;
import mcp.mobius.waila.api.IWailaDataProvider;
import mcp.mobius.waila.api.IWailaRegistrar;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;
import java.util.List;
@Optional.Interface(iface = "mcp.mobius.waila.api.IWailaDataProvider", modid = "Waila")
public class WailaPluginTank implements IWailaDataProvider {
public static void init() {
FMLInterModComms.sendMessage("Waila", "register", WailaPluginTank.class.getName() + ".registerPlugin");
}
@Optional.Method(modid = "Waila")
public static void registerPlugin(IWailaRegistrar registrar) {
WailaPluginTank instance = new WailaPluginTank();
registrar.registerStackProvider(instance, TileEntityTankFrame.class);
registrar.registerBodyProvider(instance, TileEntityValve.class);
registrar.registerBodyProvider(instance, TileEntityTankFrame.class);
}
@Optional.Method(modid = "Waila")
@Override
public ItemStack getWailaStack(IWailaDataAccessor iWailaDataAccessor, IWailaConfigHandler iWailaConfigHandler) {
TileEntity te = iWailaDataAccessor.getTileEntity();
if (te instanceof TileEntityTankFrame) {
ExtendedBlock eb = ((TileEntityTankFrame) te).getBlock();
try {
return new ItemStack(eb.getBlock(), 1, eb.getMetadata());
} catch (Exception e) {
return null; // Catch this just in case something goes bad here. It's pretty rare but possible.
}
}
return null;
}
@Optional.Method(modid = "Waila")
@Override
public List<String> getWailaBody(ItemStack itemStack, List<String> list, IWailaDataAccessor iWailaDataAccessor, IWailaConfigHandler iWailaConfigHandler) {
TileEntity te = iWailaDataAccessor.getTileEntity();
TileEntityValve valve;
if (te instanceof TileEntityValve) {
valve = (TileEntityValve) te;
} else {
valve = ((TileEntityTankFrame) te).getValve();
list.add("Part of a tank");
}
if (valve == null) return list;
int fluidAmount = valve.getFluidAmount();
int capacity = valve.getCapacity();
if (!valve.isValid()) {
list.add("Invalid tank");
return list;
}
if (fluidAmount == 0) {
list.add("Fluid: None");
list.add("Amount: 0/" + GenericUtil.intToFancyNumber(capacity) + " mB");
} else {
String fluid = valve.getFluid().getFluid().getLocalizedName(valve.getFluid());
list.add("Fluid: " + fluid);
list.add("Amount: " + GenericUtil.intToFancyNumber(fluidAmount) + "/" + GenericUtil.intToFancyNumber(capacity) + " mB");
}
return list;
}
@Optional.Method(modid = "Waila")
@Override
public List<String> getWailaHead(ItemStack itemStack, List<String> list, IWailaDataAccessor iWailaDataAccessor, IWailaConfigHandler iWailaConfigHandler) {
// Unused, implemented because of the interface
return list;
}
@Optional.Method(modid = "Waila")
@Override
public List<String> getWailaTail(ItemStack itemStack, List<String> list, IWailaDataAccessor iWailaDataAccessor, IWailaConfigHandler iWailaConfigHandler) {
// Unused, implemented because of the interface
return list;
}
@Optional.Method(modid = "Waila")
@Override
public NBTTagCompound getNBTData(EntityPlayerMP entityPlayerMP, TileEntity tileEntity, NBTTagCompound nbtTagCompound, World world, int i, int i1, int i2) {
// Unused, implemented because of the interface
return nbtTagCompound;
}
}
|
package com.massfords.maven.spel;
import javax.annotation.Generated;
/**
* @author markford
*/
public class SpelAnnotation {
private String name;
private String attribute = "value";
public SpelAnnotation(String name) {
this.name = name;
}
@Generated("generated by IDE")
public String getName() {
return name;
}
@Generated("generated by IDE")
public SpelAnnotation setName(String name) {
this.name = name;
return this;
}
@Generated("generated by IDE")
public String getAttribute() {
return attribute;
}
@Generated("generated by IDE")
public SpelAnnotation setAttribute(String attribute) {
this.attribute = attribute;
return this;
}
}
|
package com.mcgoodtime.gti.common.init;
import com.mcgoodtime.gti.common.core.Gti;
import com.mcgoodtime.gti.common.items.ItemGti;
import com.mcgoodtime.gti.common.items.ItemGtiRecord;
import com.mcgoodtime.gti.common.items.tools.GtiToolMaterial;
import com.mcgoodtime.gti.common.items.tools.ItemGtiTreetap;
import com.mcgoodtime.gti.common.items.tools.ToolGti;
import cpw.mods.fml.common.IFuelHandler;
import cpw.mods.fml.common.registry.GameRegistry;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemFood;
import net.minecraft.item.ItemStack;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.world.World;
import java.util.List;
/**
* The list of all those items in GoodTime-Industrial.
*/
public class GtiItems implements IFuelHandler {
public static Item roller;
public static Item heatInsulationPlate;
public static Item thermalInsulationMaterial;
public static Item smallCompressedWaterHyacinth;
public static Item crushedIridium;
public static Item cleanedCrushedIridium;
public static Item dustIridium;
public static Item smallDustIridium;
public static Item ingotIridium;
public static Item denseDiamondPlate;
public static Item diamondPlate;
public static Item airBrakeUnit;
public static Item airBrakeCasing;
public static Item bambooCharcoal;
public static Item diamondApple;
public static Item iridiumPickaxe;
public static Item ironTreetap;
public static Item bronzeTreetap;
public static Item leadTreetap;
public static Item refinedIronTreetap;
public static Item advancedAlloyTreetap;
public static Item carbonTreetap;
public static Item record_theSaltWaterRoom;
public static Item salt;
public static Item packagedSalt;
public static Item carbonTube;
public static Item record_MusicSpring;
public static Item iridiumAxe;
public static Item iridiumSpade;
public static Item iridiumSword;
public static Item redstoneModule;
public static Item lazuliModule;
public static Item obsidianPlateGravityField;
public static Item electronicCircuitControl;
public static Item electronicCircuitCore;
public static Item pulseElectronicCircuitControl;
public static Item pulseElectronicCircuitCore;
public static Item cyclotronParticleAccelerator;
public static Item calculateUnit;
public static Item calculateChunk;
public static Item calculateArray;
public static Item floatPointCalculationsRegion;
public static Item parallelSpaceConverter;
public static Item uuMatterCore;
public static Item obsidianMechanicalFrame;
public static Item obsidianMechanicalCasing;
public static Item carbonCrystal;
public static Item enderCalculationCrystal;
public static Item millTeeth;
public static Item millWheel;
public static void init() {
roller = new ItemGti("Roller", true);
heatInsulationPlate = new ItemGti("HeatInsulationBoard");
thermalInsulationMaterial = new ItemGti("ThermalInsulationMaterial");
smallCompressedWaterHyacinth = new ItemGti("smallCompressedWaterHyacinth");
diamondPlate = new ItemGti("DiamondPlate", true);
denseDiamondPlate = new ItemGti("DenseDiamondPlate", true);
crushedIridium = new ItemGti("CrushedIridium");
cleanedCrushedIridium = new ItemGti("CleanedCrushedIridium");
dustIridium = new ItemGti("DustIridium");
smallDustIridium = new ItemGti("SmallDustIridium");
ingotIridium = new ItemGti("IngotIridium");
airBrakeUnit = new ItemGti("AirBrakeUnit");
airBrakeCasing = new ItemGti("AirBrakeCasing");
bambooCharcoal = new ItemGti("BambooCharcoal", true);
ironTreetap = new ItemGtiTreetap("IronTreetap", 32);
bronzeTreetap = new ItemGtiTreetap("BronzeTreetap", 32);
leadTreetap = new ItemGtiTreetap("LeadTreetap", 48);
refinedIronTreetap = new ItemGtiTreetap("RefinedIronTreetap", 64);
advancedAlloyTreetap = new ItemGtiTreetap("AdvancedAlloyTreetap", 64);
carbonTreetap = new ItemGtiTreetap("CarbonTreetap", 128);
record_theSaltWaterRoom = new ItemGtiRecord("record_TheSaltwaterRoom");
salt = new ItemGti("Salt");
packagedSalt = new ItemGti("PackagedSalt");
carbonTube = new ItemGti("CarbonTube", true);
record_MusicSpring = new ItemGtiRecord("record_MusicSpring");
redstoneModule = new ItemGti("RedstoneModule");
lazuliModule = new ItemGti("LazuliModule");
obsidianPlateGravityField = new ItemGti("ObsidianPlateGravityField");
electronicCircuitControl = new ItemGti("ElectronicCircuitControl");
electronicCircuitCore = new ItemGti("ElectronicCircuitCore");
pulseElectronicCircuitControl = new ItemGti("PulseElectronicCircuitControl");
pulseElectronicCircuitCore = new ItemGti("PulseElectronicCircuitCore");
cyclotronParticleAccelerator = new ItemGti("CyclotronParticleAccelerator");
calculateUnit = new ItemGti("CalculateUnit");
calculateChunk = new ItemGti("CalculateChunk");
calculateArray = new ItemGti("CalculateArray");
floatPointCalculationsRegion = new ItemGti("FloatPointCalculationsRegion");
parallelSpaceConverter = new ItemGti("ParallelSpaceConverter");
uuMatterCore = new ItemGti("UUMatterCore");
obsidianMechanicalFrame = new ItemGti("ObsidianMechanicalFrame");
obsidianMechanicalCasing = new ItemGti("ObsidianMechanicalCasing");
carbonCrystal = new ItemGti("CarbonCrystal");
enderCalculationCrystal = new ItemGti("EnderCalculationCrystal");
millTeeth = new ItemGti("MillTeeth");
millWheel = new ItemGti("MillWheel");
// special registry TODO: Better registry system
diamondApple = new ItemFood(1005, 10F, false) {
@Override
protected void onFoodEaten(ItemStack itemStack, World world, EntityPlayer player) {
if (!world.isRemote) {
player.addPotionEffect(new PotionEffect(Potion.field_76434_w.id, 12000, 0));
player.addPotionEffect(new PotionEffect(Potion.regeneration.id, 6000, 4));
player.addPotionEffect(new PotionEffect(Potion.resistance.id, 6000, 4));
player.addPotionEffect(new PotionEffect(Potion.fireResistance.id, 6000, 0));
}
super.onFoodEaten(itemStack, world, player);
}
@Override
@SuppressWarnings("unchecked")
public void addInformation(ItemStack itemStack, EntityPlayer player, List list, boolean bool) {
list.add(I18n.format(diamondApple.getUnlocalizedName() + ".desc1"));
}
};
diamondApple = diamondApple
.setUnlocalizedName("gti.food.DiamondApple")
.setCreativeTab(Gti.creativeTabGti)
.setTextureName("gti:itemDiamondApple");
iridiumPickaxe = ToolGti.registerPickaxe(GtiToolMaterial.iridium, "IridiumPickaxe");
iridiumAxe = ToolGti.registerAxe(GtiToolMaterial.iridium, "IridiumAxe");
iridiumSpade = ToolGti.registerSpade(GtiToolMaterial.iridium, "IridiumSpade");
iridiumSword = ToolGti.registerSword(GtiToolMaterial.iridium, "IridiumSword");
// TODO: Better registry system
GameRegistry.registerItem(diamondApple, "DiamondApple");
GameRegistry.registerFuelHandler(new GtiItems());
}
@Override
public int getBurnTime(ItemStack fuel) {
if (fuel.getItem() == bambooCharcoal) {
return 800;
}
if(fuel.getItem() == smallCompressedWaterHyacinth){
return 400;
}
if(fuel.getItem().equals(Item.getItemFromBlock(GtiBlocks.waterHyacinth))){
return 100;
}
if(fuel.getItem().equals(Item.getItemFromBlock(GtiBlocks.compressedWaterHyacinth))){
return 800;
}
if(fuel.getItem().equals(Item.getItemFromBlock(GtiBlocks.dehydratedWaterHyacinthblock))){
return 1000;
}
return 0;
}
}
|
package com.ociweb.pronghorn.network;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.security.SecureRandom;
public class TLSService {
private static final Logger logger = LoggerFactory.getLogger(TLSService.class);
private final SSLContext context;
private String[] cipherSuits;
private final String[] protocols;
public static final boolean LOG_CYPHERS = false;
public TLSService(KeyManagerFactory keyManagerFactory, TrustManagerFactory trustManagerFactory, boolean trustAll) {
try {
//protocol The SSL/TLS protocol to be used. Java 1.6 will only run with up to TLSv1 protocol. Java 1.7 or higher also supports TLSv1.1 and TLSv1.2 protocols.
final String PROTOCOL = "TLSv1.2";
final String PROTOCOL1_3 = "TLSv1.3"; //check Java version and move up to this ASAP.
this.protocols = new String[]{PROTOCOL}; //[SSLv2Hello, TLSv1, TLSv1.1, TLSv1.2]
KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();
TrustManager[] trustManagers;
if (trustAll) {
trustManagers = TLSCertificateTrust.trustManagerFactoryTrustAllCerts(trustManagerFactory);
} else {
trustManagers = TLSCertificateTrust.trustManagerFactoryDefault(trustManagerFactory);
}
context = SSLContext.getInstance(PROTOCOL);
context.init(keyManagers, trustManagers, new SecureRandom());
//run once first to determine which cypher suites we will be using.
createSSLEngineServer();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public int maxEncryptedContentLength() {
return 33305;//java TLS engine requested this value;//Integer.MAX_VALUE;
}
public SSLEngine createSSLEngineClient(String host, int port) {
SSLEngine result = context.createSSLEngine(host, port);
result.setEnabledCipherSuites(filterCipherSuits(result));
result.setEnabledProtocols(protocols);
return result;
}
public SSLEngine createSSLEngineServer() {
SSLEngine result = context.createSSLEngine();
result.setEnabledCipherSuites(filterCipherSuits(result));
result.setEnabledProtocols(protocols);
return result;
}
private String[] filterCipherSuits(SSLEngine result) {
if (null==cipherSuits) {
//TODO: rewrite with recursive count...
String[] enabledCipherSuites = result.getSupportedCipherSuites();
int count = 0;
int i = enabledCipherSuites.length;
while (--i>=0) {
if (containsPerfectForward(enabledCipherSuites, i)) {
if (doesNotContainWeakCipher(enabledCipherSuites, i)) {
count++;
}
}
}
String[] temp = new String[count];
i = enabledCipherSuites.length;
int j = 0;
while (--i>=0) {
if (containsPerfectForward(enabledCipherSuites, i)) {
if (doesNotContainWeakCipher(enabledCipherSuites, i)) {
if (LOG_CYPHERS) {
logger.info("enable cipher suite: {}",enabledCipherSuites[i]);
}
temp[j++]=enabledCipherSuites[i];
}
}
}
cipherSuits = temp;
}
return cipherSuits;
}
private static boolean doesNotContainWeakCipher(String[] enabledCipherSuites, int i) {
return !enabledCipherSuites[i].contains("DES_") &&
!enabledCipherSuites[i].contains("EXPORT") &&
!enabledCipherSuites[i].contains("NULL");
}
private static boolean containsPerfectForward(String[] enabledCipherSuites, int i) {
return enabledCipherSuites[i].contains("DHE") ||
enabledCipherSuites[i].contains("EDH");
}
}
|
package com.qiniu.storage;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Client;
import com.qiniu.http.Response;
import java.io.IOException;
abstract class ResumeUploadPerformer {
final Client client;
private final Recorder recorder;
private final Configuration config;
private final ConfigHelper configHelper;
final String key;
final UploadToken token;
final ResumeUploadSource uploadSource;
final UploadOptions options;
ResumeUploadPerformer(Client client, String key, UploadToken token, ResumeUploadSource source,
Recorder recorder, UploadOptions options, Configuration config) {
this.client = client;
this.key = key;
this.token = token;
this.uploadSource = source;
this.options = options == null ? UploadOptions.defaultOptions() : options;
this.recorder = recorder;
this.config = config;
this.configHelper = new ConfigHelper(config);
}
boolean isAllBlocksUploadingOrUploaded() {
return uploadSource.isAllBlocksUploadingOrUploaded();
}
boolean isAllBlocksUploaded() {
return uploadSource.isAllBlocksUploaded();
}
abstract boolean shouldUploadInit();
abstract Response uploadInit() throws QiniuException;
Response uploadNextData() throws QiniuException {
ResumeUploadSource.Block block = null;
synchronized (this) {
block = getNextUploadingBlock();
if (block != null) {
block.isUploading = true;
}
}
if (block == null) {
return Response.createSuccessResponse();
}
try {
return uploadBlock(block);
} finally {
block.isUploading = false;
}
}
abstract Response uploadBlock(ResumeUploadSource.Block block) throws QiniuException;
abstract Response completeUpload() throws QiniuException;
private ResumeUploadSource.Block getNextUploadingBlock() throws QiniuException {
ResumeUploadSource.Block block = null;
try {
block = uploadSource.getNextUploadingBlock();
} catch (IOException e) {
throw QiniuException.unrecoverable(e);
}
return block;
}
private String getUploadHost() throws QiniuException {
return configHelper.upHost(token.getToken());
}
private void changeHost(String host) {
try {
configHelper.tryChangeUpHost(token.getToken(), host);
} catch (Exception ignored) {
}
}
Response retryUploadAction(UploadAction action) throws QiniuException {
Response response = null;
int retryCount = 0;
do {
boolean shouldSwitchHost = false;
boolean shouldRetry = false;
QiniuException exception = null;
String host = getUploadHost();
try {
response = action.uploadAction(host);
if (response == null || response.needRetry()) {
shouldRetry = true;
}
// host
if (response == null || response.needSwitchServer()) {
shouldSwitchHost = true;
}
} catch (QiniuException e) {
exception = e;
if (!e.isUnrecoverable() && (e.response == null || e.response.needRetry())) {
shouldRetry = true;
} else {
throw e;
}
if (!e.isUnrecoverable() && (e.response == null || e.response.needSwitchServer())) {
shouldSwitchHost = true;
}
}
if (!shouldRetry) {
break;
}
retryCount++;
if (retryCount >= config.retryMax) {
QiniuException innerException = null;
if (response != null) {
innerException = new QiniuException(response);
} else {
innerException = new QiniuException(exception);
}
throw new QiniuException(innerException, "failed after retry times");
}
if (shouldSwitchHost) {
changeHost(host);
}
} while (true);
return response;
}
interface UploadAction {
Response uploadAction(String host) throws QiniuException;
}
}
|
package com.rox.emu.processor.mos6502;
import com.rox.emu.env.RoxByte;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A representation of the MOS 6502 CPU registers
*
* @author Ross Drew
*/
public class Registers {
private final Logger LOG = LoggerFactory.getLogger(this.getClass());
// private enum Register {
// ACCUMULATOR(0),
// Y_INDEX(1),
// X_INDEX(2),
// PROGRAM_COUNTER_HI(3),
// PROGRAM_COUNTER_LOW(4),
// STACK_POINTER_LOW(5),
// STACK_POINTER_HI(6),
// STATUS_FLAGS(7);
// private final String description;
// private final int index;
// private final int placeValue;
// Register(int index){
// this.index = index;
// this.placeValue = 1 << index;
// description = prettifyName(name());
// private static String prettifyName(String originalName){
// String name = originalName.replaceAll("_"," ")
// .toLowerCase()
// .replace("hi","(High)")
// .replace("low","(Low)");
// name = name.substring(0, 1).toUpperCase() + name.substring(1);
// int spaceIndex = name.indexOf(' ');
// if (spaceIndex > 0)
// name = name.substring(0, spaceIndex) + name.substring(spaceIndex, spaceIndex+2).toUpperCase() + name.substring(spaceIndex+2);
// return name;
// public String getDescription(){
// return description;
// public int getIndex(){
// return this.index;
// public int getPlaceValue(){
// return this.placeValue;
/** Register ID of the Accumulator */
public static final int REG_ACCUMULATOR = 0;
/** Register ID of the Y Index register */
public static final int REG_Y_INDEX = 1;
/** Register ID of the X Index register */
public static final int REG_X_INDEX = 2;
/** Register ID of the high byte of the Program Counter */
public static final int REG_PC_HIGH = 3;
/** Register ID of the low byte of the Program Counter */
public static final int REG_PC_LOW = 4;
/** Register ID of the <em>fixed value</em> high byte of the Stack Pointer */
private static final int REG_SP_X = 5;
/** Register ID of the low byte of the Stack Pointer */
public static final int REG_SP = 6;
/** Register ID of the Status flag byte */
public static final int REG_STATUS = 7;
private static final String[] registerNames = new String[] {"Accumulator", "Y Index", "X Index", "Program Counter (Hi)", "Program Counter (Low)", "<SP>", "Stack Pointer", "Status Flags"};
/** Place value of Carry status flag in bit {@value #C} */
public static final int STATUS_FLAG_CARRY = 0x1;
/** Place value of Zero status flag in bit {@value #Z} */
public static final int STATUS_FLAG_ZERO = 0x2;
/** Place value of Interrupt status flag in bit {@value #I} */
public static final int STATUS_FLAG_IRQ_DISABLE = 0x4;
/** Place value of Binary Coded Decimal status flag in bit {@value #D} */
public static final int STATUS_FLAG_DEC = 0x8;
/** Place value of Break status flag in bit {@value #B} */
public static final int STATUS_FLAG_BREAK = 0x10;
private static final int STATUS_FLAG_UNUSED = 0x20; //Placeholder only
/** Place value of Overflow status flag in bit {@value #V} */
public static final int STATUS_FLAG_OVERFLOW = 0x40;
/** Place value of Negative status flag in bit {@value #N} */
public static final int STATUS_FLAG_NEGATIVE = 0x80;
/** Bit place of Negative status flag */
public static final int N = 7;
/** Bit place of Overflow status flag */
public static final int V = 6;
/** - <em>UNUSED</em> (Placeholder flag only) **/
private static final int U = 5; //Placeholder only
/** Bit place of Break status flag */
public static final int B = 4;
/** Bit place of Binary Coded Decimal status flag */
public static final int D = 3;
/** Bit place of Interrupt status flag */
public static final int I = 2;
/** Bit place of Zero status flag */
public static final int Z = 1;
/** Bit place ofCarry status flag */
public static final int C = 0;
private static final String[] flagNames = new String[] {"Carry", "Zero", "IRQ Disable", "Decimal Mode", "BRK Command", "<UNUSED>", "Overflow", "Negative"};
private final RoxByte[] register;
public Registers(){
register = new RoxByte[8];
for (int i=0; i<8; i++)
register[i] = RoxByte.ZERO;
register[REG_SP_X] = RoxByte.literalFrom(0b11111111);
register[REG_STATUS] = RoxByte.literalFrom(0b00000000);
}
/**
* @param registerID to return the name for
* @return A {@link String} representation of the register for <code>registerID</code>
*/
public static String getRegisterName(int registerID){
return registerNames[registerID];
}
/**
* @param registerID of the register to set
* @param val to set the register to
*/
public void setRegister(int registerID, int val){
LOG.debug("'R:" + getRegisterName(registerID) + "' := " + val);
register[registerID] = RoxByte.literalFrom(val);
}
/**
* @param registerID for which to get the value
* @return the value of the desired register
*/
public int getRegister(int registerID){
return register[registerID].getRawValue();
}
/**
* Set the given register to the given value and set the flags register based on that value
*
* @param registerID of the register to set
* @param value to set the register to
*/
public void setRegisterAndFlags(int registerID, int value){
int valueByte = value & 0xFF;
setRegister(registerID, valueByte);
setFlagsBasedOn(valueByte);
}
/**
* @param newPCWord to set the Program Counter to
*/
public void setPC(int newPCWord){
setRegister(REG_PC_HIGH, newPCWord >> 8);
setRegister(REG_PC_LOW, newPCWord & 0xFF);
LOG.debug("'R+:Program Counter' := " + newPCWord + " [ " + getRegister(REG_PC_HIGH) + " | " + getRegister(REG_PC_LOW) + " ]");
}
/**
* @return the two byte value of the Program Counter
*/
public int getPC(){
return (getRegister(REG_PC_HIGH) << 8) | getRegister(REG_PC_LOW);
}
/**
* Increment the Program Counter then return it's value
*
* @return the new value of the Program Counter
*/
public int getNextProgramCounter(){
setPC(getPC()+1);
return getPC();
}
public static int getFlagID(int flagPlaceValue) throws IllegalArgumentException {
switch (flagPlaceValue){
case STATUS_FLAG_CARRY: return C;
case STATUS_FLAG_ZERO: return Z;
case STATUS_FLAG_IRQ_DISABLE: return I;
case STATUS_FLAG_DEC: return D;
case STATUS_FLAG_BREAK: return B;
case STATUS_FLAG_UNUSED: return U;
case STATUS_FLAG_OVERFLOW: return V;
case STATUS_FLAG_NEGATIVE: return N;
default:
throw new IllegalArgumentException("Unknown 6502 Flag ID:" + flagPlaceValue);
}
}
/**
* @param flagNumber for which to get the name
* @return the {@lnk String} name of the given flag
*/
public static String getFlagName(int flagNumber){
if (flagNumber < 0 || flagNumber > 7)
throw new IllegalArgumentException("Unknown 6502 Flag ID:" + flagNumber);
return flagNames[flagNumber];
}
/**
* @param flagBitNumber flag to test
* @return <code>true</code> if the specified flag is set, <code>false</code> otherwise
*/
public boolean getFlag(int flagBitNumber) {
return register[REG_STATUS].isBitSet(flagBitNumber);
}
/**
* @param flagBitNumber for which to set to true
*/
public void setFlag(int flagBitNumber) {
LOG.debug("'F:" + getFlagName(flagBitNumber) +"' -> SET");
register[REG_STATUS] = register[REG_STATUS].withBit(flagBitNumber);
}
/**
* Bitwise clear flag by OR-ing the int carrying flags to be cleared
* then AND-ing with status flag register.
*
* Clear bit 1 (place value 2)
* 0000 0010
* NOT > 1111 1101
* AND(R) > .... ..0.
*
* @param flagBitNumber int with bits to clear, turned on
*/
public void clearFlag(int flagBitNumber){
LOG.debug("'F:" + getFlagName(flagBitNumber) + "' -> CLEARED");
register[REG_STATUS] = register[REG_STATUS].withoutBit(flagBitNumber);
}
/**
* @param value to set the register flags based on
*/
public void setFlagsBasedOn(int value){
int valueByte = value & 0xFF;
setZeroFlagFor(valueByte);
setNegativeFlagFor(valueByte);
}
/**
* Set zero flag if given argument is 0
*/
public void setZeroFlagFor(int value){
if (value == 0)
setFlag(Z);
else
clearFlag(Z);
}
/**
* Set negative flag if given argument is 0
*/
public void setNegativeFlagFor(int value){
if (isNegative(value))
setFlag(N);
else
clearFlag(N);
}
private boolean isNegative(int fakeByte){
return (fakeByte & STATUS_FLAG_NEGATIVE) == STATUS_FLAG_NEGATIVE;
}
}
|
package com.rox.emu.processor.mos6502.op;
import com.rox.emu.UnknownOpCodeException;
import com.rox.emu.processor.mos6502.Mos6502;
import com.rox.emu.processor.mos6502.op.util.OpCodeConverter;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Stream;
/**
* Enum representation of {@link Mos6502} op-codes. Each represented by an enum name using the convention
* '{OP-CODE}{@value #TOKEN_SEPARATOR}{ADDRESSING-MODE}{@value #TOKEN_SEPARATOR}{INDEXING-MODE}'.
*
* @author Ross Drew
*/
public enum OpCode {
BRK(0x00),
ASL_A(0x0A),
ASL_Z(0x06),
ASL_ABS(0x0E),
ASL_Z_IX(0x16),
ASL_ABS_IX(0x1E),
LSR_A(0x4A),
LSR_Z(0x46),
LSR_Z_IX(0x56),
LSR_ABS(0x4E),
LSR_ABS_IX(0x5E),
ADC_Z(0x65),
ADC_I(0x69),
ADC_ABS(0x6D),
ADC_ABS_IX(0x7D),
ADC_ABS_IY(0x79),
ADC_Z_IX(0x75),
ADC_IND_IX(0x61),
ADC_IND_IY(0x71),
LDA_Z(0xA5),
LDA_I(0xA9),
LDA_ABS(0xAD),
LDA_Z_IX(0xB5),
LDA_ABS_IY(0xB9),
LDA_IND_IX(0xA1),
LDA_IND_IY(0xB1),
LDA_ABS_IX(0xBD),
CLV(0xB8),
AND_Z(0x25),
AND_Z_IX(0x35),
AND_ABS_IX(0x3D),
AND_ABS_IY(0x39),
AND_ABS(0x2D),
AND_I(0x29),
AND_IND_IX(0x21),
AND_IND_IY(0x31),
ORA_I(0x09),
ORA_Z(0x05),
ORA_Z_IX(0x15),
ORA_ABS(0x0D),
ORA_ABS_IX(0x1D),
ORA_ABS_IY(0x19),
ORA_IND_IX(0x01),
ORA_IND_IY(0x11),
EOR_I(0x49),
EOR_Z(0x45),
EOR_Z_IX(0x55),
EOR_ABS(0x4D),
EOR_ABS_IX(0x5D),
EOR_ABS_IY(0x59),
EOR_IND_IX(0x41),
EOR_IND_IY(0x51),
SBC_I(0xE9),
SBC_Z(0xE5),
SBC_Z_IX(0xF5),
SBC_ABS(0xED),
SBC_ABS_IX(0xFD),
SBC_ABS_IY(0xF9),
SBC_IND_IX(0xE1),
SBC_IND_IY(0xF1),
CLC(0x18),
SEC(0x38),
LDY_I(0xA0),
LDY_Z(0xA4),
LDY_Z_IX(0xB4),
LDY_ABS(0xAC),
LDY_ABS_IX(0xBC),
LDX_I(0xA2),
LDX_ABS(0xAE),
LDX_ABS_IY(0xBE),
LDX_Z(0xA6),
LDX_Z_IY(0xB6),
STY_Z(0x84),
STY_ABS(0x8C),
STY_Z_IX(0x94),
STA_Z(0x85),
STA_ABS(0x8D),
STA_Z_IX(0x95),
STA_ABS_IX(0x9D),
STA_ABS_IY(0x99),
STA_IND_IX(0x81),
STA_IND_IY(0x91),
STX_Z(0x86),
STX_Z_IY(0x96),
STX_ABS(0x8E),
INY(0xC8),
INX(0xE8),
DEX(0xCA),
INC_Z(0xE6),
INC_Z_IX(0xF6),
INC_ABS(0xEE),
INC_ABS_IX(0xFE),
DEC_Z(0xC6),
DEC_Z_IX(0xD6),
DEC_ABS(0xCE),
DEC_ABS_IX(0xDE),
DEY(0x88),
PHA(0x48),
PLA(0x68),
PHP(0x08),
PLP(0x28),
NOP(0xEA),
JMP_ABS(0x4C),
JMP_IND(0x6C),
TAX(0xAA),
TAY(0xA8),
TYA(0x98),
TXA(0x8A),
TXS(0x9A),
TSX(0xBA),
BIT_Z(0x24),
BIT_ABS(0x2C),
CMP_I(0xC9),
CMP_Z(0xC5),
CMP_Z_IX(0xD5),
CMP_ABS(0xCD),
CMP_ABS_IX(0xDD),
CMP_ABS_IY(0xD9),
CMP_IND_IX(0xC1),
CMP_IND_IY(0xD1),
CPX_I(0xE0),
CPX_Z(0xE4),
CPX_ABS(0xEC),
CPY_I(0xC0),
CPY_Z(0xC4),
CPY_ABS(0xCC),
JSR(0x20),
BPL(0x10),
BMI(0x30),
BVC(0x50),
BVS(0x70),
BCC(0x90),
BCS(0xB0),
BNE(0xD0),
BEQ(0xF0),
ROL_A(0x2A),
ROL_Z(0x26),
ROL_Z_IX(0x36),
ROL_ABS(0x2E),
ROL_ABS_IX(0x3E),
ROR_A(0x6A),
CLI(0x58),
SEI(0x78),
SED(0xF8),
CLD(0xD8),
RTS(0x60),
RTI(0x40);
// public enum Operation {
// BRK, ASL, LSR, ADC, LDA, CLV, AND, ORA, EOR, SBC,
// CLC, SEC, LDY, LDX, STY, STA, STX, INY, INX, DEX,
// INC, DEC, DEY, PHA, PLA, PHP, PLP, NOP, JMP, TAX,
// TAY, TYA, TXA, TXS, TSX, BIT, CMP, CPX, CPY, JSR,
// BPL, BMI, BVC, BVS, BCC, BCS, BNE, BEQ, ROL, ROR,
// CLI, SEI, SED, CLD, RTS, RTI
/**
* The separator used to delimit different elements in the {@link String} enum id
*/
public static final String TOKEN_SEPARATOR = "_";
/**
* The index of the op-code name in the {@link String} enum id,
* using the token delimiter {@value TOKEN_SEPARATOR}
*/
public static final int CODE_I = 0;
/**
* The index of the addressing mode token in the {@link String} enum id,
* using the token delimiter {@value TOKEN_SEPARATOR}
*/
public static final int ADDR_I = CODE_I + 1;
/**
* The index of the indexing mode token in the {@link String} enum id,
* using the token delimiter {@value TOKEN_SEPARATOR}
*/
public static final int INDX_I = ADDR_I + 1;
private final int byteValue;
private final String opCodeName;
private final AddressingMode addressingMode;
OpCode(int byteValue){
this.byteValue = byteValue;
this.addressingMode = OpCodeConverter.getAddressingMode(this.name());
this.opCodeName = OpCodeConverter.getOpCode(this.name());
}
/**
* Get the OpCode for
*
* @param byteValue this byte value
* @return the OpCode associated with this byte value
*/
public static OpCode from(int byteValue){
return from(opcode -> opcode.getByteValue() == byteValue, byteValue);
}
/**
* Get the OpCode for
*
* @param opCodeName Three character {@link String} representing an {@link AddressingMode#IMPLIED} addressed OpCode
* @return The OpCode instance associated with this name in {@link AddressingMode#IMPLIED}
*/
public static OpCode from(String opCodeName){
return from(opcode -> opcode.getOpCodeName().equalsIgnoreCase(opCodeName), opCodeName);
}
/**
* Get the OpCode for
*
* @param opCodeName Three character {@link String} representing OpCode name
* @param addressingMode The {@link AddressingMode} of the OpCode
* @return The OpCode instance associated with this name in this {@link AddressingMode}
*/
public static OpCode from(String opCodeName, AddressingMode addressingMode){
return matching(opcode -> opcode.getOpCodeName().equalsIgnoreCase(opCodeName) &&
opcode.getAddressingMode() == addressingMode,
opCodeName + " in " + addressingMode,
opCodeName);
}
/**
* @param predicate A predicate used to search {@link OpCode}s
* @param predicateTerm The main term of {@link Object} used in the predicate
* @return The first {@link OpCode} found
* @throws UnknownOpCodeException
*/
private static OpCode from(Predicate<? super OpCode> predicate, Object predicateTerm) throws UnknownOpCodeException{
return matching(predicate, ""+predicateTerm, predicateTerm);
}
/**
* @param predicate A predicate used to search {@link OpCode}s
* @param predicateDescription A {@link String} description of the search
* @param predicateTerm The main term of {@link Object} used in the predicate
* @return The first {@link OpCode} found
* @throws UnknownOpCodeException if no {@link OpCode} matches the given predicate
*/
private static OpCode matching(Predicate<? super OpCode> predicate, String predicateDescription, Object predicateTerm) throws UnknownOpCodeException{
Optional<OpCode> result = Arrays.stream(OpCode.values()).filter(predicate).findFirst();
if (result.isPresent())
return result.get();
throw new UnknownOpCodeException("Unknown opcode name while creating OpCode object: " + predicateDescription, predicateTerm);
}
/**
* @return the 6502 byte value for this {@link OpCode}
*/
public int getByteValue(){
return byteValue;
}
/**
* @return the human readable {@link String} representing this {@link OpCode}
*/
public String getOpCodeName() {return opCodeName;}
/**
* @return the {@link AddressingMode} that this {@link OpCode} uses
*/
public AddressingMode getAddressingMode(){
return this.addressingMode;
}
/**
* @param addressingMode from which to get possible {@link OpCode}s
* @return a {@link Stream} of all {@link OpCode}s that use the the specified {@link AddressingMode}
*/
public static Stream<OpCode> streamOf(AddressingMode addressingMode){
return streamOf(opcode -> opcode.getAddressingMode() == addressingMode);
}
private static Stream<OpCode> streamOf(Predicate<? super OpCode> predicate){
return Stream.of(OpCode.values()).filter(predicate);
}
/**
* @return The textual description of this {@link OpCode} including the {@link AddressingMode} it uses
*/
@Override
public String toString(){
return opCodeName + " (" + addressingMode + ")[0x" + Integer.toHexString(byteValue) + "]";
}
}
|
package com.simplegame.protocol.message;
import com.alibaba.fastjson.JSONArray;
/**
* @Author zeusgooogle@gmail.com
* @sine 201553 10:03:06
*
*/
public class Message {
/**
* Message Body
*
* 0: command Not Null
* 1: data Not Null
* 2: dest type
* 3from type
* 4: route
* 5: sessionId
* 6: roleId
* 7: userId
* 8: stageId
* 9: token
*
*/
private Object[] msgSource;
public Message(Object[] msgSource) {
this.msgSource = msgSource;
}
public String getCommand() {
return (String) this.msgSource[0];
}
public <T> T getData() {
return (T) this.msgSource[1];
}
public int getRoute() {
return (Integer) this.msgSource[4];
}
public String getSessionId() {
return (String)this.msgSource[5];
}
public String getRoleId() {
return (String) this.msgSource[6];
}
public String getUserId() {
return (String) this.msgSource[7];
}
public String getStageId() {
Object stageId = this.msgSource[8];
if (null != stageId) {
return (String) stageId;
}
return "";
}
public Object[] getToken() {
Object stageId = this.msgSource[9];
if (null != stageId) {
return (Object[]) stageId;
}
return null;
}
public Object[] getMsgSource() {
return this.msgSource;
}
@Override
public String toString() {
return JSONArray.toJSONString(this.msgSource);
}
public enum FromType {
CLIENT(1),
BUS(2),
STAGE(3),
;
private final int value;
private FromType(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
public static FromType findType(int type) {
switch (type) {
case 1:
return CLIENT;
case 2:
return BUS;
case 3:
return STAGE;
default:
throw new IllegalArgumentException("invalid frome type.");
}
}
}
public enum DestType {
CLIENT(0),
BUS(1),
STAGE(2),
INOUT(3),
PUBLIC(4),
SYSTEM(5),
;
private final int value;
private DestType(int value) {
this.value = value;
}
public int getValue() {
return this.value;
}
public static DestType findType(int type) {
switch (type) {
case 0:
return CLIENT;
case 1:
return BUS;
case 2:
return STAGE;
case 3:
return INOUT;
case 4:
return PUBLIC;
case 5:
return SYSTEM;
default:
throw new IllegalArgumentException("invalid frome type.");
}
}
}
}
|
package com.skelril.aurora;
import com.sk89q.commandbook.CommandBook;
import com.sk89q.commandbook.FreezeComponent;
import com.sk89q.commandbook.session.PersistentSession;
import com.sk89q.commandbook.session.SessionComponent;
import com.sk89q.worldedit.blocks.BlockID;
import com.sk89q.worldedit.blocks.ItemID;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import com.skelril.aurora.admin.AdminComponent;
import com.skelril.aurora.anticheat.AntiCheatCompatibilityComponent;
import com.skelril.aurora.events.anticheat.RapidHitEvent;
import com.skelril.aurora.events.custom.item.SpecialAttackEvent;
import com.skelril.aurora.events.entity.ProjectileTickEvent;
import com.skelril.aurora.prayer.PrayerFX.HulkFX;
import com.skelril.aurora.util.ChanceUtil;
import com.skelril.aurora.util.ChatUtil;
import com.skelril.aurora.util.item.EffectUtil;
import com.skelril.aurora.util.item.InventoryUtil;
import com.skelril.aurora.util.item.ItemUtil;
import com.skelril.aurora.util.timer.IntegratedRunnable;
import com.skelril.aurora.util.timer.TimedRunnable;
import com.zachsthings.libcomponents.ComponentInformation;
import com.zachsthings.libcomponents.Depend;
import com.zachsthings.libcomponents.InjectComponent;
import com.zachsthings.libcomponents.bukkit.BukkitComponent;
import net.h31ix.anticheat.manage.CheckType;
import org.bukkit.*;
import org.bukkit.entity.*;
import org.bukkit.event.Event;
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.entity.*;
import org.bukkit.event.inventory.*;
import org.bukkit.event.player.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitTask;
import java.util.*;
import java.util.concurrent.TimeUnit;
import static com.skelril.aurora.events.custom.item.SpecialAttackEvent.Specs;
@ComponentInformation(friendlyName = "Custom Items Component", desc = "Custom Items")
@Depend(components = {SessionComponent.class, AdminComponent.class,
AntiCheatCompatibilityComponent.class, FreezeComponent.class})
public class CustomItemsComponent extends BukkitComponent implements Listener {
private final CommandBook inst = CommandBook.inst();
private final Server server = CommandBook.server();
@InjectComponent
private SessionComponent sessions;
@InjectComponent
private AdminComponent admin;
@InjectComponent
private AntiCheatCompatibilityComponent antiCheat;
@InjectComponent
private FreezeComponent freeze;
private WorldGuardPlugin WG;
private List<String> players = new ArrayList<>();
@Override
public void enable() {
//noinspection AccessStaticViaInstance
inst.registerEvents(this);
Plugin plugin = server.getPluginManager().getPlugin("WorldGuard");
WG = plugin != null && plugin instanceof WorldGuardPlugin ? (WorldGuardPlugin) plugin : null;
}
public CustomItemSession getSession(Player player) {
return sessions.getSession(CustomItemSession.class, player);
}
private Specs callSpec(Player owner, Object target, Specs spec) {
SpecialAttackEvent event;
if (target instanceof LivingEntity) {
event = new SpecialAttackEvent(owner, (LivingEntity) target, spec);
} else if (target instanceof Location) {
event = new SpecialAttackEvent(owner, (Location) target, spec);
} else {
return null;
}
server.getPluginManager().callEvent(event);
return event.isCancelled() ? null : event.getSpec();
}
private Specs callSpec(Player owner, Object target, int start, int end) {
Specs[] available;
Specs used;
SpecialAttackEvent event;
available = Arrays.copyOfRange(Specs.values(), start, end);
used = available[ChanceUtil.getRandom(available.length) - 1];
if (target instanceof LivingEntity) {
event = new SpecialAttackEvent(owner, (LivingEntity) target, used);
} else if (target instanceof Location) {
event = new SpecialAttackEvent(owner, (Location) target, used);
} else {
return null;
}
server.getPluginManager().callEvent(event);
return event.isCancelled() ? null : event.getSpec();
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityRegainHealth(EntityRegainHealthEvent event) {
Entity healed = event.getEntity();
if (healed instanceof Player) {
Player player = (Player) healed;
if (ItemUtil.matchesFilter(player.getInventory().getHelmet(), ChatColor.GOLD + "Ancient Crown")) {
event.setAmount(event.getAmount() * 2.5);
}
}
}
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onEntityDamageEntity(EntityDamageByEntityEvent event) {
Entity damager = event.getDamager();
boolean wasProjectile = false;
if (damager instanceof Projectile && ((Projectile) damager).getShooter() != null) {
damager = ((Projectile) damager).getShooter();
wasProjectile = true;
}
Player owner = damager instanceof Player ? (Player) damager : null;
LivingEntity target = event.getEntity() instanceof LivingEntity ? (LivingEntity) event.getEntity() : null;
if (owner != null && target != null) {
CustomItemSession session = getSession(owner);
Specs used;
if (session.canSpec(SpecType.FEAR)) {
if (ItemUtil.hasFearSword(owner)) {
used = callSpec(owner, target, 0, 6);
if (used == null) return;
session.updateSpec(SpecType.FEAR);
switch (used) {
case CONFUSE:
EffectUtil.Fear.confuse(owner, target);
break;
case BLAZE:
EffectUtil.Fear.fearBlaze(owner, target);
break;
case CURSE:
EffectUtil.Fear.curse(owner, target);
break;
case WEAKEN:
EffectUtil.Fear.weaken(owner, target);
break;
case DECIMATE:
EffectUtil.Fear.decimate(owner, target);
break;
case SOUL_SMITE:
EffectUtil.Fear.soulSmite(owner, target);
break;
}
} else if (ItemUtil.hasFearBow(owner) && wasProjectile) {
used = callSpec(owner, target, 6, 11);
if (used == null) return;
session.updateSpec(SpecType.FEAR);
switch (used) {
case DISARM:
if (EffectUtil.Fear.disarm(owner, target)) {
break;
}
case RANGE_CURSE:
EffectUtil.Fear.curse(owner, target);
break;
case MAGIC_CHAIN:
EffectUtil.Fear.magicChain(owner, target);
break;
case FEAR_STRIKE:
event.setDamage(EffectUtil.Fear.fearStrike(owner, target, event.getDamage(), WG));
break;
case FEAR_BOMB:
EffectUtil.Fear.fearBomb(owner, target, WG);
break;
}
}
}
if (session.canSpec(SpecType.UNLEASHED)) {
if (ItemUtil.hasUnleashedSword(owner)) {
used = callSpec(owner, target, 11, 17);
if (used == null) return;
session.updateSpec(SpecType.UNLEASHED);
switch (used) {
case BLIND:
EffectUtil.Unleashed.blind(owner, target);
break;
case HEALING_LIGHT:
EffectUtil.Unleashed.healingLight(owner, target);
break;
case SPEED:
EffectUtil.Unleashed.speed(owner, target);
break;
case REGEN:
EffectUtil.Unleashed.regen(owner, target);
break;
case DOOM_BLADE:
EffectUtil.Unleashed.doomBlade(owner, target, WG);
break;
case LIFE_LEECH:
EffectUtil.Unleashed.lifeLeech(owner, target);
break;
}
} else if (ItemUtil.hasUnleashedBow(owner) && wasProjectile) {
used = callSpec(owner, target, 18, 20);
if (used == null) return;
session.updateSpec(SpecType.UNLEASHED);
switch (used) {
case HEALING_LIFE_LEECH:
EffectUtil.Unleashed.lifeLeech(owner, target);
break;
case EVIL_FOCUS:
EffectUtil.Unleashed.evilFocus(owner, target, freeze);
break;
}
}
}
}
}
@EventHandler
public void onArrowLand(ProjectileHitEvent event) {
Projectile projectile = event.getEntity();
Entity shooter = projectile.getShooter();
if (shooter != null && shooter instanceof Player) {
Player owner = (Player) shooter;
CustomItemSession session = getSession(owner);
Location targetLoc = event.getEntity().getLocation();
RegionManager mgr = WG != null ? WG.getGlobalRegionManager().get(owner.getWorld()) : null;
if (session.canSpec(SpecType.ANIMAL_BOW)) {
Specs used;
if (ItemUtil.hasBatBow(owner)) {
used = callSpec(owner, targetLoc, Specs.MOB_ATTACK);
if (used == null) return;
session.updateSpec(SpecType.ANIMAL_BOW);
switch (used) {
case MOB_ATTACK:
EffectUtil.Strange.mobBarrage(owner, targetLoc, EntityType.BAT);
break;
}
} else if (ItemUtil.hasChickenBow(owner)) {
used = callSpec(owner, targetLoc, Specs.MOB_ATTACK);
if (used == null) return;
session.updateSpec(SpecType.ANIMAL_BOW);
switch (used) {
case MOB_ATTACK:
EffectUtil.Strange.mobBarrage(owner, targetLoc, EntityType.CHICKEN);
break;
}
}
}
if (!session.canSpec(SpecType.FEAR)) {
if (ItemUtil.hasFearBow(owner)) {
if (!targetLoc.getWorld().isThundering() && targetLoc.getBlock().getLightFromSky() > 0) {
server.getPluginManager().callEvent(new RapidHitEvent(owner));
// Simulate a lightning strike
targetLoc.getWorld().strikeLightningEffect(targetLoc);
for (Entity e : projectile.getNearbyEntities(2, 4, 2)) {
if (!e.isValid() || !(e instanceof LivingEntity)) continue;
// Pig Zombie
if (e instanceof Pig) {
e.getWorld().spawnEntity(e.getLocation(), EntityType.PIG_ZOMBIE);
e.remove();
continue;
}
// Creeper
if (e instanceof Creeper) {
((Creeper) e).setPowered(true);
}
// Player
if (mgr != null && e instanceof Player) {
ApplicableRegionSet app = mgr.getApplicableRegions(e.getLocation());
if (!app.allows(DefaultFlag.PVP)) continue;
}
((LivingEntity) e).damage(5, owner);
}
}
}
}
}
}
@EventHandler
public void onArrowTick(ProjectileTickEvent event) {
Entity shooter = event.getEntity().getShooter();
if (shooter != null && shooter instanceof Player) {
final Location location = event.getEntity().getLocation();
if (ItemUtil.hasBatBow((Player) shooter)) {
if (!ChanceUtil.getChance(5)) return;
server.getScheduler().runTaskLater(inst, new Runnable() {
@Override
public void run() {
final Bat bat = (Bat) location.getWorld().spawnEntity(location, EntityType.BAT);
server.getScheduler().runTaskLater(inst, new Runnable() {
@Override
public void run() {
if (bat.isValid()) {
bat.remove();
for (int i = 0; i < 20; i++) {
bat.getWorld().playEffect(bat.getLocation(), Effect.SMOKE, 0);
}
}
}
}, 20 * 3);
}
}, 3);
} else if (ItemUtil.hasChickenBow((Player) shooter)) {
if (!ChanceUtil.getChance(5)) return;
server.getScheduler().runTaskLater(inst, new Runnable() {
@Override
public void run() {
final Chicken chicken = (Chicken) location.getWorld().spawnEntity(location, EntityType.CHICKEN);
server.getScheduler().runTaskLater(inst, new Runnable() {
@Override
public void run() {
if (chicken.isValid()) {
chicken.remove();
for (int i = 0; i < 20; i++) {
chicken.getWorld().playEffect(chicken.getLocation(), Effect.SMOKE, 0);
}
}
}
}, 20 * 3);
}
}, 3);
}
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerInteract(PlayerInteractEvent event) {
Player player = event.getPlayer();
ItemStack itemStack = event.getItem();
if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK) && handleRightClick(player, event.getClickedBlock().getLocation(), itemStack)) {
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
Player player = event.getPlayer();
ItemStack itemStack = player.getItemInHand();
if (handleRightClick(player, event.getRightClicked().getLocation(), itemStack)) {
event.setCancelled(true);
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerBucketFill(PlayerBucketFillEvent event) {
Player player = event.getPlayer();
ItemStack itemStack = player.getItemInHand();
if (handleRightClick(player, event.getBlockClicked().getLocation(), itemStack)) {
event.setCancelled(true);
}
//noinspection deprecation
player.updateInventory();
}
public boolean handleRightClick(final Player player, Location location, ItemStack itemStack) {
if (admin.isAdmin(player)) return false;
final long currentTime = System.currentTimeMillis();
if (ItemUtil.matchesFilter(itemStack, ChatColor.DARK_PURPLE + "Magic Bucket")) {
player.setAllowFlight(!player.getAllowFlight());
if (player.getAllowFlight()) {
player.setFlySpeed(.4F);
antiCheat.exempt(player, CheckType.FLY);
ChatUtil.sendNotice(player, "The bucket glows brightly.");
} else {
player.setFlySpeed(.1F);
antiCheat.unexempt(player, CheckType.FLY);
ChatUtil.sendNotice(player, "The power of the bucket fades.");
}
return true;
} else if (ItemUtil.matchesFilter(itemStack, ChatColor.GOLD + "Pixie Dust")) {
if (player.getAllowFlight()) return false;
if (players.contains(player.getName())) {
ChatUtil.sendError(player, "You need to wait to regain your faith, and trust.");
return false;
}
player.setAllowFlight(true);
player.setFlySpeed(1);
antiCheat.exempt(player, CheckType.FLY);
ChatUtil.sendNotice(player, "You use the Pixie Dust to gain flight.");
IntegratedRunnable integratedRunnable = new IntegratedRunnable() {
@Override
public boolean run(int times) {
// Just get out of here you stupid players who don't exist!
if (!player.isValid()) return true;
if (player.getAllowFlight()) {
int c = ItemUtil.countItemsOfName(player.getInventory().getContents(), ChatColor.GOLD + "Pixie Dust") - 1;
if (c >= 0) {
ItemStack[] itemStacks = ItemUtil.removeItemOfName(player.getInventory().getContents(), ChatColor.GOLD + "Pixie Dust");
player.getInventory().setContents(itemStacks);
int amount = Math.min(c, 64);
while (amount > 0) {
player.getInventory().addItem(ItemUtil.Misc.pixieDust(amount));
c -= amount;
amount = Math.min(c, 64);
}
//noinspection deprecation
player.updateInventory();
if (System.currentTimeMillis() >= currentTime + 13000) {
ChatUtil.sendNotice(player, "You use some more Pixie Dust to keep flying.");
}
return false;
}
ChatUtil.sendWarning(player, "The effects of the Pixie Dust are about to wear off!");
}
return true;
}
@Override
public void end() {
if (player.isValid()) {
if (player.getAllowFlight()) {
ChatUtil.sendNotice(player, "You are no longer influenced by the Pixie Dust.");
antiCheat.unexempt(player, CheckType.FLY);
}
player.setFallDistance(0);
player.setAllowFlight(false);
player.setFlySpeed(.1F);
}
}
};
TimedRunnable runnable = new TimedRunnable(integratedRunnable, 1);
BukkitTask task = server.getScheduler().runTaskTimer(inst, runnable, 0, 20 * 15);
runnable.setTask(task);
return true;
}
return false;
}
@EventHandler(ignoreCancelled = true)
public void onPlayerSneak(PlayerToggleSneakEvent event) {
Player player = event.getPlayer();
if (event.isSneaking() && player.getAllowFlight() && player.isOnGround() && !admin.isAdmin(player)) {
if (!ItemUtil.findItemOfName(player.getInventory().getContents(), ChatColor.GOLD + "Pixie Dust")) return;
player.setAllowFlight(false);
antiCheat.unexempt(player, CheckType.FLY);
ChatUtil.sendNotice(player, "You are no longer influenced by the Pixie Dust.");
final String playerName = player.getName();
players.add(playerName);
server.getScheduler().runTaskLater(inst, new Runnable() {
@Override
public void run() {
players.remove(playerName);
}
}, 20 * 30);
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerDropItem(PlayerDropItemEvent event) {
final Player player = event.getPlayer();
ItemStack itemStack = event.getItemDrop().getItemStack();
if (ItemUtil.matchesFilter(itemStack, ChatColor.DARK_PURPLE + "Magic Bucket")) {
server.getScheduler().runTaskLater(inst, new Runnable() {
@Override
public void run() {
ItemStack[] contents = player.getInventory().getContents();
if (!ItemUtil.findItemOfName(contents, ChatColor.DARK_PURPLE + "Magic Bucket")) {
if (player.getAllowFlight()) {
ChatUtil.sendNotice(player, "The power of the bucket fades.");
}
player.setAllowFlight(false);
antiCheat.unexempt(player, CheckType.FLY);
}
}
}, 1);
}
}
@EventHandler(ignoreCancelled = true)
public void onClick(InventoryClickEvent event) {
if (!(event.getWhoClicked() instanceof Player)) return;
Player player = (Player) event.getWhoClicked();
ItemStack currentItem = event.getCurrentItem();
ItemStack cursorItem = event.getCursor();
InventoryType type = event.getInventory().getType();
InventoryAction action = event.getAction();
if (type.equals(InventoryType.ANVIL)) {
if (action.equals(InventoryAction.NOTHING)) return;
int rawSlot = event.getRawSlot();
if (rawSlot < 2) {
if (InventoryUtil.getPlaceActions().contains(action) && ItemUtil.isNamed(cursorItem)) {
boolean isCustomItem = ItemUtil.isAuthenticCustomItem(cursorItem.getItemMeta().getDisplayName());
if (!isCustomItem) return;
event.setResult(Event.Result.DENY);
ChatUtil.sendError(player, "You cannot place that here.");
}
} else if (rawSlot == 2) {
if (InventoryUtil.getPickUpActions().contains(action) && ItemUtil.isNamed(currentItem)) {
boolean isCustomItem = ItemUtil.isAuthenticCustomItem(currentItem.getItemMeta().getDisplayName());
if (!isCustomItem) return;
event.setResult(Event.Result.DENY);
ChatUtil.sendError(player, "You cannot name this item that name.");
}
}
}
}
@EventHandler(ignoreCancelled = true)
public void onPlayerDrag(InventoryDragEvent event) {
if (!(event.getWhoClicked() instanceof Player)) return;
if (event.getInventory().getType().equals(InventoryType.ANVIL)) {
for (int i : event.getRawSlots()) {
if (i + 1 <= event.getInventory().getSize()) {
event.setResult(Event.Result.DENY);
return;
}
}
}
}
@EventHandler(ignoreCancelled = true)
public void onClose(InventoryCloseEvent event) {
Player player = (Player) event.getPlayer();
if (!player.getAllowFlight()) return;
ItemStack[] chestContents = event.getInventory().getContents();
if (!ItemUtil.findItemOfName(chestContents, ChatColor.DARK_PURPLE + "Magic Bucket")) return;
ItemStack[] contents = player.getInventory().getContents();
if (!ItemUtil.findItemOfName(contents, ChatColor.DARK_PURPLE + "Magic Bucket")) {
if (player.getAllowFlight()) {
ChatUtil.sendNotice(player, "The power of the bucket fades.");
}
player.setAllowFlight(false);
antiCheat.unexempt(player, CheckType.FLY);
}
}
@EventHandler(priority = EventPriority.LOW)
public void onPlayerDeath(PlayerDeathEvent event) {
Player player = event.getEntity();
ItemStack[] drops = event.getDrops().toArray(new ItemStack[event.getDrops().size()]);
if (ItemUtil.findItemOfName(drops, ChatColor.DARK_PURPLE + "Magic Bucket")) {
if (player.getAllowFlight()) {
ChatUtil.sendNotice(player, "The power of the bucket fades.");
}
player.setAllowFlight(false);
antiCheat.unexempt(player, CheckType.FLY);
}
getSession(player).addDeathPoint(player.getLocation());
}
@EventHandler(ignoreCancelled = true)
public void onConsume(PlayerItemConsumeEvent event) {
Player player = event.getPlayer();
ItemStack stack = event.getItem();
if (ItemUtil.matchesFilter(stack, ChatColor.BLUE + "God Fish")) {
player.chat("The fish flow within me!");
new HulkFX().add(player);
} else if (ItemUtil.matchesFilter(stack, ChatColor.DARK_RED + "Potion of Restitution")) {
Location lastLoc = getSession(player).getRecentDeathPoint();
if (lastLoc != null) {
player.teleport(lastLoc);
}
}
}
@EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
public void onXPPickUp(PlayerExpChangeEvent event) {
Player player = event.getPlayer();
boolean hasCrown = ItemUtil.matchesFilter(player.getInventory().getHelmet(), ChatColor.GOLD + "Ancient Crown");
int exp = event.getAmount();
if (hasCrown) {
exp *= 2;
}
if (ItemUtil.hasAncientArmour(player)) {
ItemStack[] armour = player.getInventory().getArmorContents();
ItemStack is = armour[ChanceUtil.getRandom(armour.length) - 1];
if (exp > is.getDurability()) {
exp -= is.getDurability();
is.setDurability((short) 0);
} else {
is.setDurability((short) (is.getDurability() - exp));
exp = 0;
}
player.getInventory().setArmorContents(armour);
event.setAmount(exp);
} else if (hasCrown) {
event.setAmount(exp);
}
}
@EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST)
public void onItemPickup(PlayerPickupItemEvent event) {
final Player player = event.getPlayer();
ItemStack itemStack = event.getItem().getItemStack();
if (itemStack.getTypeId() == ItemID.GOLD_BAR || itemStack.getTypeId() == ItemID.GOLD_NUGGET) {
ItemStack[] inventoryContents = player.getInventory().getContents();
ItemStack[] armorContents = player.getInventory().getArmorContents();
if (!(ItemUtil.findItemOfName(inventoryContents, ChatColor.AQUA + "Imbued Crystal")
|| ItemUtil.findItemOfName(armorContents, ChatColor.GOLD + "Ancient Crown"))) {
return;
}
server.getScheduler().runTaskLater(inst, new Runnable() {
@Override
public void run() {
int nugget = ItemUtil.countItemsOfType(player.getInventory().getContents(), ItemID.GOLD_NUGGET);
while (nugget / 9 > 0 && player.getInventory().firstEmpty() != -1) {
player.getInventory().removeItem(new ItemStack(ItemID.GOLD_NUGGET, 9));
player.getInventory().addItem(new ItemStack(ItemID.GOLD_BAR));
nugget -= 9;
}
int bar = ItemUtil.countItemsOfType(player.getInventory().getContents(), ItemID.GOLD_BAR);
while (bar / 9 > 0 && player.getInventory().firstEmpty() != -1) {
player.getInventory().removeItem(new ItemStack(ItemID.GOLD_BAR, 9));
player.getInventory().addItem(new ItemStack(BlockID.GOLD_BLOCK));
bar -= 9;
}
//noinspection deprecation
player.updateInventory();
}
}, 1);
}
}
@EventHandler(priority = EventPriority.HIGHEST)
public void onEntityDeath(EntityDeathEvent event) {
LivingEntity damaged = event.getEntity();
Player player = damaged.getKiller();
if (player != null) {
World w = player.getWorld();
Location pLocation = player.getLocation();
List<ItemStack> drops = event.getDrops();
if (drops.size() > 0) {
if (ItemUtil.hasUnleashedBow(player) || ItemUtil.hasMasterBow(player) && !(damaged instanceof Player)) {
for (ItemStack is : ItemUtil.clone(drops.toArray(new ItemStack[drops.size()]))) {
if (is != null) w.dropItemNaturally(pLocation, is);
}
drops.clear();
ChatUtil.sendNotice(player, "Your Bow releases a bright flash.");
}
}
}
}
public static class CustomItemSession extends PersistentSession {
private static final long MAX_AGE = TimeUnit.DAYS.toMillis(3);
private HashMap<SpecType, Long> specMap = new HashMap<>();
private LinkedList<Location> recentDeathLocations = new LinkedList<>();
protected CustomItemSession() {
super(MAX_AGE);
}
public void updateSpec(SpecType type) {
specMap.put(type, System.currentTimeMillis());
}
public boolean canSpec(SpecType type) {
return !specMap.containsKey(type) || System.currentTimeMillis() - specMap.get(type) >= type.getDelay();
}
public void addDeathPoint(Location deathPoint) {
recentDeathLocations.add(0, deathPoint.clone());
while (recentDeathLocations.size() > 5) {
recentDeathLocations.pollLast();
}
}
public Location getRecentDeathPoint() {
return recentDeathLocations.poll();
}
}
public enum SpecType {
FEAR(3800),
UNLEASHED(3800),
ANIMAL_BOW(15000);
private final long delay;
private SpecType(long delay) {
this.delay = delay;
}
public long getDelay() {
return delay;
}
}
}
|
package com.soasta.jenkins;
import hudson.AbortException;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.JDK;
import hudson.tasks.Builder;
import hudson.util.ArgumentListBuilder;
import hudson.util.FormValidation;
import hudson.util.QuotedStringTokenizer;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import java.io.IOException;
/**
* @author Kohsuke Kawaguchi
*/
public class MakeAppTouchTestable extends Builder {
/**
* URL of {@link CloudTestServer}.
*/
private final String url;
private final String projectFile,target;
private final String launchURL;
private final boolean backupModifiedFiles;
private final String additionalOptions;
@DataBoundConstructor
public MakeAppTouchTestable(String url, String projectFile, String target, String launchURL, boolean backupModifiedFiles, String additionalOptions) {
this.url = url;
this.projectFile = projectFile;
this.target = target;
this.launchURL = launchURL;
this.backupModifiedFiles = backupModifiedFiles;
this.additionalOptions = additionalOptions;
}
public String getUrl() {
return url;
}
public String getProjectFile() {
return projectFile;
}
public String getTarget() {
return target;
}
public String getLaunchURL() {
return launchURL;
}
public boolean getBackupModifiedFiles() {
return backupModifiedFiles;
}
public String getAdditionalOptions() {
return additionalOptions;
}
public CloudTestServer getServer() {
return CloudTestServer.get(url);
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
ArgumentListBuilder args = new ArgumentListBuilder();
JDK java = build.getProject().getJDK();
if (java!=null)
args.add(java.getHome()+"/bin/java");
else
args.add("java");
CloudTestServer s = getServer();
if (s==null)
throw new AbortException("No TouchTest server is configured in the system configuration.");
EnvVars envs = build.getEnvironment(listener);
FilePath path = new MakeAppTouchTestableInstaller(s).performInstallation(build.getBuiltOn(), listener);
args.add("-jar").add(path.child("MakeAppTouchTestable.jar"))
.add("-overwriteapp")
.add("-project", envs.expand(projectFile))
.add("-url").add(s.getUrl())
.add("-username",s.getUsername())
.add("-password").addMasked(s.getPassword().getPlainText());
if (target!=null && !target.trim().isEmpty())
args.add("-target", envs.expand(target));
if (launchURL!=null && !launchURL.trim().isEmpty())
args.add("-launchURL", envs.expand(launchURL));
if (!backupModifiedFiles)
args.add("-nobackup");
args.add(new QuotedStringTokenizer(envs.expand(additionalOptions)).toArray());
int r = launcher.launch().cmds(args).pwd(build.getWorkspace()).stdout(listener).join();
return r==0;
}
@Extension
public static class DescriptorImpl extends AbstractCloudTestBuilderDescriptor {
@Override
public String getDisplayName() {
return "Make App TouchTestable";
}
public FormValidation doCheckProjectFile(@AncestorInPath AbstractProject project, @QueryParameter String value) throws IOException {
if (value == null || value.trim().isEmpty()) {
return FormValidation.error("Project directory is required.");
} else {
// Make sure the directory exists.
return FilePath.validateFileMask(project.getSomeWorkspace(), value);
}
}
}
}
|
package com.strider.datadefender;
import static java.lang.Double.parseDouble;
import static org.apache.log4j.Logger.getLogger;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Arrays;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.collections.ListUtils;
import org.apache.log4j.Logger;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.SAXException;
import opennlp.tools.util.Span;
import com.strider.datadefender.file.metadata.FileMatchMetaData;
import com.strider.datadefender.utils.CommonUtils;
import java.util.Collections;
/**
*
* @author Armenak Grigoryan
*/
public class FileDiscoverer extends Discoverer {
private static final Logger log = getLogger(FileDiscoverer.class);
private static String[] modelList;
protected List<FileMatchMetaData> fileMatches;
@SuppressWarnings("unchecked")
public List<FileMatchMetaData> discover(final Properties dataDiscoveryProperties)
throws AnonymizerException, IOException, SAXException, TikaException {
log.info("Data discovery in process");
// Get the probability threshold from property file
final double probabilityThreshold = parseDouble(dataDiscoveryProperties.getProperty("probability_threshold"));
log.info("Probability threshold [" + probabilityThreshold + "]");
// Get list of models used in data discovery
final String models = dataDiscoveryProperties.getProperty("models");
modelList = models.split(",");
log.info("Model list [" + Arrays.toString(modelList) + "]");
List<FileMatchMetaData> finalList = new ArrayList<>();
for (String model: modelList) {
log.info("********************************");
log.info("Processing model " + model);
log.info("********************************");
final Model modelPerson = createModel(dataDiscoveryProperties, model);
fileMatches = discoverAgainstSingleModel(dataDiscoveryProperties, modelPerson, probabilityThreshold);
finalList = ListUtils.union(finalList, fileMatches);
}
final DecimalFormat decimalFormat = new DecimalFormat("
log.info("List of suspects:");
log.info(String.format("%20s %20s %20s %20s", "Table*", "Column*", "Probability*", "Model*"));
for(final FileMatchMetaData data: finalList) {
final String probability = decimalFormat.format(data.getAverageProbability());
final String result = String.format("%20s %20s %20s %20s", data.getDirectory(), data.getFileName(), probability, data.getModel());
log.info(result);
}
return Collections.unmodifiableList(fileMatches);
}
private List<FileMatchMetaData> discoverAgainstSingleModel(final Properties fileDiscoveryProperties, final Model model, final double probabilityThreshold)
throws AnonymizerException, IOException, SAXException, TikaException {
// Start running NLP algorithms for each column and collect percentage
fileMatches = new ArrayList<>();
String[] directoryList = null;
String[] exclusionList = null;
final String directories = fileDiscoveryProperties.getProperty("directories");
final String exclusions = fileDiscoveryProperties.getProperty("exclusions");
directoryList = directories.split(",");
exclusionList = exclusions.split(",");
// Let's iterate over directories
File node;
Metadata metadata;
List<Probability> probabilityList;
for (final String directory: directoryList) {
node = new File(directory);
if (node.isDirectory()) {
final String[] files = node.list();
for (final String file: files) {
// Detect file type
log.info("Analyzing " + directory + "/" + file);
// Detect file extenstion
final String ext = CommonUtils.getFileExtension(new File(directory + "/" + file));
log.info("Extension " + ext);
if (Arrays.asList(exclusionList).contains(ext)) {
log.info("Extention " + ext + " in in exclusion list");
continue;
}
final BodyContentHandler handler = new BodyContentHandler(-1);
final AutoDetectParser parser = new AutoDetectParser();
metadata = new Metadata();
String handlerString = "";
try {
final InputStream stream = new FileInputStream(directory + "/" + file);
if (stream != null) {
parser.parse(stream, handler, metadata);
handlerString = handler.toString();
}
}
catch (IOException e) {
log.info("Unable to read " + directory + "/" + file + ". Ignoring...");
}
log.debug("Content: " + handlerString);
final String tokens[] = model.getTokenizer().tokenize(handler.toString());
final Span nameSpans[] = model.getNameFinder().find(tokens);
final double[] spanProbs = model.getNameFinder().probs(nameSpans);
//display names
probabilityList = new ArrayList<>();
for( int i = 0; i < nameSpans.length; i++) {
log.info("Span: "+nameSpans[i].toString());
log.info("Covered text is: "+tokens[nameSpans[i].getStart()]);
log.info("Probability is: "+spanProbs[i]);
probabilityList.add(new Probability(tokens[nameSpans[i].getStart()], spanProbs[i]));
}
model.getNameFinder().clearAdaptiveData();
final double averageProbability = calculateAverage(probabilityList);
if ((averageProbability >= probabilityThreshold)) {
final FileMatchMetaData result = new FileMatchMetaData(directory, file);
result.setAverageProbability(averageProbability);
result.setModel(model.getName());
fileMatches.add(result);
}
}
}
}
return fileMatches;
}
}
|
package com.strider.datadefender;
import static java.lang.Double.parseDouble;
import static org.apache.log4j.Logger.getLogger;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Arrays;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.collections.ListUtils;
import org.apache.log4j.Logger;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.SAXException;
import opennlp.tools.util.Span;
import com.strider.datadefender.file.metadata.FileMatchMetaData;
/**
*
* @author Armenak Grigoryan
*/
public class FileDiscoverer extends Discoverer {
private static final Logger log = getLogger(FileDiscoverer.class);
private static String[] modelList;
protected List<FileMatchMetaData> fileMatches;
public List<FileMatchMetaData> discover(final Properties dataDiscoveryProperties)
throws AnonymizerException, IOException, SAXException, TikaException {
log.info("Data discovery in process");
// Get the probability threshold from property file
final double probabilityThreshold = parseDouble(dataDiscoveryProperties.getProperty("probability_threshold"));
log.info("Probability threshold [" + probabilityThreshold + "]");
// Get list of models used in data discovery
final String models = dataDiscoveryProperties.getProperty("models");
modelList = models.split(",");
log.info("Model list [" + Arrays.toString(modelList) + "]");
List<FileMatchMetaData> finalList = new ArrayList<>();
for (String model: modelList) {
log.info("********************************");
log.info("Processing model " + model);
log.info("********************************");
final Model modelPerson = createModel(dataDiscoveryProperties, model);
fileMatches = discoverAgainstSingleModel(dataDiscoveryProperties, modelPerson, probabilityThreshold);
finalList = ListUtils.union(finalList, fileMatches);
}
final DecimalFormat decimalFormat = new DecimalFormat("
log.info("List of suspects:");
log.info(String.format("%20s %20s %20s %20s", "Table*", "Column*", "Probability*", "Model*"));
for(final FileMatchMetaData data: finalList) {
final String probability = decimalFormat.format(data.getAverageProbability());
final String result = String.format("%20s %20s %20s %20s", data.getDirectory(), data.getFileName(), probability, data.getModel());
log.info(result);
}
return fileMatches;
}
private List<FileMatchMetaData> discoverAgainstSingleModel(final Properties fileDiscoveryProperties, final Model model, final double probabilityThreshold)
throws AnonymizerException, IOException, SAXException, TikaException {
// Start running NLP algorithms for each column and collect percentage
fileMatches = new ArrayList<>();
String[] directoryList = null;
final String directories = fileDiscoveryProperties.getProperty("directories");
directoryList = directories.split(",");
// Let's iterate over directories
File node;
Metadata metadata;
List<Double> probabilityList;
for (final String directory: directoryList) {
node = new File(directory);
if (node.isDirectory()) {
final String[] files = node.list();
for (final String file: files) {
// Detect file type
log.info("Analyzing " + directory + "/" + file);
final BodyContentHandler handler = new BodyContentHandler(-1);
final AutoDetectParser parser = new AutoDetectParser();
metadata = new Metadata();
String handlerString = "";
try (InputStream stream = new FileInputStream(directory + "/" + file)) {
if (stream != null) {
parser.parse(stream, handler, metadata);
handlerString = handler.toString();
}
}
log.debug("Content: " + handlerString);
final String tokens[] = model.getTokenizer().tokenize(handler.toString());
final Span nameSpans[] = model.getNameFinder().find(tokens);
final double[] spanProbs = model.getNameFinder().probs(nameSpans);
//display names
probabilityList = new ArrayList<>();
for( int i = 0; i < nameSpans.length; i++) {
log.info("Span: "+nameSpans[i].toString());
log.info("Covered text is: "+tokens[nameSpans[i].getStart()]);
log.info("Probability is: "+spanProbs[i]);
probabilityList.add(spanProbs[i]);
}
model.getNameFinder().clearAdaptiveData();
final double averageProbability = calculateAverage(probabilityList);
if ((averageProbability >= probabilityThreshold)) {
final FileMatchMetaData result = new FileMatchMetaData(directory, file);
result.setAverageProbability(averageProbability);
result.setModel(model.getName());
fileMatches.add(result);
}
}
}
}
return fileMatches;
}
}
|
import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;
import com.yiji.falcon.agent.jmx.vo.JMXConnectionInfo;
import com.yiji.falcon.agent.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.management.MBeanServerConnection;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
public abstract class JMXConnection {
private static final Logger log = LoggerFactory.getLogger(JMXConnection.class);
private static final Map<String,JMXConnectionInfo> connectLibrary = new HashMap<>();//JMX
private static final Map<String,Integer> serverConnectCount = new HashMap<>();//JMX
private static List<JMXConnector> closeRecord = new ArrayList<>();
/**
* ,JMX
* @param serverName
* @return
*/
public static int getServerConnectCount(String serverName){
return serverConnectCount.get(serverName);
}
/**
* JMX
* @param serverName
* @return
*/
public static boolean hasJMXServerInLocal(String serverName){
if(!StringUtils.isEmpty(serverName)){
List<VirtualMachineDescriptor> vms = VirtualMachine.list();
for (VirtualMachineDescriptor desc : vms) {
if(desc.displayName().contains(serverName)){
return true;
}
}
}
return false;
}
/**
* JMX
* @param serverName (main)
* @return
* null :
* @throws IOException
*/
public synchronized List<JMXConnectionInfo> getMBeanConnection(String serverName){
if(StringUtils.isEmpty(serverName)){
log.error("JMXserverName");
}
if(this.getClass() == JMXConnection.class){
log.warn(": {} {}",JMXConnection.class.getName(),"getMBeanConnection()");
}
List<JMXConnectionInfo> connections = connectLibrary.entrySet().
stream().
filter(entry -> entry.getKey().contains(serverName)).
map(Map.Entry::getValue).
collect(Collectors.toList());
if(connections.isEmpty()){
int count = 0;
List<VirtualMachineDescriptor> vms = VirtualMachine.list();
for (VirtualMachineDescriptor desc : vms) {
if(desc.displayName().contains(serverName)){
String connectorAddress = new AbstractJmxCommand().findJMXUrlByProcessId(Integer.parseInt(desc.id()));
if (connectorAddress == null) {
log.error(" {} JMXURL",desc.displayName());
continue;
}
try {
JMXServiceURL url = new JMXServiceURL(connectorAddress);
JMXConnector connector = JMXConnectorFactory.connect(url);
connections.add(initJMXConnectionInfo(connector,serverName,desc, UUID.randomUUID().toString()));
count++;
} catch (IOException e) {
log.error("JMX ",e);
}
}
}
if(count > 0){
serverConnectCount.put(serverName,count);
}
}
return connections;
}
/**
* jmx
* @param serverName
* jmx
* @throws IOException
*/
public synchronized void resetMBeanConnection(String serverName) {
if(StringUtils.isEmpty(serverName)){
log.error("JMXserverName");
}
List<VirtualMachineDescriptor> vms = VirtualMachine.list();
//JMXVirtualMachineDescriptor
List<VirtualMachineDescriptor> targetDesc = new ArrayList<>();
for (VirtualMachineDescriptor desc : vms) {
if(desc.displayName().contains(serverName)){
targetDesc.add(desc);
}
}
//targetJMX,
if(targetDesc.size() >= getServerConnectCount(serverName)){
List<String> removeKey = new ArrayList<>();
for (String key : connectLibrary.keySet()) {
if(key.contains(serverName)){
removeKey.add(key);
}
}
for (String key : removeKey) {
connectLibrary.remove(key);
}
int count = 0;
for (VirtualMachineDescriptor desc : targetDesc) {
String connectorAddress = new AbstractJmxCommand().findJMXUrlByProcessId(Integer.parseInt(desc.id()));
if (connectorAddress == null) {
log.error("{}JMXURL",serverName);
continue;
}
try {
JMXServiceURL url = new JMXServiceURL(connectorAddress);
JMXConnector connector = JMXConnectorFactory.connect(url);
initJMXConnectionInfo(connector,serverName,desc,UUID.randomUUID().toString());
count++;
} catch (IOException e) {
log.error("JMX ",e);
}
}
serverConnectCount.put(serverName,count);
}
}
/**
* JMXConnectionInfo
* @param connector
* @param serverName
* @param desc
* @param keyId
* @return
* @throws IOException
*/
private JMXConnectionInfo initJMXConnectionInfo(JMXConnector connector,String serverName,VirtualMachineDescriptor desc,String keyId) throws IOException {
JMXConnectionInfo jmxConnectionInfo = new JMXConnectionInfo();
jmxConnectionInfo.setCacheKeyId(keyId);
jmxConnectionInfo.setConnectionServerName(serverName);
jmxConnectionInfo.setConnectionQualifiedServerName(desc.displayName());
jmxConnectionInfo.setmBeanServerConnection(connector.getMBeanServerConnection());
jmxConnectionInfo.setName(getJmxConnectionName(connector.getMBeanServerConnection(),Integer.parseInt(desc.id())));
jmxConnectionInfo.setValid(true);
jmxConnectionInfo.setPid(Integer.parseInt(desc.id()));
connectLibrary.put(serverName + keyId,jmxConnectionInfo);
closeRecord.add(connector);
return jmxConnectionInfo;
}
/**
*
* @throws IOException
*/
public static void close() {
for (JMXConnector jmxConnector : closeRecord) {
try {
jmxConnector.close();
} catch (IOException e) {
log.warn("",e);
}
}
}
/**
*
* @param mBeanServerConnection
* @return
*/
public abstract String getJmxConnectionName(MBeanServerConnection mBeanServerConnection,int pid);
}
|
package cz.diribet.aqdef.model;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import org.apache.commons.collections4.MapUtils;
import cz.diribet.aqdef.KKey;
import cz.diribet.aqdef.parser.AqdefParser;
import cz.diribet.aqdef.writer.AqdefWriter;
/**
* Object model of AQDEF content.
* <p>
* Provides methods to
* <ul>
* <li>manipulate with the content ({@code getXXX}, {@code putXXX},
* {@code removeXXX}, {@code filterXXX})</li>
* <li>iterate through the content {@code forEachXXX}</li>
* </ul>
* </p>
* <p>
* Use {@link AqdefParser} to read AQDEF content and {@link AqdefWriter} to
* write this object model as AQDEF content.
* </p>
*
* @author Vlastimil Dolejs
*
* @see AqdefParser
* @see AqdefWriter
*/
public class AqdefObjectModel {
/**
* Removes part entries with the given index.
* Characteristic and value entries of given part are preserved!
*
* @param index
*/
private PartEntries removePartEntries(PartIndex index) {
return partEntries.remove(index);
}
public void putCharacteristicEntry(KKey key, CharacteristicIndex characteristicIndex, Object value) {
if (value == null) {
return;
}
CharacteristicEntries entriesWithIndex = computeCharacteristicEntriesIfAbsent(characteristicIndex);
entriesWithIndex.put(key, value);
}
public void putCharacteristicEntries(CharacteristicEntries newCharacteristicEntries) {
CharacteristicIndex characteristicIndex = newCharacteristicEntries.getIndex();
CharacteristicEntries entriesWithIndex = computeCharacteristicEntriesIfAbsent(characteristicIndex);
entriesWithIndex.putAll(newCharacteristicEntries, true);
}
private CharacteristicEntries computeCharacteristicEntriesIfAbsent(CharacteristicIndex characteristicIndex) {
PartIndex partIndex = characteristicIndex.getPartIndex();
Map<CharacteristicIndex, CharacteristicEntries> entriesWithPartIndex =
characteristicEntries.computeIfAbsent(partIndex, i -> newEntriesMap());
return entriesWithPartIndex.computeIfAbsent(characteristicIndex, CharacteristicEntries::new);
}
/**
* Removes characteristic entries with the given index.
* Value entries of the given characteristic are preserved!
*
* @param index
* @return
*/
private CharacteristicEntries removeCharacteristicEntries(CharacteristicIndex index) {
Map<CharacteristicIndex, CharacteristicEntries> entriesWithPartIndex = characteristicEntries.get(index.getPartIndex());
if (entriesWithPartIndex != null) {
CharacteristicEntries removedEntries = entriesWithPartIndex.remove(index);
// cleanup empty entries
if (entriesWithPartIndex.isEmpty()) {
characteristicEntries.remove(index.getPartIndex());
}
return removedEntries;
}
return null;
}
public void putGroupEntry(KKey key, GroupIndex groupIndex, Object value) {
if (value == null) {
return;
}
PartIndex partIndex = groupIndex.getPartIndex();
Map<GroupIndex, GroupEntries> entriesWithPartIndex =
groupEntries.computeIfAbsent(partIndex, i -> newEntriesMap());
GroupEntries entriesWithIndex =
entriesWithPartIndex.computeIfAbsent(groupIndex, GroupEntries::new);
entriesWithIndex.put(key, value);
}
public void putValueEntry(KKey key, ValueIndex valueIndex, Object value) {
if (value == null) {
return;
}
ValueEntries entriesWithIndex = computeValueEntriesIfAbsent(valueIndex);
entriesWithIndex.put(key, value);
}
public void putValueEntries(ValueEntries newValueEntries) {
ValueIndex valueIndex = newValueEntries.getIndex();
ValueEntries entriesWithIndex = computeValueEntriesIfAbsent(valueIndex);
entriesWithIndex.putAll(newValueEntries, true);
}
private ValueEntries computeValueEntriesIfAbsent(ValueIndex valueIndex) {
PartIndex partIndex = valueIndex.getPartIndex();
Map<CharacteristicIndex, Map<ValueIndex, ValueEntries>> entriesWithPartIndex =
valueEntries.computeIfAbsent(partIndex, i -> newEntriesMap());
CharacteristicIndex characteristicIndex = valueIndex.getCharacteristicIndex();
Map<ValueIndex, ValueEntries> entriesWithCharacteristicIndex =
entriesWithPartIndex.computeIfAbsent(characteristicIndex, i -> newEntriesMap());
return entriesWithCharacteristicIndex.computeIfAbsent(valueIndex, ValueEntries::new);
}
/**
* Removes all values of characteristic with the given index.
*
* @param index
* @return
*/
private List<ValueEntries> removeValueEntries(CharacteristicIndex index) {
Map<CharacteristicIndex, Map<ValueIndex, ValueEntries>> entriesWithPartIndex = valueEntries.get(index.getPartIndex());
if (entriesWithPartIndex != null) {
Map<ValueIndex, ValueEntries> removedValueEntries = entriesWithPartIndex.remove(index);
// cleanup empty entries
if (entriesWithPartIndex.isEmpty()) {
valueEntries.remove(index.getPartIndex());
}
if (removedValueEntries != null) {
return new ArrayList<>(removedValueEntries.values());
}
}
return new ArrayList<>();
}
public void putHierarchyEntry(KKey kKey, Integer nodeIndex, Object value) {
hierarchy.putEntry(kKey, nodeIndex, value);
}
/**
* Returns indexes of all parts in this object model.
*
* @return
*/
public List<PartIndex> getPartIndexes() {
return new ArrayList<>(partEntries.keySet());
}
public PartEntries getPartEntries(int index) {
return getPartEntries(PartIndex.of(index));
}
public PartEntries getPartEntries(PartIndex index) {
return partEntries.get(index);
}
/**
* Returns indexes of all characteristics of a part with the given index.
*
* @return
*/
public List<CharacteristicIndex> getCharacteristicIndexes(PartIndex partIndex) {
Map<CharacteristicIndex, CharacteristicEntries> entriesWithPartIndex = characteristicEntries.get(partIndex);
if (entriesWithPartIndex == null) {
return new ArrayList<>();
} else {
return new ArrayList<>(entriesWithPartIndex.keySet());
}
}
public CharacteristicEntries getCharacteristicEntries(int partIndex, int characteristicIndex) {
return getCharacteristicEntries(CharacteristicIndex.of(PartIndex.of(partIndex), characteristicIndex));
}
public CharacteristicEntries getCharacteristicEntries(CharacteristicIndex characteristicIndex) {
Map<CharacteristicIndex, CharacteristicEntries> entriesWithPartIndex = characteristicEntries.get(characteristicIndex.getPartIndex());
if (entriesWithPartIndex == null) {
return null;
} else {
return entriesWithPartIndex.get(characteristicIndex);
}
}
/**
* Returns indexes of all values of a characteristics with the given index.
*
* @return
*/
public List<ValueIndex> getValueIndexes(CharacteristicIndex characteristicIndex) {
Map<CharacteristicIndex, Map<ValueIndex, ValueEntries>> entriesWithPartIndex = valueEntries.get(characteristicIndex.getPartIndex());
if (entriesWithPartIndex == null) {
return new ArrayList<>();
} else {
Map<ValueIndex, ValueEntries> entriesWithCharacteristicIndex = entriesWithPartIndex.get(characteristicIndex);
if (entriesWithCharacteristicIndex == null) {
return new ArrayList<>();
} else {
return new ArrayList<>(entriesWithCharacteristicIndex.keySet());
}
}
}
/**
* Returns indexes of all values in this object model.
* @return
*/
public List<ValueIndex> getValueIndexes() {
List<ValueIndex> allValueIndexes = new ArrayList<>();
for (Map<CharacteristicIndex, Map<ValueIndex, ValueEntries>> entriesOfPart : valueEntries.values()) {
for (Map<ValueIndex, ValueEntries> entriesOfCharacteristic : entriesOfPart.values()) {
allValueIndexes.addAll(entriesOfCharacteristic.keySet());
}
}
return allValueIndexes;
}
public ValueEntries getValueEntries(int partIndex, int characteristicIndex, int valueIndex) {
return getValueEntries(ValueIndex.of(CharacteristicIndex.of(PartIndex.of(partIndex), characteristicIndex), valueIndex));
}
public ValueEntries getValueEntries(ValueIndex valueIndex) {
Map<CharacteristicIndex, Map<ValueIndex, ValueEntries>> entriesWithPartIndex = valueEntries.get(valueIndex.getPartIndex());
if (entriesWithPartIndex == null) {
return null;
} else {
Map<ValueIndex, ValueEntries> entriesWithCharacteristicIndex = entriesWithPartIndex.get(valueIndex.getCharacteristicIndex());
if (entriesWithCharacteristicIndex == null) {
return null;
} else {
return entriesWithCharacteristicIndex.get(valueIndex);
}
}
}
public List<ValueEntries> getValueEntries(CharacteristicIndex characteristicIndex) {
Map<CharacteristicIndex, Map<ValueIndex, ValueEntries>> entriesWithPartIndex = valueEntries.get(characteristicIndex.getPartIndex());
if (entriesWithPartIndex == null) {
return new ArrayList<>();
} else {
Map<ValueIndex, ValueEntries> entriesWithCharacteristicIndex = entriesWithPartIndex.get(characteristicIndex);
if (entriesWithCharacteristicIndex == null) {
return new ArrayList<>();
} else {
return new ArrayList<>(entriesWithCharacteristicIndex.values());
}
}
}
public List<ValueSet> getValueSets(PartIndex partIndex) {
Map<CharacteristicIndex, Map<ValueIndex, ValueEntries>> entriesWithPartIndex = valueEntries.get(partIndex);
List<ValueSet> valueSets = new ArrayList<>();
for (Entry<CharacteristicIndex, Map<ValueIndex, ValueEntries>> entriesOfCharacteristic : entriesWithPartIndex.entrySet()) {
CharacteristicIndex characteristicIndex = entriesOfCharacteristic.getKey();
Map<ValueIndex, ValueEntries> valuesOfCharacteristic = entriesOfCharacteristic.getValue();
int counter = 0;
for (Entry<ValueIndex, ValueEntries> valueEntries : valuesOfCharacteristic.entrySet()) {
while (counter >= valueSets.size()) {
valueSets.add(new ValueSet());
}
ValueSet valueSet = valueSets.get(counter);
valueSet.addValueOfCharacteristic(characteristicIndex, valueEntries.getValue());
counter++;
}
}
return valueSets;
}
/**
* Finds part index to which the given characteristic index belongs.
* <p>
* You should call this method only after this {@link AqdefObjectModel} is fully created.
* </p>
*
* @param characteristicIndex
* @return
*/
public PartIndex findPartIndexForCharacteristic(int characteristicIndex) {
for (Map<CharacteristicIndex, CharacteristicEntries> characteristics : characteristicEntries.values()) {
for (CharacteristicIndex characteristic : characteristics.keySet()) {
if (characteristic.getCharacteristicIndex() == characteristicIndex) {
return characteristic.getPartIndex();
}
}
}
return null;
}
public Set<CharacteristicIndex> findCharacteristicIndexesForPart(PartIndex partIndex, CharacteristicOfSinglePartPredicate predicate) {
Set<CharacteristicIndex> characteristicIndexes = new HashSet<>();
Map<CharacteristicIndex, CharacteristicEntries> partCharacteristics = characteristicEntries.get(partIndex);
if (partCharacteristics != null) {
for (CharacteristicEntries entries : partCharacteristics.values()) {
if (predicate.test(entries)) {
characteristicIndexes.add(entries.getIndex());
}
}
}
return characteristicIndexes;
}
/**
* Iterates through all parts
*
* @param consumer
*/
public void forEachPart(PartConsumer consumer) {
partEntries.forEach((partIndex, part) -> {
consumer.accept(part);
});
}
/**
* Iterates through all characteristics of all parts
*
* @param consumer
*/
public void forEachCharacteristic(CharacteristicConsumer consumer) {
partEntries.forEach((partIndex, part) -> {
Map<CharacteristicIndex, CharacteristicEntries> characteristicsOfPart = characteristicEntries.get(part.getIndex());
if (characteristicsOfPart != null) {
characteristicsOfPart.forEach((characteristicIndex, characteristic) -> {
consumer.accept(part, characteristic);
});
}
});
}
/**
* Iterates through all characteristics of the given part. Most of the time it will be used together with {@link #forEachPart(PartConsumer)}.
* <pre>
* model.forEachPart(part -> {
* // do something with the part
*
* model.forEachCharacteristic(part, characteristic -> {
* // do something with the characteristic
* });
* })
* </pre>
* @param part
* @param consumer
*/
public void forEachCharacteristic(PartEntries part, CharacteristicOfSinglePartConsumer consumer) {
Map<CharacteristicIndex, CharacteristicEntries> characteristicsOfPart = characteristicEntries.get(part.getIndex());
if (characteristicsOfPart != null) {
characteristicsOfPart.forEach((characteristicIndex, characteristic) -> {
consumer.accept(characteristic);
});
}
}
/**
* Iterates through all logical groups of all parts
*
* @param consumer
*/
public void forEachGroup(GroupConsumer consumer) {
partEntries.forEach((partIndex, part) -> {
Map<GroupIndex, GroupEntries> groupsOfPart = groupEntries.get(part.getIndex());
if (groupsOfPart != null) {
groupsOfPart.forEach((groupIndex, group) -> {
consumer.accept(part, group);
});
}
});
}
/**
* Iterates through all logical groups of the given part. Similar to {@link #forEachCharacteristic(PartEntries, CharacteristicOfSinglePartConsumer)}
*
* @param part
* @param consumer
*/
public void forEachGroup(PartEntries part, GroupOfSinglePartConsumer consumer) {
Map<GroupIndex, GroupEntries> groupsOfPart = groupEntries.get(part.getIndex());
if (groupsOfPart != null) {
groupsOfPart.forEach((groupIndex, group) -> {
consumer.accept(group);
});
}
}
/**
* Iterates through all values.
*
* @param consumer
*/
public void forEachValue(ValueConsumer consumer) {
partEntries.forEach((partIndex, part) -> {
Map<CharacteristicIndex, CharacteristicEntries> characteristicsOfPart = characteristicEntries.get(part.getIndex());
if (characteristicsOfPart != null) {
characteristicsOfPart.forEach((characteristicIndex, characteristic) -> {
Map<CharacteristicIndex, Map<ValueIndex, ValueEntries>> valuesOfPart = valueEntries.get(part.getIndex());
if (valuesOfPart != null) {
Map<ValueIndex, ValueEntries> values = valuesOfPart.get(characteristic.getIndex());
if (values != null) {
values.forEach((valueIndex, value) -> {
consumer.accept(part, characteristic, value);
});
}
}
});
}
});
}
/**
* Iterates through all values of the given part. Most of the time it will be used together with {@link #forEachPart(PartConsumer)}.
* <pre>
* model.forEachPart(part -> {
* // do something with the part
*
* model.forEachValue(part, (characteristic, value) -> {
* // do something with the value
* });
* })
* </pre>
*
* @param part
* @param consumer
*/
public void forEachValue(PartEntries part, ValueOfSinglePartConsumer consumer) {
Map<CharacteristicIndex, CharacteristicEntries> characteristicsOfPart = characteristicEntries.get(part.getIndex());
if (characteristicsOfPart != null) {
characteristicsOfPart.forEach((characteristicIndex, characteristic) -> {
Map<CharacteristicIndex, Map<ValueIndex, ValueEntries>> valuesOfPart = valueEntries.get(part.getIndex());
if (valuesOfPart != null) {
Map<ValueIndex, ValueEntries> values = valuesOfPart.get(characteristic.getIndex());
if (values != null) {
values.forEach((valueIndex, value) -> {
consumer.accept(characteristic, value);
});
}
}
});
}
}
/**
* Iterates through all values of the given characteristic. Most of the time it will be used together with {@link #forEachCharacteristic(CharacteristicConsumer)}.
* <pre>
* model.forEachCharacteristic(part, characteristic -> {
* // do something with the characteristic
*
* model.forEachValue(part, characteristic, value -> {
* // do something with the value
* });
* })
* </pre>
*
* @param part
* @param characteristic
* @param consumer
*/
public void forEachValue(PartEntries part, CharacteristicEntries characteristic, ValueOfSingleCharacteristicConsumer consumer) {
Map<CharacteristicIndex, Map<ValueIndex, ValueEntries>> valuesOfPart = valueEntries.get(part.getIndex());
if (valuesOfPart != null) {
Map<ValueIndex, ValueEntries> values = valuesOfPart.get(characteristic.getIndex());
if (values != null) {
values.forEach((valueIndex, value) -> {
consumer.accept(value);
});
}
}
}
/**
* Removes all parts that do not match the given predicate.
* If a part is removed it's characteristics and values are also removed.
*
* @param predicate
*/
public void filterParts(PartPredicate predicate) {
Iterator<Map.Entry<PartIndex, PartEntries>> iterator = partEntries.entrySet().iterator();
while (iterator.hasNext()) {
Entry<PartIndex, PartEntries> entry = iterator.next();
PartIndex partIndex = entry.getKey();
PartEntries part = entry.getValue();
if (!predicate.test(part)) {
iterator.remove();
// remove characteristics and values for that part
characteristicEntries.remove(partIndex);
valueEntries.remove(partIndex);
}
}
}
/**
* Removes all characteristics that do not match the given predicate.
* If a characteristic is removed it's values are also removed.
*
* @param predicate
*/
public void filterCharacteristics(CharacteristicPredicate predicate) {
partEntries.forEach((partIndex, part) -> {
Map<CharacteristicIndex, CharacteristicEntries> characteristicsOfPart = characteristicEntries.get(part.getIndex());
if (characteristicsOfPart != null) {
Iterator<Entry<CharacteristicIndex, CharacteristicEntries>> iterator = characteristicsOfPart.entrySet().iterator();
while (iterator.hasNext()) {
Entry<CharacteristicIndex, CharacteristicEntries> entry = iterator.next();
CharacteristicIndex characteristicIndex = entry.getKey();
CharacteristicEntries characteristic = entry.getValue();
if (!predicate.test(part, characteristic)) {
iterator.remove();
// remove values for that characteristic
removeValueEntries(characteristicIndex);
}
}
}
});
}
/**
* Removes all characteristics of the given part that do not match the given predicate.
* If a characteristic is removed it's values are also removed.
*
* @param part
* @param predicate
*/
public void filterCharacteristics(PartEntries part, CharacteristicOfSinglePartPredicate predicate) {
Map<CharacteristicIndex, CharacteristicEntries> characteristicsOfPart = characteristicEntries.get(part.getIndex());
if (characteristicsOfPart != null) {
Iterator<Entry<CharacteristicIndex, CharacteristicEntries>> iterator = characteristicsOfPart.entrySet().iterator();
while (iterator.hasNext()) {
Entry<CharacteristicIndex, CharacteristicEntries> entry = iterator.next();
CharacteristicIndex characteristicIndex = entry.getKey();
CharacteristicEntries characteristic = entry.getValue();
if (!predicate.test(characteristic)) {
iterator.remove();
// remove values for that characteristic
removeValueEntries(characteristicIndex);
}
}
}
}
/**
* Removes all groups that do not match the given predicate.
*
* @param predicate
*/
public void filterGroups(GroupPredicate predicate) {
partEntries.forEach((partIndex, part) -> {
Map<GroupIndex, GroupEntries> groupsOfPart = groupEntries.get(part.getIndex());
if (groupsOfPart != null) {
Iterator<Entry<GroupIndex, GroupEntries>> iterator = groupsOfPart.entrySet().iterator();
while (iterator.hasNext()) {
GroupEntries group = iterator.next().getValue();
if (!predicate.test(part, group)) {
iterator.remove();
}
}
}
});
}
/**
* Removes all groups of the given part that do not match the given predicate.
*
* @param part
* @param predicate
*/
public void filterGroups(PartEntries part, GroupOfSinglePartPredicate predicate) {
Map<GroupIndex, GroupEntries> groupsOfPart = groupEntries.get(part.getIndex());
if (groupsOfPart != null) {
Iterator<Entry<GroupIndex, GroupEntries>> iterator = groupsOfPart.entrySet().iterator();
while (iterator.hasNext()) {
GroupEntries group = iterator.next().getValue();
if (!predicate.test(group)) {
iterator.remove();
}
}
}
}
/**
* Removes all values that do not match the given predicate.
*
* @param predicate
*/
public void filterValues(ValuePredicate predicate) {
partEntries.forEach((partIndex, part) -> {
Map<CharacteristicIndex, CharacteristicEntries> characteristicsOfPart = characteristicEntries.get(part.getIndex());
if (characteristicsOfPart != null) {
characteristicsOfPart.forEach((characteristicIndex, characteristic) -> {
Map<CharacteristicIndex, Map<ValueIndex, ValueEntries>> valuesOfPart = valueEntries.get(part.getIndex());
if (valuesOfPart != null) {
Map<ValueIndex, ValueEntries> values = valuesOfPart.get(characteristic.getIndex());
if (values != null) {
Iterator<Entry<ValueIndex, ValueEntries>> iterator = values.entrySet().iterator();
while (iterator.hasNext()) {
Entry<ValueIndex, ValueEntries> entry = iterator.next();
ValueEntries value = entry.getValue();
if (!predicate.test(part, characteristic, value)) {
iterator.remove();
}
}
}
}
});
}
});
}
/**
* Removes all values of the given part that do not match the given predicate.
*
* @param part
* @param predicate
*/
public void filterValues(PartEntries part, ValueOfSinglePartPredicate predicate) {
Map<CharacteristicIndex, CharacteristicEntries> characteristicsOfPart = characteristicEntries.get(part.getIndex());
if (characteristicsOfPart != null) {
characteristicsOfPart.forEach((characteristicIndex, characteristic) -> {
Map<CharacteristicIndex, Map<ValueIndex, ValueEntries>> valuesOfPart = valueEntries.get(part.getIndex());
if (valuesOfPart != null) {
Map<ValueIndex, ValueEntries> values = valuesOfPart.get(characteristic.getIndex());
if (values != null) {
Iterator<Entry<ValueIndex, ValueEntries>> iterator = values.entrySet().iterator();
while (iterator.hasNext()) {
Entry<ValueIndex, ValueEntries> entry = iterator.next();
ValueEntries value = entry.getValue();
if (!predicate.test(characteristic, value)) {
iterator.remove();
}
}
}
}
});
}
}
/**
* Removes all values of the given characteristic that do not match the given predicate.
*
* @param part
* @param characteristic
* @param predicate
*/
public void filterValues(PartEntries part, CharacteristicEntries characteristic, ValueOfSinglePartPredicate predicate) {
Map<CharacteristicIndex, Map<ValueIndex, ValueEntries>> valuesOfPart = valueEntries.get(part.getIndex());
if (valuesOfPart != null) {
Map<ValueIndex, ValueEntries> values = valuesOfPart.get(characteristic.getIndex());
if (values != null) {
Iterator<Entry<ValueIndex, ValueEntries>> iterator = values.entrySet().iterator();
while (iterator.hasNext()) {
Entry<ValueIndex, ValueEntries> entry = iterator.next();
ValueEntries value = entry.getValue();
if (!predicate.test(characteristic, value)) {
iterator.remove();
}
}
}
}
}
public Object getAnyValueOf(KKey key) {
if (key.isPartLevel()) {
return partEntries.values().stream().findAny().map((entries) -> entries.getValue(key)).orElse(null);
} else if (key.isCharacteristicLevel()) {
return characteristicEntries.values().stream().findAny().map((entriesOfPart) -> {
return entriesOfPart.values().stream().findAny().map((entries) -> entries.getValue(key)).orElse(null);
}).orElse(null);
} else if (key.isGroupLevel()) {
return groupEntries.values().stream().findAny().map((entriesOfPart) -> {
return entriesOfPart.values().stream().findAny().map((entries) -> entries.getValue(key)).orElse(null);
}).orElse(null);
} else if (key.isValueLevel()) {
return valueEntries.values().stream().findAny().map((entriesOfPart) -> {
return entriesOfPart.values().stream().findAny().map((entriesOfCharacteristic) -> {
return entriesOfCharacteristic.values().stream().findAny().map((entries) -> entries.getValue(key)).orElse(null);
}).orElse(null);
}).orElse(null);
} else {
throw new IllegalArgumentException(String.format("Invalid k-key %s. Value can be obtained only for part / characteristic / value keys.", key));
}
}
/**
* Normalize the AQDEF content.
* <ul>
* <li>Apply all /0 K-keys on all parts / characteristics / values and then
* remove them from object model.</li>
* <li>Complement the hierarchy so there are no nodes/characteristics wihout a
* parent part node. This may happen when hierarchy was created from simple
* characteristics grouping (K2030/K2031).</li>
* </ul>
*/
public void normalize() {
// normalize part entries
PartEntries entriesForAllParts = removePartEntries(PartIndex.of(0));
if (MapUtils.isNotEmpty(entriesForAllParts)) {
if (getPartIndexes().isEmpty()) {
// if there are no part entries then /0 entries become /1 entries
PartIndex partIndex = PartIndex.of(1);
partEntries.put(partIndex, entriesForAllParts.withIndex(partIndex));
} else {
// put /0 entries to all existing parts
forEachPart((part) -> {
part.putAll(entriesForAllParts.withIndex(part.getIndex()), false);
});
}
}
// normalize characteristic and value entries
CharacteristicIndex indexForAllCharacteristicsOfAllParts = CharacteristicIndex.of(PartIndex.of(0), 0);
CharacteristicEntries entriesForAllCharacteristicsOfAllParts = new CharacteristicEntries(indexForAllCharacteristicsOfAllParts);
CharacteristicEntries characteristicEntriesForAllCharacteristicsOfAllParts =
removeCharacteristicEntries(indexForAllCharacteristicsOfAllParts);
if (MapUtils.isNotEmpty(characteristicEntriesForAllCharacteristicsOfAllParts)) {
entriesForAllCharacteristicsOfAllParts.putAll(characteristicEntriesForAllCharacteristicsOfAllParts, false);
}
List<ValueEntries> entriesForAllValuesOfAllParts = removeValueEntries(indexForAllCharacteristicsOfAllParts);
Map<Integer, List<ValueEntries>> entriesForAllValuesByValueIndex =
entriesForAllValuesOfAllParts
.stream()
.collect(groupingBy(e -> e.getIndex().getValueIndex()));
forEachPart((part) -> {
CharacteristicIndex indexForAllCharacteristics = CharacteristicIndex.of(part.getIndex(), 0);
CharacteristicEntries entriesForAllCharacteristics = removeCharacteristicEntries(indexForAllCharacteristics);
if (MapUtils.isNotEmpty(entriesForAllCharacteristics)) {
entriesForAllCharacteristicsOfAllParts.putAll(entriesForAllCharacteristics, false);
}
});
forEachCharacteristic((part, characteristic) -> {
characteristic.putAll(entriesForAllCharacteristicsOfAllParts.withIndex(characteristic.getIndex()), false);
forEachValue(part, characteristic, (value) -> {
// value entries for all values are applied to single value set for all characteristic values
List<ValueEntries> entriesForValueIndex = entriesForAllValuesByValueIndex.get(value.getIndex().getValueIndex());
if (entriesForValueIndex != null) {
for (ValueEntries valueEntries : entriesForValueIndex) {
value.putAll(valueEntries.withIndex(value.getIndex()), false);
}
}
});
});
hierarchy = hierarchy.normalize(this);
}
/**
* Returns total number of characteristics of all parts in this object model
*
* @return
*/
public int getCharacteristicCount() {
AtomicInteger characteristicCount = new AtomicInteger();
forEachCharacteristic((part, characteristic) -> characteristicCount.incrementAndGet());
return characteristicCount.get();
}
/**
* Returns total number of values of all parts and characteristics in this object model
*
* @return
*/
public int getValueCount() {
AtomicInteger count = new AtomicInteger();
forEachValue((part, characteristic, value) -> count.incrementAndGet());
return count.get();
}
private <K, V> Map<K, V> newEntriesMap() {
return new ConcurrentSkipListMap<>();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((characteristicEntries == null) ? 0 : characteristicEntries.hashCode());
result = prime * result + ((groupEntries == null) ? 0 : groupEntries.hashCode());
result = prime * result + ((hierarchy == null) ? 0 : hierarchy.hashCode());
result = prime * result + ((partEntries == null) ? 0 : partEntries.hashCode());
result = prime * result + ((valueEntries == null) ? 0 : valueEntries.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof AqdefObjectModel)) {
return false;
}
AqdefObjectModel other = (AqdefObjectModel) obj;
if (characteristicEntries == null) {
if (other.characteristicEntries != null) {
return false;
}
} else if (!characteristicEntries.equals(other.characteristicEntries)) {
return false;
}
if (groupEntries == null) {
if (other.groupEntries != null) {
return false;
}
} else if (!groupEntries.equals(other.groupEntries)) {
return false;
}
if (hierarchy == null) {
if (other.hierarchy != null) {
return false;
}
} else if (!hierarchy.equals(other.hierarchy)) {
return false;
}
if (partEntries == null) {
if (other.partEntries != null) {
return false;
}
} else if (!partEntries.equals(other.partEntries)) {
return false;
}
if (valueEntries == null) {
if (other.valueEntries != null) {
return false;
}
} else if (!valueEntries.equals(other.valueEntries)) {
return false;
}
return true;
}
/**
* Creates a copy of this entries with a given index.
*
* @param index
* @return
*/
public abstract Entries<E, I> withIndex(I index);
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((index == null) ? 0 : index.hashCode());
return result;
}
@SuppressWarnings("rawtypes")
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof Entries)) {
return false;
}
Entries other = (Entries) obj;
if (index == null) {
if (other.index != null) {
return false;
}
} else if (!index.equals(other.index)) {
return false;
}
return true;
}
}
public static abstract class AbstractEntry<I> {
private final KKey key;
private final I index;
private final Object value;
public AbstractEntry(KKey key, I index, Object value) {
super();
this.key = key;
this.index = index;
this.value = value;
}
public KKey getKey() {
return key;
}
public I getIndex() {
return index;
}
public Object getValue() {
return value;
}
/**
* Whether this entry has given key.
*
* @param otherkey
* @return
*/
public boolean hasKey(KKey otherkey) {
return key.equals(otherkey);
}
@Override
public String toString() {
if (value == null) {
return "null";
} else {
return value.toString();
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((index == null) ? 0 : index.hashCode());
result = prime * result + ((key == null) ? 0 : key.hashCode());
result = prime * result + ((value == null) ? 0 : value.hashCode());
return result;
}
@SuppressWarnings("rawtypes")
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof AbstractEntry)) {
return false;
}
AbstractEntry other = (AbstractEntry) obj;
if (index == null) {
if (other.index != null) {
return false;
}
} else if (!index.equals(other.index)) {
return false;
}
if (key == null) {
if (other.key != null) {
return false;
}
} else if (!key.equals(other.key)) {
return false;
}
if (value == null) {
if (other.value != null) {
return false;
}
} else if (!value.equals(other.value)) {
return false;
}
return true;
}
}
public static class PartEntry extends AbstractEntry<PartIndex> {
public PartEntry(KKey key, PartIndex index, Object value) {
super(validateKey(key), index, value);
}
private static KKey validateKey(KKey key) {
if (!key.isPartLevel()) {
throw new IllegalArgumentException("K-Key of part type expected, but found: " + key);
}
return key;
}
}
public static class CharacteristicEntry extends AbstractEntry<CharacteristicIndex> {
public CharacteristicEntry(KKey key, CharacteristicIndex index, Object value) {
super(validateKey(key), index, value);
}
private static KKey validateKey(KKey key) {
if (!key.isCharacteristicLevel()) {
throw new IllegalArgumentException("K-Key of characteristic type expected, but found: " + key);
}
return key;
}
}
public static class ValueEntry extends AbstractEntry<ValueIndex>{
public ValueEntry(KKey key, ValueIndex index, Object value) {
super(validateKey(key), index, value);
}
private static KKey validateKey(KKey key) {
if (!key.isValueLevel()) {
throw new IllegalArgumentException("K-Key of value type expected, but found: " + key);
}
return key;
}
}
public static class GroupEntry extends AbstractEntry<GroupIndex> {
public GroupEntry(KKey key, GroupIndex index, Object value) {
super(validateKey(key), index, value);
}
private static KKey validateKey(KKey key) {
if (!key.isGroupLevel()) {
throw new IllegalArgumentException("K-Key of group type expected, but found: " + key);
}
return key;
}
}
/**
* Contains one "set" of values for all characteristics. <br>
*
* @author Vlastimil Dolejs
*
*/
public static class ValueSet {
private final TreeMap<CharacteristicIndex, ValueEntries> valuesOfCharacteristics;
public ValueSet() {
this(new TreeMap<>());
}
public ValueSet(TreeMap<CharacteristicIndex, ValueEntries> valuesOfCharacteristics) {
super();
this.valuesOfCharacteristics = valuesOfCharacteristics;
}
public void addValueOfCharacteristic(CharacteristicIndex characteristicIndex, ValueEntries valueEntries) {
valuesOfCharacteristics.put(characteristicIndex, valueEntries);
}
public List<CharacteristicIndex> getCharacteristicIndexes() {
return new ArrayList<>(valuesOfCharacteristics.keySet());
}
public ValueEntries getValuesOfCharacteristic(CharacteristicIndex characteristicIndex) {
return valuesOfCharacteristics.get(characteristicIndex);
}
public List<ValueEntries> getValues() {
return new ArrayList<>(valuesOfCharacteristics.values());
}
}
}
|
package de.braintags.vertx.util;
import static java.util.stream.Collectors.toList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.activation.MimeType;
import javax.activation.MimeTypeParameterList;
import javax.activation.MimeTypeParseException;
import com.google.common.base.Joiner;
public class HttpContentType {
public static final String MAIN_TYPE_APPLICATION = "application";
public static final String MAIN_TYPE_TEXT = "text";
public static final String MAIN_TYPE_IMAGE = "image";
public static final String SUB_TYPE_JSON = "json";
public static final String SUB_TYPE_JAVASCRIPT = "javascript";
public static final String SUB_TYPE_HTML = "html";
public static final String SUB_TYPE_CSS = "css";
public static final String SUB_TYPE_PNG = "png";
public static final String SUB_TYPE_SVG = "svg+xml";
public static final String SUB_TYPE_JPEG = "jpeg";
private static final String PARAM_CHARSET = "charset";
private static final String CHARSET_UTF8 = "utf-8";
public static HttpContentType TEXT_HTML = new HttpContentType(MAIN_TYPE_TEXT, SUB_TYPE_HTML);
public static HttpContentType TEXT_CSS = new HttpContentType(MAIN_TYPE_TEXT, SUB_TYPE_CSS);
public static HttpContentType APPLICATION_JAVASCRIPT = new HttpContentType(MAIN_TYPE_APPLICATION, SUB_TYPE_JAVASCRIPT);
public static HttpContentType JSON = new HttpContentType(MAIN_TYPE_APPLICATION, SUB_TYPE_JSON);
public static HttpContentType JSON_UTF8 = new HttpContentType(MAIN_TYPE_APPLICATION, SUB_TYPE_JSON,
Collections.singletonMap(PARAM_CHARSET, CHARSET_UTF8));
public static HttpContentType IMAGE_PNG = new HttpContentType(MAIN_TYPE_IMAGE, SUB_TYPE_PNG);
public static HttpContentType IMAGE_SVG = new HttpContentType(MAIN_TYPE_IMAGE, SUB_TYPE_SVG);
public static HttpContentType IMAGE_JPEG = new HttpContentType(MAIN_TYPE_IMAGE, SUB_TYPE_JPEG);
private final String value;
private final String mainType;
private final String subType;
private final Map<String, String> parameters;
private final String parameterlessValue;
public static HttpContentType parse(final String string) {
try {
MimeType mimeType = new MimeType(string);
return new HttpContentType(mimeType.getPrimaryType(), mimeType.getSubType(), toMap(mimeType.getParameters()));
} catch (MimeTypeParseException e) {
throw new IllegalArgumentException("unable to parse_ " + string, e);
}
}
private static Map<String, String> toMap(final MimeTypeParameterList parameters) {
LinkedHashMap<String, String> result = new LinkedHashMap<>();
Enumeration names = parameters.getNames();
while (names.hasMoreElements()) {
String name = names.nextElement().toString();
result.put(name, parameters.get(name));
}
return result;
}
HttpContentType(final String mainType, final String subType) {
this(mainType, subType, Collections.emptyMap());
}
HttpContentType(final String mainType, final String subType, final Map<String, String> parameters) {
this.mainType = mainType;
this.subType = subType;
this.parameters = parameters;
parameterlessValue = mainType + "/" + subType;
this.value = parameterlessValue + (parameters.isEmpty() ? ""
: ";" + Joiner.on(';').join(parameters.entrySet().stream()
.map(param -> param.getKey() + "=" + param.getValue()).collect(toList())));
}
@Override
public String toString() {
return value;
}
public String getParameterlessValue() {
return parameterlessValue;
}
public String getValue() {
return value;
}
public String getMainType() {
return mainType;
}
public String getSubType() {
return subType;
}
public Map<String, String> getParameters() {
return parameters;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((mainType == null) ? 0 : mainType.hashCode());
result = prime * result + ((parameters == null) ? 0 : parameters.hashCode());
result = prime * result + ((subType == null) ? 0 : subType.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
HttpContentType other = (HttpContentType) obj;
if (mainType == null) {
if (other.mainType != null)
return false;
} else if (!mainType.equals(other.mainType))
return false;
if (parameters == null) {
if (other.parameters != null)
return false;
} else if (!parameters.equals(other.parameters))
return false;
if (subType == null) {
if (other.subType != null)
return false;
} else if (!subType.equals(other.subType))
return false;
return true;
}
}
|
package de.domisum.lib.auxilium.util;
import de.domisum.lib.auxilium.util.java.annotations.API;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.ArrayUtils;
import java.util.Arrays;
import java.util.List;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class StringUtil
{
@API public static String replaceLast(String string, String from, String to)
{
int pos = string.lastIndexOf(from);
if(pos > -1)
return string.substring(0, pos)+to+string.substring(pos+from.length(), string.length());
return string;
}
@API public static String repeat(String string, int repeats)
{
StringBuilder result = new StringBuilder();
for(int i = 0; i < repeats; i++)
result.append(string);
return result.toString();
}
@API public static String getCommonPrefix(String s1, String s2)
{
StringBuilder common = new StringBuilder();
for(int ci = 0; ci < Math.min(s1.length(), s2.length()); ci++)
{
char c1 = s1.charAt(ci);
char c2 = s2.charAt(ci);
if(c1 != c2)
break;
common.append(c1);
}
return common.toString();
}
@API public static String escapeStringForRegex(String input)
{
List<Character> charactersToEscape = Arrays.asList(ArrayUtils.toObject("<([{\\^-=$!|]})?*+.>".toCharArray()));
String escaped = input;
for(int i = 0; i < escaped.length(); i++)
{
char charAt = escaped.charAt(i);
if(charactersToEscape.contains(charAt))
{
escaped = escaped.substring(0, i)+("\\"+charAt)+escaped.substring(i+1);
i++;
}
}
return escaped;
}
@API public static String listToString(List<?> list, String delimiter)
{
StringBuilder combined = new StringBuilder();
for(int i = 0; i < list.size(); i++)
{
combined.append(list.get(i));
combined.append(((i+1) == list.size()) ? "" : delimiter);
}
return combined.toString();
}
@API public static String truncateStart(String string, int maxLength)
{
String toBeContinued = "...";
if(string.length() <= maxLength)
return string;
int desiredBaseStringLength = maxLength-toBeContinued.length();
return toBeContinued+string.substring(string.length()-desiredBaseStringLength);
}
}
|
package de.slikey.effectlib.util;
import de.slikey.effectlib.util.ReflectionUtils.PackageType;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.Color;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.util.Vector;
public enum ParticleEffect {
/**
* A particle effect which is displayed by exploding tnt and creepers:
* <ul>
* <li>It looks like a white cloud
* <li>The speed value influences the velocity at which the particle flies off
* </ul>
*/
EXPLOSION_NORMAL("poof", "explode", 34, 0, -1),
/**
* A particle effect which is displayed by exploding ghast fireballs and wither skulls:
* <ul>
* <li>It looks like a gray ball which is fading away
* <li>The speed value slightly influences the size of this particle effect
* </ul>
*/
EXPLOSION_LARGE("explosion", "largeexplode", 19, 1, -1),
/**
* A particle effect which is displayed by exploding tnt and creepers:
* <ul>
* <li>It looks like a crowd of gray balls which are fading away
* <li>The speed value has no influence on this particle effect
* </ul>
*/
EXPLOSION_HUGE("explosion_emitter", "hugeexplosion", 18, 2, -1),
/**
* A particle effect which is displayed by launching fireworks:
* <ul>
* <li>It looks like a white star which is sparkling
* <li>The speed value influences the velocity at which the particle flies off
* </ul>
*/
FIREWORKS_SPARK("firework", "fireworksSpark", 21, 3, -1),
/**
* A particle effect which is displayed by swimming entities and arrows in water:
* <ul>
* <li>It looks like a bubble
* <li>The speed value influences the velocity at which the particle flies off
* </ul>
*/
WATER_BUBBLE("bubble", "bubble", 4, 4, -1, false, true),
/**
* A particle effect which is displayed by swimming entities and shaking wolves:
* <ul>
* <li>It looks like a blue drop
* <li>The speed value has no influence on this particle effect
* </ul>
*/
WATER_SPLASH("splash", "splash", 43, 5, -1),
/**
* A particle effect which is displayed on water when fishing:
* <ul>
* <li>It looks like a blue droplet
* <li>The speed value influences the velocity at which the particle flies off
* </ul>
*/
WATER_WAKE("fishing", "wake", 22, 6, 7),
/**
* A particle effect which is displayed by water:
* <ul>
* <li>It looks like a tiny blue square
* <li>The speed value has no influence on this particle effect
* </ul>
*/
SUSPENDED("underwater", "suspended", 42, 7, -1, false, true),
/**
* A particle effect which is displayed by air when close to bedrock and the in the void:
* <ul>
* <li>It looks like a tiny gray square
* <li>The speed value has no influence on this particle effect
* <li>Removed as of 1.13
* </ul>
*/
@Deprecated
SUSPENDED_DEPTH("", "depthSuspend", -1, 8, -1),
/**
* A particle effect which is displayed when landing a critical hit and by arrows:
* <ul>
* <li>It looks like a light brown cross
* <li>The speed value influences the velocity at which the particle flies off
* </ul>
*/
CRIT("crit", "crit", 6, 9, -1),
/**
* A particle effect which is displayed when landing a hit with an enchanted weapon:
* <ul>
* <li>It looks like a cyan star
* <li>The speed value influences the velocity at which the particle flies off
* </ul>
*/
CRIT_MAGIC("enchanted_hit", "magicCrit", 14, 10, -1),
/**
* A particle effect which is displayed by primed tnt, torches, droppers, dispensers, end portals, brewing stands and monster spawners:
* <ul>
* <li>It looks like a little gray cloud
* <li>The speed value influences the velocity at which the particle flies off
* </ul>
*/
SMOKE_NORMAL("smoke", "smoke", 37, 11, -1),
/**
* A particle effect which is displayed by fire, minecarts with furnace and blazes:
* <ul>
* <li>It looks like a large gray cloud
* <li>The speed value influences the velocity at which the particle flies off
* </ul>
*/
SMOKE_LARGE("large_smoke", "largesmoke", 30, 12, -1),
/**
* A particle effect which is displayed when splash potions or bottles o' enchanting hit something:
* <ul>
* <li>It looks like a white swirl
* <li>The speed value causes the particle to only move upwards when set to 0
* </ul>
*/
SPELL("effect", "spell", 12, 13, -1),
/**
* A particle effect which is displayed when instant splash potions hit something:
* <ul>
* <li>It looks like a white cross
* <li>The speed value causes the particle to only move upwards when set to 0
* </ul>
*/
SPELL_INSTANT("instant_effect", "instantSpell", 26, 14, -1),
/**
* A particle effect which is displayed by entities with active potion effects:
* <ul>
* <li>It looks like a colored swirl
* <li>The speed value causes the particle to be colored black when set to 0
* <li>The particle color gets lighter when increasing the speed and darker when decreasing the speed
* </ul>
*/
SPELL_MOB("entity_effect", "mobSpell", 17, 15, -1),
/**
* A particle effect which is displayed by entities with active potion effects applied through a beacon:
* <ul>
* <li>It looks like a transparent colored swirl
* <li>The speed value causes the particle to be always colored black when set to 0
* <li>The particle color gets lighter when increasing the speed and darker when decreasing the speed
* </ul>
*/
SPELL_MOB_AMBIENT("ambient_entity_effect", "mobSpellAmbient", 0, 16, -1),
/**
* A particle effect which is displayed by witches:
* <ul>
* <li>It looks like a purple cross
* <li>The speed value causes the particle to only move upwards when set to 0
* </ul>
*/
SPELL_WITCH("witch", "witchMagic", 44, 17, -1),
/**
* A particle effect which is displayed by blocks beneath a water source:
* <ul>
* <li>It looks like a blue drip
* <li>The speed value has no influence on this particle effect
* </ul>
*/
DRIP_WATER("dripping_water", "dripWater", 10, 18, -1),
/**
* A particle effect which is displayed by blocks beneath a lava source:
* <ul>
* <li>It looks like an orange drip
* <li>The speed value has no influence on this particle effect
* </ul>
*/
DRIP_LAVA("dripping_lava", "dripLava", 9, 19, -1),
/**
* A particle effect which is displayed when using bone meal and trading with a villager in a village:
* <ul>
* <li>It looks like a green star
* <li>The speed value has no influence on this particle effect
* </ul>
*/
VILLAGER_HAPPY("happy_villager", "happyVillager", 24, 21, -1),
/**
* A particle effect which is displayed when attacking a villager in a village:
* <ul>
* <li>It looks like a cracked gray heart
* <li>The speed value has no influence on this particle effect
* </ul>
*/
VILLAGER_ANGRY("angry_villager", "angryVillager", 1, 20, -1),
/**
* A particle effect which is displayed by mycelium:
* <ul>
* <li>It looks like a tiny gray square
* <li>The speed value has no influence on this particle effect
* </ul>
*/
TOWN_AURA("mycelium", "townaura", 32, 22, -1),
/**
* A particle effect which is displayed by note blocks:
* <ul>
* <li>It looks like a colored note
* <li>The speed value causes the particle to be colored green when set to 0
* </ul>
*/
NOTE("note", "note", 33, 23, -1),
/**
* A particle effect which is displayed by nether portals, endermen, ender pearls, eyes of ender, ender chests and dragon eggs:
* <ul>
* <li>It looks like a purple cloud
* <li>The speed value influences the spread of this particle effect
* </ul>
*/
PORTAL("portal", "portal", 35, 24, -1),
/**
* A particle effect which is displayed by enchantment tables which are nearby bookshelves:
* <ul>
* <li>It looks like a cryptic white letter
* <li>The speed value influences the spread of this particle effect
* </ul>
*/
ENCHANTMENT_TABLE("enchant", "enchantmenttable", 15, 25, -1),
/**
* A particle effect which is displayed by torches, active furnaces, magma cubes and monster spawners:
* <ul>
* <li>It looks like a tiny flame
* <li>The speed value influences the velocity at which the particle flies off
* </ul>
*/
FLAME("flame", "flame", 23, 26, -1),
/**
* A particle effect which is displayed by lava:
* <ul>
* <li>It looks like a spark
* <li>The speed value has no influence on this particle effect
* </ul>
*/
LAVA("lava", "lava", 31, 27, -1),
/**
* A particle effect which is displayed when a mob dies:
* <ul>
* <li>It looks like a large white cloud
* <li>The speed value influences the velocity at which the particle flies off
* </ul>
*/
CLOUD("cloud", "cloud", 5, 29, -1),
/**
* A particle effect which is displayed by redstone ore, powered redstone, redstone torches and redstone repeaters:
* <ul>
* <li>It looks like a tiny colored cloud
* <li>The speed value causes the particle to be colored red when set to 0
* </ul>
*/
REDSTONE("dust", "reddust", 11, 30, -1),
/**
* A particle effect which is displayed when snowballs hit a block:
* <ul>
* <li>It looks like a little piece with the snowball texture
* <li>The speed value has no influence on this particle effect
* </ul>
*/
SNOWBALL("item_snowball", "snowballpoof", 29, 31, -1),
/**
* A particle effect which is currently unused:
* <ul>
* <li>It looks like a tiny white cloud
* <li>The speed value influences the velocity at which the particle flies off
* <li>This was removed as of 1.13
* </ul>
*/
@Deprecated
SNOW_SHOVEL("", "snowshovel", -1, 32, -1),
/**
* A particle effect which is displayed by slimes:
* <ul>
* <li>It looks like a tiny part of the slimeball icon
* <li>The speed value has no influence on this particle effect
* </ul>
*/
SLIME("item_slime", "slime", 28, 33, -1),
/**
* A particle effect which is displayed when breeding and taming animals:
* <ul>
* <li>It looks like a red heart
* <li>The speed value has no influence on this particle effect
* </ul>
*/
HEART("heart", "heart", 25, 34, -1),
/**
* A particle effect which is displayed by barriers:
* <ul>
* <li>It looks like a red box with a slash through it
* <li>The speed value has no influence on this particle effect
* </ul>
*/
BARRIER("barrier", "barrier", 2, 35, 8),
/**
* A particle effect which is displayed when breaking a tool or eggs hit a block:
* <ul>
* <li>It looks like a little piece with an item texture
* </ul>
*/
ITEM_CRACK("item", "iconcrack", 27, 36, -1, true),
/**
* A particle effect which is displayed when breaking blocks or sprinting:
* <ul>
* <li>It looks like a little piece with a block texture
* <li>The speed value has no influence on this particle effect
* </ul>
*/
BLOCK_CRACK("block", "blockcrack", 3, 37, -1, true),
/**
* A particle effect which is displayed when falling:
* <ul>
* <li>It looks like a little piece with a block texture
* <li>This was merged with "block as of 1.13
* </ul>
*/
BLOCK_DUST("block", "blockdust", 3, 38, 7, true),
/**
* A particle effect which is displayed when rain hits the ground:
* <ul>
* <li>It looks like a blue droplet
* <li>The speed value has no influence on this particle effect
* </ul>
*/
WATER_DROP("rain", "droplet", 36, 39, 8),
/**
* A particle effect which is displayed by elder guardians:
* <ul>
* <li>It looks like the shape of the elder guardian
* <li>The speed value has no influence on this particle effect
* </ul>
*/
MOB_APPEARANCE("elder_guardian", "mobappearance", 13, 41, 8),
/**
* A particle effect which is displayed by the ender dragon when breathing poison:
* <ul>
* <li>It looks like a purple redstone particle
* </ul>
*/
DRAGON_BREATH("dragon_breath", "dragonbreath", 8, 42, 9),
/**
* A particle effect which is displayed by end rods.
* <ul>
* <li>It looks like a bright white glow
* </ul>
*/
END_ROD("end_rod", "endRod", 16, 43, 9),
/**
* A particle effect which is displayed when damaging a mob:
* <ul>
* <li>It looks like a dark red heart
* </ul>
*/
DAMAGE_INDICATOR("damage_indicator", "damageIndicator", 7, 44, 9),
/**
* A particle effect which is displayed when performing a well-timed attack
* <ul>
* <li>It looks like a gray/white arc
* </ul>
*/
SWEEP_ATTACK("sweep_attack", "sweepAttack", 40, 45, 9),
/**
* A particle effect which is displayed by sand and other gravity-effected blocks while
* they are suspended in the air.
* <ul>
* <li>It looks like falling particles of the target block
* </ul>
*/
FALLING_DUST("falling_dust", "fallingdust", 20, 46, 10, true),
/**
* A particle effect which is displayed when using a totem of undying:
* <ul>
* <li>It looks like a green diamond
* </ul>
*/
TOTEM("totem_of_undying", "totem", 41, 47, 11),
/**
* A particle effect which is displayed when a llama spits:
* <ul>
* <li>It looks like a white cloud
* </ul>
*/
SPIT("spit", "spit", 38, 48, 11),
/**
* A particle effect which is displayed when a squid shoots out ink
* <ul>
* <li>It looks like a cloud of black squares
* </ul>
*/
SQUID_INK("squid_ink", "", 39, -1, 13, false, true),
/**
* A particle effect which is displayed at the top bubble columns:
* <ul>
* <li>It looks like a bubble popping
* </ul>
*/
BUBBLE_POP("bubble_pop", "", 45, -1, 13, false, true),
/**
* A particle effect which is displayed for underwater downward bubble columns:
* <ul>
* <li>It looks like a stream of bubbles of going downward
* </ul>
*/
CURRENT_DOWN("current_down", "", 46, -1, 13, false, true),
/**
* A particle effect which is displayed by underwater bubble columns:
* <ul>
* <li>It looks like a stream of bubbles
* </ul>
*/
BUBBLE_COLUMN_UP("bubble_column_up", "", 47, -1, 13, false, true),
/**
* TODO: Document me!
*/
NAUTILUS("nautilus", "", -1, 48, -1),
/**
* A particle effect which is currently unused:
* <ul>
* <li>It looks like a transparent gray square
* <li>The speed value has no influence on this particle effect
* <li>Removed as of 1.13
* </ul>
*/
@Deprecated
FOOTSTEP("", "footstep", -1, 28, -1),
/**
* A particle effect which is currently unused:
* <ul>
* <li>It has no visual effect
* <li>This was removed as of 1.13
* </ul>
*/
@Deprecated
ITEM_TAKE("", "take", -1, 40, 8),
;
private static final int LONG_DISTANCE = 16;
private static final int LONG_DISTANCE_SQUARED = LONG_DISTANCE * LONG_DISTANCE;
private final String legacyName;
private final String name;
private final int legacyId;
private final int id;
private final int requiredVersion;
private final boolean requiresData;
private final boolean requiresWater;
/**
* Construct a new particle effect
*
* @param name Name of this particle effect
* @param legacyName Pre-1.13 name of this particle effect
* @param id Id of this particle effect
* @param legacyId Pre-1.13 id of this particle effect
* @param requiredVersion Version which is required (1.x)
* @param requiresData Indicates whether additional data is required for this particle effect
* @param requiresWater Indicates whether water is required for this particle effect to display properly
*/
private ParticleEffect(String name, String legacyName, int id, int legacyId, int requiredVersion, boolean requiresData, boolean requiresWater) {
this.name = name;
this.legacyName = legacyName;
this.id = id;
this.legacyId = legacyId;
this.requiredVersion = requiredVersion;
this.requiresData = requiresData;
this.requiresWater = requiresWater;
}
/**
* Construct a new particle effect with {@link #requiresWater} set to <code>false</code>
*
* @param name Name of this particle effect
* @param legacyName Pre-1.13 name of this particle effect
* @param id Id of this particle effect
* @param legacyId Pre-1.13 id of this particle effect
* @param requiredVersion Version which is required (1.x)
* @param requiresData Indicates whether additional data is required for this particle effect
*/
private ParticleEffect(String name, String legacyName, int id, int legacyId, int requiredVersion, boolean requiresData) {
this(name, legacyName, id, legacyId, requiredVersion, requiresData, false);
}
/**
* Construct a new particle effect with {@link #requiresData} and {@link #requiresWater} set to <code>false</code>
*
* @param name Name of this particle effect
* @param legacyName Pre-1.13 name of this particle effect
* @param id Id of this particle effect
* @param legacyId Pre-1.13 id of this particle effect
* @param requiredVersion Version which is required (1.x)
*/
private ParticleEffect(String name, String legacyName, int id, int legacyId, int requiredVersion) {
this(name, legacyName, id, legacyId, requiredVersion, false);
}
/**
* Returns the legacy name of this particle effect, for pre-1.8 particles
*
* @return The name
*/
public String getLegacyName() {
return legacyName;
}
/**
* Returns the name of this particle effect
*
* @return The name
*/
public String getName() {
return name;
}
/**
* Returns the id of this particle effect
*
* @return The id
*/
public int getId() {
return id;
}
/**
* Returns the legacy id of this particle effect, for pre-1.13 particles
*
* @return The legacy id
*/
public int getLegacyId() {
return legacyId;
}
/**
* Returns the required version for this particle effect (1.x)
*
* @return The required version
*/
public int getRequiredVersion() {
return requiredVersion;
}
/**
* Determine if additional data is required for this particle effect
*
* @return Whether additional data is required or not
*/
public boolean getRequiresData() {
return requiresData;
}
/**
* Determine if water is required for this particle effect to display properly
*
* @return Whether water is required or not
*/
public boolean getRequiresWater() {
return requiresWater;
}
/**
* Determine if this particle effect is supported by your current server version
*
* @return Whether the particle effect is supported or not
*/
public boolean isSupported() {
if (requiredVersion == -1) {
return true;
}
return ParticlePacket.getVersion() >= requiredVersion;
}
/**
* Determine if water is at a certain location
*
* @param location Location to check
* @return Whether water is at this location or not
*/
private static boolean isWater(Location location) {
// Short-circuited due to differences in Material between versions.
// TODO: Just remove this check.
return true;
}
/**
* Determine if the distance between @param location and one of the players exceeds LONG_DISTANCE
*
* @param location Location to check
* @return Whether the distance exceeds 16 or not
*/
private static boolean isLongDistance(Location location, List<Player> players) {
for (Player player : players) {
if (player.getLocation().distanceSquared(location) > LONG_DISTANCE_SQUARED) {
return true;
}
}
return false;
}
/**
* Determine if the data type for a particle effect is correct
*
* @param effect Particle effect
* @param data Particle data
* @return Whether the data type is correct or not
*/
private static boolean isDataCorrect(ParticleEffect effect, ParticleData data) {
return ((effect == BLOCK_CRACK || effect == BLOCK_DUST || effect == FALLING_DUST) && data instanceof BlockData) || effect == ITEM_CRACK && data instanceof ItemData;
}
public void display(float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, double range, List<Player> targetPlayers) throws ParticleVersionException, ParticleDataException, IllegalArgumentException {
if (!isSupported()) {
throw new ParticleVersionException("The " + this + " particle effect is not supported by your server version " + ParticlePacket.getVersion());
}
if (requiresData) {
throw new ParticleDataException("The " + this + " particle effect requires additional data");
}
if (requiresWater && !isWater(center)) {
throw new IllegalArgumentException("There is no water at the center location");
}
ParticlePacket particle = new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, range > 16, null);
if (targetPlayers != null) particle.sendTo(center, targetPlayers);
else particle.sendTo(center, range);
}
public void display(float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, double range) throws ParticleVersionException, ParticleDataException, IllegalArgumentException {
display(offsetX, offsetY, offsetZ, speed, amount, center, range, null);
}
public void display(float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, List<Player> players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException {
if (!isSupported()) {
throw new ParticleVersionException("The " + this + " particle effect is not supported by your server version " + ParticlePacket.getVersion());
}
if (requiresData) {
throw new ParticleDataException("The " + this + " particle effect requires additional data");
}
if (requiresWater && !isWater(center)) {
throw new IllegalArgumentException("There is no water at the center location");
}
new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, isLongDistance(center, players), null).sendTo(center, players);
}
public void display(float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, Player... players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException {
display(offsetX, offsetY, offsetZ, speed, amount, center, Arrays.asList(players));
}
public void display(Vector direction, float speed, Location center, double range) throws ParticleVersionException, ParticleDataException, IllegalArgumentException {
if (!isSupported()) {
throw new ParticleVersionException("The " + this + " particle effect is not supported by your server version " + ParticlePacket.getVersion());
}
if (requiresData) {
throw new ParticleDataException("The " + this + " particle effect requires additional data");
}
if (requiresWater && !isWater(center)) {
throw new IllegalArgumentException("There is no water at the center location");
}
ParticlePacket particle = new ParticlePacket(this, direction, speed, range > LONG_DISTANCE, null);
particle.sendTo(center, range);
}
public void display(Vector direction, float speed, Location center, List<Player> players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException {
if (!isSupported()) {
throw new ParticleVersionException("The " + this + " particle effect is not supported by your server version " + ParticlePacket.getVersion());
}
if (requiresData) {
throw new ParticleDataException("The " + this + " particle effect requires additional data");
}
if (requiresWater && !isWater(center)) {
throw new IllegalArgumentException("There is no water at the center location");
}
new ParticlePacket(this, direction, speed, isLongDistance(center, players), null).sendTo(center, players);
}
public void display(Vector direction, float speed, Location center, Player... players) throws ParticleVersionException, ParticleDataException, IllegalArgumentException {
display(direction, speed, center, Arrays.asList(players));
}
/**
* Displays a particle effect which requires additional data and is only visible for all players within a certain range in the world of @param center
*
* @param data Data of the effect
* @param offsetX Maximum distance particles can fly away from the center on the x-axis
* @param offsetY Maximum distance particles can fly away from the center on the y-axis
* @param offsetZ Maximum distance particles can fly away from the center on the z-axis
* @param speed Display speed of the particles
* @param amount Amount of particles
* @param center Center location of the effect
* @param range Range of the visibility
* @param targetPlayers if set, will send to a specific set of players
* @throws ParticleVersionException If the particle effect is not supported by the server version
* @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect
* @see ParticlePacket
* @see ParticlePacket#sendTo(Location, double)
*/
public void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, double range, List<Player> targetPlayers) throws ParticleVersionException, ParticleDataException {
if (!isSupported()) {
throw new ParticleVersionException("The " + this + " particle effect is not supported by your server version " + ParticlePacket.getVersion());
}
if (!requiresData) {
throw new ParticleDataException("The " + this + " particle effect does not require additional data");
}
// Just skip it if there's no data, rather than throwing an exception
if (data == null) return;
if (!isDataCorrect(this, data)) {
throw new ParticleDataException("The particle data type is incorrect: " + data + " for " + this);
}
ParticlePacket particle = new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, range > LONG_DISTANCE, data);
if (targetPlayers != null) particle.sendTo(center, targetPlayers);
else particle.sendTo(center, range);
}
public void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, double range) throws ParticleVersionException, ParticleDataException {
display(data, offsetX, offsetY, offsetZ, speed, amount, center, range, null);
}
/**
* Displays a particle effect which requires additional data and is only visible for the specified players
*
* @param data Data of the effect
* @param offsetX Maximum distance particles can fly away from the center on the x-axis
* @param offsetY Maximum distance particles can fly away from the center on the y-axis
* @param offsetZ Maximum distance particles can fly away from the center on the z-axis
* @param speed Display speed of the particles
* @param amount Amount of particles
* @param center Center location of the effect
* @param players Receivers of the effect
* @throws ParticleVersionException If the particle effect is not supported by the server version
* @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect
* @see ParticlePacket
* @see ParticlePacket#sendTo(Location, List)
*/
public void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, List<Player> players) throws ParticleVersionException, ParticleDataException {
if (!isSupported()) {
throw new ParticleVersionException("The " + this + " particle effect is not supported by your server version " + ParticlePacket.getVersion());
}
if (!requiresData) {
throw new ParticleDataException("The " + this + " particle effect does not require additional data");
}
if (!isDataCorrect(this, data)) {
throw new ParticleDataException("The particle data type is incorrect: " + data + " for " + this);
}
new ParticlePacket(this, offsetX, offsetY, offsetZ, speed, amount, isLongDistance(center, players), data).sendTo(center, players);
}
/**
* Displays a particle effect which requires additional data and is only visible for the specified players
*
* @param data Data of the effect
* @param offsetX Maximum distance particles can fly away from the center on the x-axis
* @param offsetY Maximum distance particles can fly away from the center on the y-axis
* @param offsetZ Maximum distance particles can fly away from the center on the z-axis
* @param speed Display speed of the particles
* @param amount Amount of particles
* @param center Center location of the effect
* @param players Receivers of the effect
* @throws ParticleVersionException If the particle effect is not supported by the server version
* @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect
* @see #display(ParticleData, float, float, float, float, int, Location, List)
*/
public void display(ParticleData data, float offsetX, float offsetY, float offsetZ, float speed, int amount, Location center, Player... players) throws ParticleVersionException, ParticleDataException {
display(data, offsetX, offsetY, offsetZ, speed, amount, center, Arrays.asList(players));
}
/**
* Displays a single particle which requires additional data that flies into a determined direction and is only visible for all players within a certain range in the world of @param center
*
* @param data Data of the effect
* @param direction Direction of the particle
* @param speed Display speed of the particles
* @param center Center location of the effect
* @param range Range of the visibility
* @throws ParticleVersionException If the particle effect is not supported by the server version
* @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect
* @see ParticlePacket
* @see ParticlePacket#sendTo(Location, double)
*/
public void display(ParticleData data, Vector direction, float speed, Location center, double range) throws ParticleVersionException, ParticleDataException {
if (!isSupported()) {
throw new ParticleVersionException("The " + this + " particle effect is not supported by your server version " + ParticlePacket.getVersion());
}
if (!requiresData) {
throw new ParticleDataException("The " + this + " particle effect does not require additional data");
}
if (!isDataCorrect(this, data)) {
throw new ParticleDataException("The particle data type is incorrect: " + data + " for " + this);
}
new ParticlePacket(this, direction, speed, range > LONG_DISTANCE, data).sendTo(center, range);
}
/**
* Displays a single particle which requires additional data that flies into a determined direction and is only visible for the specified players
*
* @param data Data of the effect
* @param direction Direction of the particle
* @param speed Display speed of the particles
* @param center Center location of the effect
* @param players Receivers of the effect
* @throws ParticleVersionException If the particle effect is not supported by the server version
* @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect
* @see ParticlePacket
* @see ParticlePacket#sendTo(Location, List)
*/
public void display(ParticleData data, Vector direction, float speed, Location center, List<Player> players) throws ParticleVersionException, ParticleDataException {
if (!isSupported()) {
throw new ParticleVersionException("The " + this + " particle effect is not supported by your server version " + ParticlePacket.getVersion());
}
if (!requiresData) {
throw new ParticleDataException("The " + this + " particle effect does not require additional data");
}
if (!isDataCorrect(this, data)) {
throw new ParticleDataException("The particle data type is incorrect: " + data + " for " + this);
}
new ParticlePacket(this, direction, speed, isLongDistance(center, players), data).sendTo(center, players);
}
/**
* Displays a single particle which requires additional data that flies into a determined direction and is only visible for the specified players
*
* @param data Data of the effect
* @param direction Direction of the particle
* @param speed Display speed of the particles
* @param center Center location of the effect
* @param players Receivers of the effect
* @throws ParticleVersionException If the particle effect is not supported by the server version
* @throws ParticleDataException If the particle effect does not require additional data or if the data type is incorrect
* @see #display(ParticleData, Vector, float, Location, List)
*/
public void display(ParticleData data, Vector direction, float speed, Location center, Player... players) throws ParticleVersionException, ParticleDataException {
display(data, direction, speed, center, Arrays.asList(players));
}
/**
* Represents the particle data for effects like {@link ParticleEffect#ITEM_CRACK}, {@link ParticleEffect#BLOCK_CRACK} and {@link ParticleEffect#BLOCK_DUST}
* <p>
* This class is part of the <b>ParticleEffect Library</b> and follows the same usage conditions
*
* @author DarkBlade12
* @since 1.6
*/
public static abstract class ParticleData {
private final Material material;
private final byte data;
private final int[] packetData;
public ParticleData(Material material, byte data, int[] packetData) {
this.material = material;
this.data = data;
this.packetData = packetData;
}
/**
* Returns the material of this data
*
* @return The material
*/
public Material getMaterial() {
return material;
}
/**
* Returns the data value of this data
*
* @return The data value
*/
public byte getData() {
return data;
}
/**
* Returns the data as an int array for packet construction
*
* @return The data for the packet
*/
public int[] getPacketData() {
return packetData;
}
/**
* Returns the data as a string for pre 1.8 versions
*
* @return The data string for the packet
*/
public String getPacketDataString() {
if (packetData.length >= 2) return "_" + packetData[0] + "_" + packetData[1];;
if (packetData.length == 1) return "_" + packetData[0];
return "";
}
}
/**
* Represents the item data for the {@link ParticleEffect#ITEM_CRACK} effect
* <p>
* This class is part of the <b>ParticleEffect Library</b> and follows the same usage conditions
*
* @author DarkBlade12
* @since 1.6
*/
public static final class ItemData extends ParticleData {
/**
* Construct a new item data
*
* @param material Material of the item
* @param data Data value of the item
* @see ParticleData#ParticleData(Material, byte, int[])
*/
@SuppressWarnings("deprecation")
public ItemData(Material material, byte data) {
super(material, data,
ParticlePacket.getVersion() >= 13 ?
new int[]{material.getId(), 1, data, 0} :
new int[]{material.getId(), data}
);
}
}
/**
* Represents the block data for the {@link ParticleEffect#BLOCK_CRACK} and {@link ParticleEffect#BLOCK_DUST} effects
* <p>
* This class is part of the <b>ParticleEffect Library</b> and follows the same usage conditions
*
* @author DarkBlade12
* @since 1.6
*/
public static final class BlockData extends ParticleData {
@SuppressWarnings("deprecation")
public BlockData(Material material, byte data) throws IllegalArgumentException {
super(material, data,
ParticlePacket.getVersion() >= 13 ?
new int[]{material.getId()} :
new int[]{(data << 12) | (material.getId() & 4095)}
);
if (!material.isBlock()) {
throw new IllegalArgumentException("The material is not a block");
}
}
}
/**
* Represents a runtime exception that is thrown either if the displayed particle effect requires data and has none or vice-versa or if the data type is wrong
* <p>
* This class is part of the <b>ParticleEffect Library</b> and follows the same usage conditions
*
* @author DarkBlade12
* @since 1.6
*/
private static final class ParticleDataException extends RuntimeException {
private static final long serialVersionUID = 3203085387160737484L;
/**
* Construct a new particle data exception
*
* @param message Message that will be logged
*/
public ParticleDataException(String message) {
super(message);
}
}
/**
* Represents a runtime exception that is thrown if the displayed particle effect requires a newer version
* <p>
* This class is part of the <b>ParticleEffect Library</b> and follows the same usage conditions
*
* @author DarkBlade12
* @since 1.6
*/
private static final class ParticleVersionException extends RuntimeException {
private static final long serialVersionUID = 3203085387160737484L;
/**
* Construct a new particle version exception
*
* @param message Message that will be logged
*/
public ParticleVersionException(String message) {
super(message);
}
}
/**
* Represents a particle effect packet with all attributes which is used for sending packets to the players
* <p>
* This class is part of the <b>ParticleEffect Library</b> and follows the same usage conditions
*
* @author DarkBlade12
* @since 1.5
*/
public static final class ParticlePacket {
private static int version;
private static boolean isKcauldron;
private static final int[] emptyData = new int[0];
private static Object[] enumParticles;
private static Class<?> enumParticle;
private static Constructor<?> packetConstructor;
private static Field packet_idField;
private static Field packet_locationXField;
private static Field packet_locationYField;
private static Field packet_locationZField;
private static Field packet_offsetXField;
private static Field packet_offsetYField;
private static Field packet_offsetZField;
private static Field packet_speedField;
private static Field packet_amountField;
private static Field packet_longDistanceField;
private static Field packet_dataField;
private static Method getHandle;
private static Field playerConnection;
private static Method sendPacket;
private static boolean initialized;
private final ParticleEffect effect;
private final float offsetX;
private final float offsetY;
private final float offsetZ;
private final float speed;
private final int amount;
private final boolean longDistance;
private final ParticleData data;
private Object packet;
public static void skipInitialization() {
initialized = true;
}
public ParticlePacket(ParticleEffect effect, float offsetX, float offsetY, float offsetZ, float speed, int amount, boolean longDistance, ParticleData data) throws IllegalArgumentException {
initialize();
if (speed < 0) {
throw new IllegalArgumentException("The speed is lower than 0");
}
if (amount < 0) {
throw new IllegalArgumentException("The amount is lower than 0");
}
this.effect = effect;
this.offsetX = offsetX;
this.offsetY = offsetY;
this.offsetZ = offsetZ;
this.speed = speed;
this.amount = amount;
this.longDistance = longDistance;
this.data = data;
}
public ParticlePacket(ParticleEffect effect, Vector direction, float speed, boolean longDistance, ParticleData data) throws IllegalArgumentException {
initialize();
if (speed < 0) {
throw new IllegalArgumentException("The speed is lower than 0");
}
this.effect = effect;
this.offsetX = (float) direction.getX();
this.offsetY = (float) direction.getY();
this.offsetZ = (float) direction.getZ();
this.speed = speed;
this.amount = 0;
this.longDistance = longDistance;
this.data = data;
}
/**
* Initializes {@link #packetConstructor}, {@link #getHandle}, {@link #playerConnection} and {@link #sendPacket} and sets {@link #initialized} to <code>true</code> if it succeeds
* <p>
* <b>Note:</b> These fields only have to be initialized once, so it will return if {@link #initialized} is already set to <code>true</code>
*
* @throws VersionIncompatibleException if your bukkit version is not supported by this library
*/
public static void initialize() throws VersionIncompatibleException {
if (initialized) {
return;
}
try {
//Try and enable effect lib for bukkit
isKcauldron = false;
String[] pieces = StringUtils.split(PackageType.getServerVersion(), "_");
version = Integer.parseInt(pieces[1]);
if (version > 7) {
enumParticle = PackageType.MINECRAFT_SERVER.getClass("EnumParticle");
enumParticles = enumParticle.getEnumConstants();
}
Class<?> packetClass = PackageType.MINECRAFT_SERVER.getClass(version < 7 ? "Packet63WorldParticles" : "PacketPlayOutWorldParticles");
packetConstructor = ReflectionUtils.getConstructor(packetClass);
getHandle = ReflectionUtils.getMethod("CraftPlayer", PackageType.CRAFTBUKKIT_ENTITY, "getHandle");
playerConnection = ReflectionUtils.getField("EntityPlayer", PackageType.MINECRAFT_SERVER, false, "playerConnection");
sendPacket = ReflectionUtils.getMethod(playerConnection.getType(), "sendPacket", PackageType.MINECRAFT_SERVER.getClass("Packet"));
if (version >= 13 ) {
packet_idField = ReflectionUtils.getField(packetClass, true, "j");
packet_locationXField = ReflectionUtils.getField(packetClass, true, "a");
packet_locationYField = ReflectionUtils.getField(packetClass, true, "b");
packet_locationZField = ReflectionUtils.getField(packetClass, true, "c");
packet_offsetXField = ReflectionUtils.getField(packetClass, true, "d");
packet_offsetYField = ReflectionUtils.getField(packetClass, true, "e");
packet_offsetZField = ReflectionUtils.getField(packetClass, true, "f");
packet_speedField = ReflectionUtils.getField(packetClass, true, "g");
packet_amountField = ReflectionUtils.getField(packetClass, true, "h");
packet_longDistanceField = ReflectionUtils.getField(packetClass, true, "i");
} else {
packet_idField = ReflectionUtils.getField(packetClass, true, "a");
packet_locationXField = ReflectionUtils.getField(packetClass, true, "b");
packet_locationYField = ReflectionUtils.getField(packetClass, true, "c");
packet_locationZField = ReflectionUtils.getField(packetClass, true, "d");
packet_offsetXField = ReflectionUtils.getField(packetClass, true, "e");
packet_offsetYField = ReflectionUtils.getField(packetClass, true, "f");
packet_offsetZField = ReflectionUtils.getField(packetClass, true, "g");
packet_speedField = ReflectionUtils.getField(packetClass, true, "h");
packet_amountField = ReflectionUtils.getField(packetClass, true, "i");
if (version > 7) {
packet_longDistanceField = ReflectionUtils.getField(packetClass, true, "j");
packet_dataField = ReflectionUtils.getField(packetClass, true, "k");
}
}
} catch (Exception exception) {
try {
//If an error occurs try and use KCauldron classes
isKcauldron = true;
Class<?> packetClass = Class.forName("net.minecraft.network.play.server.S2APacketParticles");
packetConstructor = ReflectionUtils.getConstructor(packetClass);
getHandle = ReflectionUtils.getMethod("CraftPlayer", PackageType.CRAFTBUKKIT_ENTITY, "getHandle");
playerConnection = Class.forName("net.minecraft.entity.player.EntityPlayerMP").getDeclaredField("field_71135_a");
sendPacket = playerConnection.getType().getDeclaredMethod("func_147359_a", Class.forName("net.minecraft.network.Packet"));
packet_idField = ReflectionUtils.getField(packetClass, true, "field_149236_a");
packet_locationXField = ReflectionUtils.getField(packetClass, true, "field_149234_b");
packet_locationYField = ReflectionUtils.getField(packetClass, true, "field_149235_c");
packet_locationZField = ReflectionUtils.getField(packetClass, true, "field_149232_d");
packet_offsetXField = ReflectionUtils.getField(packetClass, true, "field_149233_e");
packet_offsetYField = ReflectionUtils.getField(packetClass, true, "field_149230_f");
packet_offsetZField = ReflectionUtils.getField(packetClass, true, "field_149231_g");
packet_speedField = ReflectionUtils.getField(packetClass, true, "field_149237_h");
packet_amountField = ReflectionUtils.getField(packetClass, true, "field_149238_i");
} catch (Exception e) {
throw new VersionIncompatibleException("Your current bukkit version seems to be incompatible with this library", exception);
}
}
initialized = true;
}
/**
* Returns the version of your server (1.x)
*
* @return The version number
*/
public static int getVersion() {
return version;
}
/**
* Determine if {@link #packetConstructor}, {@link #getHandle}, {@link #playerConnection} and {@link #sendPacket} are initialized
*
* @return Whether these fields are initialized or not
* @see #initialize()
*/
public static boolean isInitialized() {
return initialized;
}
/**
* Sends the packet to a single player and caches it
*
* @param center Center location of the effect
* @param player Receiver of the packet
* @throws PacketInstantiationException if instantion fails due to an unknown error
* @throws PacketSendingException if sending fails due to an unknown error
*/
public void sendTo(Location center, Player player) throws PacketInstantiationException, PacketSendingException {
if (packet == null) {
try {
packet = packetConstructor.newInstance();
Object id;
if (version < 8) {
id = effect.getLegacyName() + (data == null ? "" : data.getPacketDataString());
} else if (version < 13) {
id = enumParticles[effect.getLegacyId()];
} else {
if (effect.getId() < 0)
throw new ParticleVersionException("The " + effect + " particle effect is not supported by your server version " + ParticlePacket.getVersion());
id = enumParticles[effect.getId()];
// TODO ... this isn't so easy, need to get the particle type and add data to it. Not actually
// sure enumParticles is going to work 1.13. Need to wait for a release to see, unfortunately.
}
packet_idField.set(packet, id);
packet_locationXField.set(packet, (float) center.getX());
packet_locationYField.set(packet, (float) center.getY());
packet_locationZField.set(packet, (float) center.getZ());
packet_offsetXField.set(packet, offsetX);
packet_offsetYField.set(packet, offsetY);
packet_offsetZField.set(packet, offsetZ);
packet_speedField.set(packet, speed);
packet_amountField.set(packet, amount);
if (packet_longDistanceField != null) {
packet_longDistanceField.set(packet, longDistance);
}
if (packet_dataField != null) {
packet_dataField.set(packet, data == null ? emptyData : data.getPacketData());
}
} catch (Exception exception) {
throw new PacketInstantiationException("Packet instantiation failed", exception);
}
}
try {
sendPacket.invoke(playerConnection.get(getHandle.invoke(player)), packet);
} catch (Exception exception) {
throw new PacketSendingException("Failed to send the packet to player '" + player.getName() + "'", exception);
}
}
public void sendTo(Location center, List<Player> players) throws IllegalArgumentException {
if (players.isEmpty()) {
throw new IllegalArgumentException("The player list is empty");
}
for (Player player : players) {
sendTo(center, player);
}
}
@SuppressWarnings("deprecation")
public void sendTo(Location center, double range) throws IllegalArgumentException {
if (range < 1) {
throw new IllegalArgumentException("The range is lower than 1");
}
String worldName = center.getWorld().getName();
double squared = range * range;
for (Player player : Bukkit.getOnlinePlayers()) {
if (!player.getWorld().getName().equals(worldName) || player.getLocation().distanceSquared(center) > squared) {
continue;
}
sendTo(center, player);
}
}
/**
* Represents a runtime exception that is thrown if a bukkit version is not compatible with this library
* <p>
* This class is part of the <b>ParticleEffect Library</b> and follows the same usage conditions
*
* @author DarkBlade12
* @since 1.5
*/
private static final class VersionIncompatibleException extends RuntimeException {
private static final long serialVersionUID = 3203085387160737484L;
/**
* Construct a new version incompatible exception
*
* @param message Message that will be logged
* @param cause Cause of the exception
*/
public VersionIncompatibleException(String message, Throwable cause) {
super(message, cause);
}
}
/**
* Represents a runtime exception that is thrown if packet instantiation fails
* <p>
* This class is part of the <b>ParticleEffect Library</b> and follows the same usage conditions
*
* @author DarkBlade12
* @since 1.4
*/
private static final class PacketInstantiationException extends RuntimeException {
private static final long serialVersionUID = 3203085387160737484L;
/**
* Construct a new packet instantiation exception
*
* @param message Message that will be logged
* @param cause Cause of the exception
*/
public PacketInstantiationException(String message, Throwable cause) {
super(message, cause);
}
}
/**
* Represents a runtime exception that is thrown if packet sending fails
* <p>
* This class is part of the <b>ParticleEffect Library</b> and follows the same usage conditions
*
* @author DarkBlade12
* @since 1.4
*/
private static final class PacketSendingException extends RuntimeException {
private static final long serialVersionUID = 3203085387160737484L;
/**
* Construct a new packet sending exception
*
* @param message Message that will be logged
* @param cause Cause of the exception
*/
public PacketSendingException(String message, Throwable cause) {
super(message, cause);
}
}
}
/**
* Helper method to migrate pre-3.0 Effects.
*
* @param center
* @param range
* @param offsetX
* @param offsetY
* @param offsetZ
* @param speed
* @param amount
*/
@Deprecated
public void display(Location center, double range, float offsetX, float offsetY, float offsetZ, float speed, int amount) {
display(offsetX, offsetY, offsetZ, speed, amount, center, range);
}
/**
* Helper method to migrate pre-3.0 Effects.
*
* @param center
* @param range
*/
@Deprecated
public void display(Location center, double range) {
display(0, 0, 0, 0, 1, center, range);
}
/**
* Helper method to migrate pre-3.0 Effects, and bridge parameterized effects.
*
* @param data
* @param center
* @param range
* @param offsetX
* @param offsetY
* @param offsetZ
* @param speed
* @param amount
*/
@Deprecated
public void display(ParticleData data, Location center, double range, float offsetX, float offsetY, float offsetZ, float speed, int amount) {
if (this.requiresData) {
display(data, offsetX, offsetY, offsetZ, speed, amount, center, range);
} else {
display(offsetX, offsetY, offsetZ, speed, amount, center, range);
}
}
public void display(Location center, Color color, double range) {
display(null, center, color, range, 0, 0, 0, 1, 0);
}
public void display(ParticleData data, Location center, Color color, double range, float offsetX, float offsetY, float offsetZ, float speed, int amount) {
display(data, center, color, range, offsetX, offsetY, offsetZ, speed, amount, null);
}
public void display(ParticleData data, Location center, Color color, double range, float offsetX, float offsetY, float offsetZ, float speed, int amount, List<Player> targetPlayers) {
// Colorizeable!
if (color != null && (this == ParticleEffect.REDSTONE || this == ParticleEffect.SPELL_MOB || this == ParticleEffect.SPELL_MOB_AMBIENT)) {
amount = 0;
// Colored particles can't have a speed of 0.
if (speed == 0) {
speed = 1;
}
offsetX = (float) color.getRed() / 255;
offsetY = (float) color.getGreen() / 255;
offsetZ = (float) color.getBlue() / 255;
// The redstone particle reverts to red if R is 0!
if (offsetX < Float.MIN_NORMAL) {
offsetX = Float.MIN_NORMAL;
}
}
if (this.requiresData) {
display(data, offsetX, offsetY, offsetZ, speed, amount, center, range, targetPlayers);
} else {
display(offsetX, offsetY, offsetZ, speed, amount, center, range, targetPlayers);
}
}
public boolean requiresData() {
return requiresData;
}
public boolean requiresWater() {
return requiresWater;
}
@SuppressWarnings("deprecation")
public ParticleData getData(Material material, Byte blockData) {
ParticleData data = null;
if (blockData == null) {
blockData = 0;
}
if (this == ParticleEffect.BLOCK_CRACK || this == ParticleEffect.ITEM_CRACK
|| this == ParticleEffect.BLOCK_DUST || this == ParticleEffect.FALLING_DUST) {
if (material != null && material != Material.AIR) {
if (this == ParticleEffect.ITEM_CRACK) {
data = new ParticleEffect.ItemData(material, blockData);
} else {
data = new ParticleEffect.BlockData(material, blockData);
}
}
}
return data;
}
}
|
package archimulator.service.impl;
import archimulator.model.Benchmark;
import archimulator.service.BenchmarkService;
import archimulator.service.ServiceManager;
import com.j256.ormlite.dao.Dao;
import net.pickapack.model.WithId;
import net.pickapack.service.AbstractService;
import java.util.Arrays;
import java.util.List;
/**
* @author Min Cai
*/
public class BenchmarkServiceImpl extends AbstractService implements BenchmarkService {
private Dao<Benchmark, Long> benchmarks;
@SuppressWarnings("unchecked")
public BenchmarkServiceImpl() {
super(ServiceManager.getDatabaseUrl(), Arrays.<Class<? extends WithId>>asList(Benchmark.class));
this.benchmarks = createDao(Benchmark.class);
}
//TODO: to be refactored to support the bundling of simulation mode and input set!!!
@Override
public void initialize() {
if (this.getBenchmarkByTitle("mst_baseline") == null) {
this.addBenchmark(new Benchmark(
"mst_baseline", ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/Olden_Custom1/mst/baseline",
"mst.mips",
"4000"));
}
if (this.getBenchmarkByTitle("mst_ht") == null) {
this.addBenchmark(new Benchmark(
"mst_ht", ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/Olden_Custom1/mst/ht",
"mst.mips",
"4000", "", true));
}
if (this.getBenchmarkByTitle("em3d_baseline") == null) {
this.addBenchmark(new Benchmark(
"em3d_baseline", ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/Olden_Custom1/em3d/baseline",
"em3d.mips",
"400000 128 75 1"));
}
if (this.getBenchmarkByTitle("em3d_ht") == null) {
this.addBenchmark(new Benchmark(
"em3d_ht", ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/Olden_Custom1/em3d/ht",
"em3d.mips",
"400000 128 75 1", "", true));
}
if (this.getBenchmarkByTitle("429_mcf_baseline") == null) {
this.addBenchmark(new Benchmark(
"429_mcf_baseline", ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/CPU2006_Custom1/429.mcf/baseline",
"429.mcf.mips",
ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/CPU2006_Custom1/429.mcf/baseline/data/ref/input/inp.in"));
}
if (this.getBenchmarkByTitle("429_mcf_ht") == null) {
this.addBenchmark(new Benchmark(
"429_mcf_ht", ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/CPU2006_Custom1/429.mcf/ht",
"429.mcf.mips",
ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/CPU2006_Custom1/429.mcf/ht/data/ref/input/inp.in", "", true));
}
if (this.getBenchmarkByTitle("462_libquantum_baseline") == null) {
this.addBenchmark(new Benchmark(
"462_libquantum_baseline", ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/CPU2006_Custom1/462.libquantum/baseline",
"462.libquantum.mips",
"1397 8"));
}
if (this.getBenchmarkByTitle("462_libquantum_ht") == null) {
this.addBenchmark(new Benchmark(
"462_libquantum_ht", ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/CPU2006_Custom1/462.libquantum/ht",
"462.libquantum.mips",
"1397 8", "", true));
}
if (this.getBenchmarkByTitle("mst_baseline_sim") == null) {
this.addBenchmark(new Benchmark(
"mst_baseline_sim", ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/Olden_Custom1/mst/baseline",
"mst.mips",
"1024"));
}
if (this.getBenchmarkByTitle("mst_ht_sim") == null) {
this.addBenchmark(new Benchmark(
"mst_ht_sim", ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/Olden_Custom1/mst/ht",
"mst.mips",
"1024", "", true));
}
if (this.getBenchmarkByTitle("em3d_baseline_sim") == null) {
this.addBenchmark(new Benchmark(
"em3d_baseline_sim", ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/Olden_Custom1/em3d/baseline",
"em3d.mips",
"4000 128 75 1"));
}
if (this.getBenchmarkByTitle("em3d_ht_sim") == null) {
this.addBenchmark(new Benchmark(
"em3d_ht_sim", ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/Olden_Custom1/em3d/ht",
"em3d.mips",
"4000 128 75 1", "", true));
}
if (this.getBenchmarkByTitle("429_mcf_baseline_sim") == null) {
this.addBenchmark(new Benchmark(
"429_mcf_baseline_sim", ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/CPU2006_Custom1/429.mcf/baseline",
"429.mcf.mips",
ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/CPU2006_Custom1/429.mcf/baseline/data/ref/input/inp.in"));
}
if (this.getBenchmarkByTitle("429_mcf_ht_sim") == null) {
this.addBenchmark(new Benchmark(
"429_mcf_ht_sim", ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/CPU2006_Custom1/429.mcf/ht",
"429.mcf.mips",
ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/CPU2006_Custom1/429.mcf/ht/data/ref/input/inp.in", "", true));
}
if (this.getBenchmarkByTitle("462_libquantum_baseline_sim") == null) {
this.addBenchmark(new Benchmark(
"462_libquantum_baseline_sim", ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/CPU2006_Custom1/462.libquantum/baseline",
"462.libquantum.mips",
"1397 8"));
}
if (this.getBenchmarkByTitle("462_libquantum_ht_sim") == null) {
this.addBenchmark(new Benchmark(
"462_libquantum_ht_sim", ServiceManager.USER_HOME_TEMPLATE_ARG + "/Archimulator/benchmarks/CPU2006_Custom1/462.libquantum/ht",
"462.libquantum.mips",
"1397 8", "", true));
}
}
/**
* @return
*/
@Override
public List<Benchmark> getAllBenchmarks() {
return this.getItems(this.benchmarks);
}
/**
* @param first
* @param count
* @return
*/
@Override
public List<Benchmark> getAllBenchmarks(long first, long count) {
return this.getItems(this.benchmarks, first, count);
}
/**
* @return
*/
@Override
public long getNumAllBenchmarks() {
return this.getNumItems(this.benchmarks);
}
/**
* @param id
* @return
*/
@Override
public Benchmark getBenchmarkById(long id) {
return this.getItemById(this.benchmarks, id);
}
/**
* @param title
* @return
*/
@Override
public Benchmark getBenchmarkByTitle(String title) {
return this.getFirstItemByTitle(this.benchmarks, title);
}
/**
* @return
*/
@Override
public Benchmark getFirstBenchmark() {
return this.getFirstItem(this.benchmarks);
}
/**
* @param benchmark
* @return
*/
@Override
public long addBenchmark(Benchmark benchmark) {
return this.addItem(this.benchmarks, benchmark);
}
/**
* @param id
*/
@Override
public void removeBenchmarkById(long id) {
this.removeItemById(this.benchmarks, id);
}
@Override
public void clearBenchmarks() {
this.clearItems(this.benchmarks);
}
/**
* @param benchmark
*/
@Override
public void updateBenchmark(Benchmark benchmark) {
this.updateItem(this.benchmarks, benchmark);
}
}
|
package be.bow.db.bloomfilter;
import be.bow.db.DataInterface;
import be.bow.db.LayeredDataInterface;
import be.bow.iterator.CloseableIterator;
import be.bow.ui.UI;
import java.util.concurrent.locks.ReentrantLock;
public class BloomFilterDataInterface<T extends Object> extends LayeredDataInterface<T> {
private static final boolean DEBUG = false;
/**
* TODO: optimize these variables
*/
private final static double INITIAL_FPP = 0.001;
private final static double MAX_FPP = 0.05;
private final DataInterface<LongBloomFilterWithCheckSum> bloomFilterDataInterface;
private LongBloomFilterWithCheckSum bloomFilter;
private ReentrantLock modifyBloomFilterLock;
private long currentKeyForNewBloomFilterCreation = Long.MAX_VALUE;
private int truePositive;
private int falsePositive;
public BloomFilterDataInterface(DataInterface<T> baseInterface, DataInterface<LongBloomFilterWithCheckSum> bloomFilterDataInterface) {
super(baseInterface);
this.bloomFilterDataInterface = bloomFilterDataInterface;
this.modifyBloomFilterLock = new ReentrantLock();
}
private void createNewBloomFilter() {
baseInterface.flush(); //Make sure all values are written to disk
long numOfValuesForBloomFilter = Math.max(1000, baseInterface.apprSize());
UI.write("Creating bloomfilter " + getName());
currentKeyForNewBloomFilterCreation = Long.MIN_VALUE;
bloomFilter = new LongBloomFilterWithCheckSum(numOfValuesForBloomFilter, INITIAL_FPP);
bloomFilter.setDataCheckSum(baseInterface.dataCheckSum());
long start = System.currentTimeMillis();
int numOfKeys = 0;
CloseableIterator<Long> it = baseInterface.keyIterator();
while (it.hasNext()) {
long key = it.next();
bloomFilter.put(key);
numOfKeys++;
currentKeyForNewBloomFilterCreation = key;
}
it.close();
long taken = (System.currentTimeMillis() - start);
UI.write("Created bloomfilter " + getName() + " in " + taken + " ms for " + numOfKeys + " keys.");
}
@Override
public T readInt(long key) {
checkInitialization();
if (bloomFilter == null || currentKeyForNewBloomFilterCreation < key) {
//we are still creating the bloom filter
return baseInterface.read(key);
} else {
boolean mightContainValue = true;
try {
mightContainValue = bloomFilter.mightContain(key);
} catch (NullPointerException exp) {
//bloom filter might have become null. We don't use a lock to prevent that case since that slows things down too much.
}
if (mightContainValue) {
T value = baseInterface.read(key);
if (DEBUG) {
if (value != null) {
truePositive++;
} else {
falsePositive++;
}
}
return value;
} else {
return null;
}
}
}
private void checkInitialization() {
if (bloomFilter == null) {
if (modifyBloomFilterLock.tryLock()) {
bloomFilter = bloomFilterDataInterface.read(getName());
if (bloomFilter == null || bloomFilter.getDataCheckSum() != baseInterface.dataCheckSum()) {
createNewBloomFilter();
bloomFilterDataInterface.write(getName(), bloomFilter);
}
modifyBloomFilterLock.unlock();
}
}
}
@Override
public void dropAllData() {
modifyBloomFilterLock.lock();
try {
baseInterface.dropAllData();
bloomFilterDataInterface.remove(getName());
bloomFilter = null;
} finally {
modifyBloomFilterLock.unlock();
}
}
public int getTruePositive() {
return truePositive;
}
public int getFalsePositive() {
return falsePositive;
}
@Override
public boolean mightContain(long key) {
checkInitialization();
if (bloomFilter == null) {
//we are still creating the bloom filter
return baseInterface.mightContain(key);
} else {
return bloomFilter.mightContain(key);
}
}
@Override
public void valuesChanged(long[] keys) {
super.valuesChanged(keys);
modifyBloomFilterLock.lock();
if (bloomFilter != null) {
for (Long key : keys) {
bloomFilter.put(key);
}
if (bloomFilter.expectedFpp() > MAX_FPP) {
bloomFilter = null;
}
}
modifyBloomFilterLock.unlock();
}
}
|
package edu.jhu.gm.maxent;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import edu.jhu.gm.data.FgExampleList;
import edu.jhu.gm.feat.FeatureVector;
import edu.jhu.gm.maxent.LogLinearObsFeatsData.LogLinearExample;
import edu.jhu.gm.maxent.LogLinearObsFeats.LogLinearObsFeatsPrm;
import edu.jhu.gm.model.DenseFactor;
import edu.jhu.gm.model.FgModel;
import edu.jhu.gm.train.AvgBatchObjective;
import edu.jhu.gm.train.CrfObjective;
import edu.jhu.gm.train.CrfObjectiveTest;
import edu.jhu.prim.arrays.DoubleArrays;
import edu.jhu.prim.tuple.Pair;
import edu.jhu.util.JUnitUtils;
import edu.jhu.util.collections.Lists;
public class LogLinearObsFeatsTest {
@Test
public void testLogLinearModelTrainDecode() {
LogLinearObsFeatsData exs = new LogLinearObsFeatsData();
exs.addEx(30, "y=A", Lists.getList("BIAS", "circle", "solid"));
exs.addEx(15, "y=B", Lists.getList("BIAS", "circle"));
exs.addEx(10, "y=C", Lists.getList("BIAS", "solid"));
exs.addEx(5, "y=D", Lists.getList("BIAS"));
List<LogLinearExample> data = exs.getData();
LogLinearObsFeatsPrm prm = new LogLinearObsFeatsPrm();
prm.includeUnsupportedFeatures = false;
LogLinearObsFeats td = new LogLinearObsFeats(prm);
FgModel model = td.train(exs);
{
Pair<String,DenseFactor> p = td.decode(model, data.get(0));
String predLabel = p.get1();
DenseFactor dist = p.get2();
System.out.println(Arrays.toString(dist.getValues()));
assertEquals("y=A", predLabel);
double[] goldLogMarg = new double[] { -2.6635044410250623, -2.4546874985293083, -0.1790960208295953,
-4.781808684934602 };
DoubleArrays.exp(goldLogMarg);
JUnitUtils.assertArrayEquals(goldLogMarg, dist.getValues(), 1e-3);
}
{
Pair<String,DenseFactor> p = td.decode(model, data.get(1));
String predLabel = p.get1();
DenseFactor dist = p.get2();
System.out.println(Arrays.toString(dist.getValues()));
assertEquals("y=B", predLabel);
double[] goldLogMarg = new double[] { -3.4406673404005783, -0.34125259077453896, -1.6728440342006794,
-2.668373777179833 };
DoubleArrays.exp(goldLogMarg);
JUnitUtils.assertArrayEquals(goldLogMarg, dist.getValues(), 1e-3);
}
}
@Test
public void testLogLinearModelShapesLogProbs() {
// Test with inference in the log-domain.
boolean logDomain = true;
testLogLinearModelShapesHelper(logDomain);
}
@Test
public void testLogLinearModelShapesProbs() {
// Test with inference in the prob-domain.
boolean logDomain = false;
testLogLinearModelShapesHelper(logDomain);
}
@Test
public void testLogLinearModelShapesTwoExamplesLogProbs() {
boolean logDomain = true;
testLogLinearModelShapesTwoExamplesHelper(logDomain);
}
@Test
public void testLogLinearModelShapesTwoExamplesProbs() {
boolean logDomain = false;
testLogLinearModelShapesTwoExamplesHelper(logDomain);
}
@Test
public void testLogLinearModelShapesOneExampleLogProbs() {
boolean logDomain = true;
testLogLinearModelShapesOneExampleHelper(logDomain);
}
@Test
public void testLogLinearModelShapesOneExampleProbs() {
boolean logDomain = false;
testLogLinearModelShapesOneExampleHelper(logDomain);
}
private void testLogLinearModelShapesHelper(boolean logDomain) {
LogLinearObsFeatsData exs = new LogLinearObsFeatsData();
exs.addEx(30, "y=A", Lists.getList("BIAS", "circle", "solid"));
exs.addEx(15, "y=B", Lists.getList("BIAS", "circle"));
exs.addEx(10, "y=C", Lists.getList("BIAS", "solid"));
exs.addEx(5, "y=D", Lists.getList("BIAS"));
LogLinearObsFeatsPrm prm = new LogLinearObsFeatsPrm();
prm.includeUnsupportedFeatures = false;
LogLinearObsFeats td = new LogLinearObsFeats(prm);
FgExampleList data = td.getData(exs);
double[] params = new double[]{3.0, 2.0, 1.0, 4.0, 5.0, 6.0, 7.0, 8.0};
FgModel model = new FgModel(params.length);
model.updateModelFromDoubles(params);
System.out.println(model);
System.out.println(td.getOfc().toString());
// Test log-likelihood.
CrfObjective exObj = new CrfObjective(data, CrfObjectiveTest.getInfFactory(logDomain));
AvgBatchObjective obj = new AvgBatchObjective(exObj, model, 1);
// Test log-likelihood.
double ll = obj.getValue(model.getParams())
;
System.out.println(ll);
//assertEquals(-2.687, ll, 1e-3);
// Test observed feature counts.
FeatureVector obsFeats = exObj.getObservedFeatureCounts(model, params);
assertEquals(10, obsFeats.get(0), 1e-13);
assertEquals(10, obsFeats.get(1), 1e-13);
assertEquals(15, obsFeats.get(2), 1e-13);
assertEquals(15, obsFeats.get(3), 1e-13);
// Test expected feature counts.
FeatureVector expFeats = exObj.getExpectedFeatureCounts(model, params);
assertEquals(0.045, expFeats.get(0), 1e-3);
assertEquals(0.009, expFeats.get(1), 1e-3);
// Test gradient.
double[] gradient = obj.getGradient(model.getParams()).toNativeArray();
System.out.println(Arrays.toString(gradient));
JUnitUtils.assertArrayEquals(new double[] { 0.16590575430912835, 0.16651642575232348, 0.24933555564704535,
0.24941014930579491, -0.4049252957987691, -0.23748187663263962, -0.16349489515194487,
-0.01031601415740464 }, gradient, 1e-3);
}
private void testLogLinearModelShapesTwoExamplesHelper(boolean logDomain) {
LogLinearObsFeatsData exs = new LogLinearObsFeatsData();
exs.addEx(1, "y=A", Lists.getList("circle"));
exs.addEx(1, "y=B", Lists.getList("circle"));
double[] params = new double[]{2.0, 3.0};
LogLinearObsFeatsPrm prm = new LogLinearObsFeatsPrm();
prm.includeUnsupportedFeatures = false;
LogLinearObsFeats td = new LogLinearObsFeats(prm);
FgExampleList data = td.getData(exs);
FgModel model = new FgModel(params.length);
model.updateModelFromDoubles(params);
CrfObjective exObj = new CrfObjective(data, CrfObjectiveTest.getInfFactory(logDomain));
AvgBatchObjective obj = new AvgBatchObjective(exObj, model, 1);
assertEquals(1, exs.getAlphabet().size());
// Test average log-likelihood.
double ll = obj.getValue(model.getParams());
System.out.println(ll + " " + Math.exp(ll));
assertEquals(((3*1 + 2*1) - 2*Math.log((Math.exp(3*1) + Math.exp(2*1)))) / 2.0, ll, 1e-2);
// Test observed feature counts.
FeatureVector obsFeats = exObj.getObservedFeatureCounts(model, params);
assertEquals(1, obsFeats.get(0), 1e-13);
assertEquals(1, obsFeats.get(1), 1e-13);
// Test expected feature counts.
FeatureVector expFeats = exObj.getExpectedFeatureCounts(model, params);
assertEquals(1.4621, expFeats.get(1), 1e-3);
assertEquals(0.5378, expFeats.get(0), 1e-3);
// Test gradient.
double[] gradient = obj.getGradient(model.getParams()).toNativeArray();
double[] expectedGradient = new double[]{1.0 - 0.5378, 1.0 - 1.4621};
DoubleArrays.scale(expectedGradient, 1.0/2.0);
JUnitUtils.assertArrayEquals(expectedGradient, gradient, 1e-3);
}
private void testLogLinearModelShapesOneExampleHelper(boolean logDomain) {
LogLinearObsFeatsData exs = new LogLinearObsFeatsData();
exs.addEx(1, "y=A", Lists.getList("circle"));
exs.addEx(0, "y=B", Lists.getList("circle"));
double[] params = new double[]{2.0, 3.0};
LogLinearObsFeatsPrm prm = new LogLinearObsFeatsPrm();
prm.includeUnsupportedFeatures = true;
LogLinearObsFeats td = new LogLinearObsFeats(prm);
FgExampleList data = td.getData(exs);
FgModel model = new FgModel(params.length);
model.updateModelFromDoubles(params);
CrfObjective exObj = new CrfObjective(data, CrfObjectiveTest.getInfFactory(logDomain));
AvgBatchObjective obj = new AvgBatchObjective(exObj, model, 1);
assertEquals(1, exs.getAlphabet().size());
// Test log-likelihood.
double ll = obj.getValue(model.getParams())
;
System.out.println(ll);
assertEquals(3*1 - Math.log(Math.exp(3*1) + Math.exp(2*1)), ll, 1e-2);
// Test observed feature counts.
FeatureVector obsFeats = exObj.getObservedFeatureCounts(model, params);
assertEquals(0, obsFeats.get(0), 1e-13);
assertEquals(1, obsFeats.get(1), 1e-13);
// Test expected feature counts.
FeatureVector expFeats = exObj.getExpectedFeatureCounts(model, params);
assertEquals(0.2689, expFeats.get(0), 1e-3);
assertEquals(0.7310, expFeats.get(1), 1e-3);
// Test gradient.
double[] gradient = obj.getGradient(model.getParams()).toNativeArray();
JUnitUtils.assertArrayEquals(new double[]{-0.2689, 0.2689}, gradient, 1e-3);
}
}
|
// (MIT)
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// copies or substantial portions of the Software.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package be.yildiz.shared.mission;
import be.yildiz.common.id.PlayerId;
public interface MissionStatusListener <T extends Mission> {
void missionReady(T mission, PlayerId playerId);
void missionStarted(T mission, PlayerId playerId);
void missionSuccess(T mission, PlayerId playerId);
void missionFailed(T mission, PlayerId playerId);
}
|
package edu.virginia.psyc.pi.domain;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Questionnaire DAO's that are labeled with this class should not be removed
* after export. This information will be communicated to clients, so they
* know they should follow up with delete commands after they have successfully
* backed up the data.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE) //can use in method only.
public @interface DoNotDelete {}
|
package br.com.fourdev.orderfood.service;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.fourdev.orderfood.model.Pedido;
import br.com.fourdev.orderfood.model.StatusPedido;
import br.com.fourdev.orderfood.repository.pedido.PedidoRepository;
@Service
public class PedidoService {
final static Logger logger = LoggerFactory.getLogger(PedidoService.class);
@Autowired
private PedidoRepository pedidoRepository;
public List<Pedido> pedidosAbertos() {
StatusPedido statusPedido = StatusPedido.ABERTO;
return pedidoRepository.retornaStatusPedido(statusPedido);
}
public List<Pedido> pedidosEmAndamento() {
StatusPedido statusPedido = StatusPedido.EMANDAMENTO;
return pedidoRepository.retornaStatusPedido(statusPedido);
}
public List<Pedido> pedidosFechados() {
StatusPedido statusPedido = StatusPedido.FINALIZADO;
return pedidoRepository.retornaStatusPedido(statusPedido);
}
public List<Pedido> pedidosEmCancelados() {
StatusPedido statusPedido = StatusPedido.CANCELADO;
return pedidoRepository.retornaStatusPedido(statusPedido);
}
public List<Pedido> retornaPedidoPorMesa(int idmesa) {
return pedidoRepository.retornaPedidoPorMesa(idmesa);
}
// public StatusPedido reservarMesa() {
// return pedidoRepository.selectProdutoList();
}
|
package com.airbnb.plog.stats;
import com.airbnb.plog.fragmentation.Defragmenter;
import com.google.common.cache.CacheStats;
import com.yammer.metrics.core.Meter;
import kafka.producer.*;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicLongArray;
@RequiredArgsConstructor
@Slf4j
public final class SimpleStatisticsReporter implements StatisticsReporter {
private final AtomicLong
holesFromDeadPort = new AtomicLong(),
holesFromNewMessage = new AtomicLong(),
udpSimpleMessages = new AtomicLong(),
udpInvalidVersion = new AtomicLong(),
v0InvalidType = new AtomicLong(),
unknownCommand = new AtomicLong(),
v0Commands = new AtomicLong(),
v0MultipartMessages = new AtomicLong(),
failedToSend = new AtomicLong(),
exceptions = new AtomicLong();
private final AtomicLongArray
v0MultipartMessageFragments = new AtomicLongArray(Short.SIZE + 1),
v0InvalidChecksum = new AtomicLongArray(Short.SIZE + 1),
droppedFragments = new AtomicLongArray((Short.SIZE + 1) * (Short.SIZE + 1)),
invalidFragments = new AtomicLongArray((Short.SIZE + 1) * (Short.SIZE + 1));
private final String kafkaClientId;
private Defragmenter defragmenter = null;
private final long startTime = System.currentTimeMillis();
private static final int intLog2(int i) {
return Integer.SIZE - Integer.numberOfLeadingZeros(i);
}
@Override
public final long receivedUdpSimpleMessage() {
return this.udpSimpleMessages.incrementAndGet();
}
@Override
public final long receivedUdpInvalidVersion() {
return this.udpInvalidVersion.incrementAndGet();
}
@Override
public final long receivedV0InvalidType() {
return this.v0InvalidType.incrementAndGet();
}
@Override
public final long receivedV0Command() {
return this.v0Commands.incrementAndGet();
}
@Override
public final long receivedUnknownCommand() {
return this.unknownCommand.incrementAndGet();
}
@Override
public final long receivedV0MultipartMessage() {
return this.v0MultipartMessages.incrementAndGet();
}
@Override
public long failedToSend() {
return this.failedToSend.incrementAndGet();
}
@Override
public long exception() {
return this.exceptions.incrementAndGet();
}
@Override
public long foundHolesFromDeadPort(int holesFound) {
return holesFromDeadPort.addAndGet(holesFound);
}
@Override
public long foundHolesFromNewMessage(int holesFound) {
return holesFromNewMessage.addAndGet(holesFound);
}
@Override
public final long receivedV0MultipartFragment(final int index) {
return v0MultipartMessageFragments.incrementAndGet(intLog2(index));
}
@Override
public final long receivedV0InvalidChecksum(int fragments) {
return this.v0InvalidChecksum.incrementAndGet(intLog2(fragments - 1));
}
@Override
public long receivedV0InvalidMultipartFragment(final int fragmentIndex, final int expectedFragments) {
final int target = (Short.SIZE * intLog2(expectedFragments - 1)) + intLog2(fragmentIndex);
return invalidFragments.incrementAndGet(target);
}
@Override
public long missingFragmentInDroppedMessage(final int fragmentIndex, final int expectedFragments) {
final int target = (Short.SIZE * intLog2(expectedFragments - 1)) + intLog2(fragmentIndex);
return droppedFragments.incrementAndGet(target);
}
public final String toJSON() {
StringBuilder builder = new StringBuilder();
builder.append("{\"uptime\":");
builder.append(System.currentTimeMillis() - this.startTime);
builder.append(",\"udp_simple_messages\":");
builder.append(this.udpSimpleMessages.get());
builder.append(",\"udp_invalid_version\":");
builder.append(this.udpInvalidVersion.get());
builder.append(",\"v0_invalid_type\":");
builder.append(this.v0InvalidType.get());
builder.append(",\"unknown_command\":");
builder.append(this.unknownCommand.get());
builder.append(",\"v0_commands\":");
builder.append(this.v0Commands.get());
builder.append(",\"failed_to_send\":");
builder.append(this.failedToSend.get());
builder.append(",\"exceptions\":");
builder.append(this.exceptions.get());
builder.append(",\"holes_from_dead_port\":");
builder.append(this.holesFromDeadPort.get());
builder.append(",\"holes_from_new_message\":");
builder.append(this.holesFromNewMessage.get());
builder.append(',');
appendLogStats(builder, "v0_fragments", v0MultipartMessageFragments);
builder.append(',');
appendLogStats(builder, "v0_invalid_checksum", v0InvalidChecksum);
builder.append(',');
appendLogLogStats(builder, "v0_invalid_fragments", invalidFragments);
builder.append(',');
appendLogLogStats(builder, "dropped_fragments", droppedFragments);
if (defragmenter != null) {
final CacheStats cacheStats = defragmenter.getCacheStats();
builder.append(",\"cache\":{\"evictions\":");
builder.append(cacheStats.evictionCount());
builder.append(",\"hits\":");
builder.append(cacheStats.hitCount());
builder.append(",\"misses\":");
builder.append(cacheStats.missCount());
builder.append('}');
}
if (kafkaClientId != null)
appendKafka(builder);
builder.append("}");
return builder.toString();
}
private void appendKafka(StringBuilder builder) {
builder.append(",\"kafka\":{");
final ProducerStats producerStats = ProducerStatsRegistry.getProducerStats(kafkaClientId);
final ProducerTopicStats producerTopicStats = ProducerTopicStatsRegistry.getProducerTopicStats(kafkaClientId);
final ProducerTopicMetrics producerAllTopicsStats = producerTopicStats.getProducerAllTopicsStats();
builder.append("\"serializationErrorRate\":{");
report(producerStats.serializationErrorRate(), builder);
builder.append("},\"failedSendRate\":{");
report(producerStats.failedSendRate(), builder);
builder.append("},\"resendRate\":{");
report(producerStats.resendRate(), builder);
builder.append("},\"byteRate\":{");
report(producerAllTopicsStats.byteRate(), builder);
builder.append("},\"droppedMessageRate\":{");
report(producerAllTopicsStats.droppedMessageRate(), builder);
builder.append("},\"messageRate\":{");
report(producerAllTopicsStats.messageRate(), builder);
builder.append("}}");
}
private void appendLogStats(StringBuilder builder, String name, AtomicLongArray data) {
builder.append('\"');
builder.append(name);
builder.append("\":[");
for (int i = 0; i < data.length(); i++) {
builder.append(data.get(i));
builder.append(',');
}
builder.append(data.get(data.length() - 1));
builder.append(']');
}
private void appendLogLogStats(StringBuilder builder, String name, AtomicLongArray data) {
builder.append('\"');
builder.append(name);
builder.append("\":[");
for (int packetCountLog = 0; packetCountLog <= Short.SIZE; packetCountLog++) {
builder.append('[');
for (int packetIndexLog = 0; packetIndexLog <= Short.SIZE; packetIndexLog++) {
builder.append(data.get(packetCountLog * (Short.SIZE + 1) + packetIndexLog));
if (packetIndexLog != Short.SIZE)
builder.append(',');
}
builder.append(']');
if (packetCountLog != Short.SIZE)
builder.append(',');
}
builder.append(']');
}
private void report(Meter meter, StringBuilder builder) {
builder.append("\"count\":");
builder.append(meter.count());
builder.append(",\"rate\":[");
builder.append(meter.oneMinuteRate());
builder.append(',');
builder.append(meter.fiveMinuteRate());
builder.append(',');
builder.append(meter.fifteenMinuteRate());
builder.append(']');
}
public synchronized void withDefrag(Defragmenter defragmenter) {
if (this.defragmenter == null)
this.defragmenter = defragmenter;
else
throw new IllegalStateException("Defragmenter already provided");
}
}
|
package com.bailei.study.jzoffer.interview6;
public class BinaryTree {
private BinaryTreeNode root;
public BinaryTreeNode reconstruct(int[] preOrder, int[] inOrder) {
root = null;
return reconstruct(preOrder, inOrder, 0, preOrder.length - 1,
0, inOrder.length - 1);
}
public void preOrder() {
preOrder(root);
System.out.println();
}
private void preOrder(BinaryTreeNode root) {
if (root != null) {
System.out.print(root + ", ");
preOrder(root.pLeft);
preOrder(root.pRight);
}
}
private BinaryTreeNode reconstruct(int[] preOrder, int[] inOrder,
int startPre, int endPre,
int startIn, int endIn) {
int lengthPre = endPre - startPre + 1;
int lengthIn = endIn - startIn + 1;
if (lengthPre == 0 || lengthIn == 0) {
return null;
}
if (lengthPre == 1 || lengthIn == 1) {
return new BinaryTreeNode(preOrder[startPre]);
}
int rootValue = preOrder[startPre];
int rootValueIndexOfInOrder = -1;
for (int i = startIn; i <= endIn; i++) {
if (rootValue == inOrder[i]) {
rootValueIndexOfInOrder = i;
break;
}
}
if (rootValueIndexOfInOrder == -1) {
throw new RuntimeException("");
}
int leftLength = rootValueIndexOfInOrder - startIn;
int rightLength = endIn - rootValueIndexOfInOrder;
BinaryTreeNode rootNode = new BinaryTreeNode(rootValue);
if (root == null) {
root = rootNode;
}
if (leftLength > 0) {
rootNode.pLeft = reconstruct(preOrder, inOrder,
startPre + 1, startPre + leftLength,
startIn, startIn + leftLength - 1);
}
if (rightLength > 0) {
rootNode.pRight = reconstruct(preOrder, inOrder,
startPre + leftLength + 1, startPre + leftLength + rightLength,
rootValueIndexOfInOrder + 1, rootValueIndexOfInOrder + rightLength);
}
return rootNode;
}
public static void main(String[] args) {
int[] preOrder = {1, 2, 4, 7, 3, 5, 6, 8};
int[] inOrder = {4, 7, 2, 1, 5, 3, 8, 6};
BinaryTree binaryTree = new BinaryTree();
binaryTree.reconstruct(preOrder, inOrder);
binaryTree.preOrder();
int[] preOrder1 = {1, 2, 3, 4, 5};
int[] inOrder1 = {5, 4, 3, 2, 1};
binaryTree.reconstruct(preOrder1, inOrder1);
binaryTree.preOrder();
int[] preOrder2 = {1, 2, 3, 4, 5};
int[] inOrder2 = {1, 2, 3, 4, 5};
binaryTree.reconstruct(preOrder2, inOrder2);
binaryTree.preOrder();
}
}
|
package fr.liglab.lcm.mapred;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.mapreduce.Reducer;
import fr.liglab.lcm.mapred.writables.ItemAndSupportWritable;
import fr.liglab.lcm.mapred.writables.SupportAndTransactionWritable;
import gnu.trove.map.TIntIntMap;
public class AggregationReducer extends
Reducer<ItemAndSupportWritable, SupportAndTransactionWritable, IntWritable, SupportAndTransactionWritable> {
protected final IntWritable keyW = new IntWritable();
protected final SupportAndTransactionWritable valueW = new SupportAndTransactionWritable();
protected TIntIntMap reverseBase = null;
protected int k;
@Override
protected void setup(Context context) throws java.io.IOException, InterruptedException {
if (this.reverseBase == null) {
Configuration conf = context.getConfiguration();
this.k = conf.getInt(Driver.KEY_DO_TOP_K, -1);
this.reverseBase = DistCache.readReverseRebasing(conf);
}
}
protected void reduce(ItemAndSupportWritable key, java.lang.Iterable<SupportAndTransactionWritable> patterns,
Context context) throws java.io.IOException, InterruptedException {
int rebased = this.reverseBase.get(key.getItem());
this.keyW.set(rebased);
int count = 0;
for (SupportAndTransactionWritable entry : patterns) {
int[] transaction = entry.getTransaction();
for (int i = 0; i < transaction.length; i++) {
transaction[i] = this.reverseBase.get(transaction[i]);
}
this.valueW.set(entry.getSupport(), transaction);
context.write(this.keyW, this.valueW);
count++;
if (count == this.k) {
break;
}
}
}
}
|
package com.celements.rights;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.celements.rights.publication.IPublicationServiceRole;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.user.api.XWikiRightNotFoundException;
import com.xpn.xwiki.user.impl.xwiki.XWikiRightServiceImpl;
import com.xpn.xwiki.web.Utils;
public class CelementsRightServiceImpl extends XWikiRightServiceImpl {
private static Logger LOGGER = LoggerFactory.getLogger(CelementsRightServiceImpl.class);
/*
* Adds an optional check for publish and unpublish dates to determine whether or not a
* page can be viewed.
*/
@Override
public boolean checkRight(String userOrGroupName, XWikiDocument doc, String accessLevel,
boolean user, boolean allow, boolean global, XWikiContext context)
throws XWikiRightNotFoundException, XWikiException {
if (getPubSrv().isPublishActive() && getPubSrv().isRestrictedRightsAction(accessLevel)) {
// default behaviour: no object -> published
if (!getPubSrv().isPubOverride() && (getPubSrv().isUnpubOverride() || getPubSrv().isPublished(
doc))) {
LOGGER.info("Document published or not publish controlled.");
return super.checkRight(userOrGroupName, doc, accessLevel, user, allow, global, context);
} else {
LOGGER.info("Document not published, checking edit rights.");
try {
return super.checkRight(userOrGroupName, doc, "edit", user, allow, global, context);
} catch (XWikiRightNotFoundException xwrnfe) {
LOGGER.info("Rights could not be determined.");
// If rights can not be determined default to no rights.
return false;
}
}
} else {
if (getPubSrv().isPubUnpubOverride()) {
LOGGER.warn("Needs CelementsRightServiceImpl for publish / unpublish to work");
}
return super.checkRight(userOrGroupName, doc, accessLevel, user, allow, global, context);
}
}
IPublicationServiceRole getPubSrv() {
return Utils.getComponent(IPublicationServiceRole.class);
}
@Override
public boolean hasProgrammingRights(XWikiDocument doc, XWikiContext context) {
LOGGER.debug("hasProgrammingRights checking for '{}'", (doc != null)
? doc.getDocumentReference() : "null");
final boolean hasRights = super.hasProgrammingRights(doc, context);
LOGGER.info("hasProgrammingRights for '{}' returning '{}'", (doc != null)
? doc.getDocumentReference() : "null", hasRights);
if (!hasRights && (doc != null)) {
LOGGER.trace("hasProgrammingRights FALSE for '{}' with contentAuthor '{}' and context '{}'",
doc.getDocumentReference(), doc.getContentAuthor(), context);
}
return hasRights;
}
}
|
package gg.uhc.uhc.modules.portals;
import com.google.common.base.Joiner;
import com.google.common.collect.Iterables;
import com.google.common.collect.Sets;
import gg.uhc.uhc.modules.DisableableModule;
import gg.uhc.uhc.modules.team.FunctionalUtil;
import org.bukkit.*;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityPortalEvent;
import org.bukkit.event.player.PlayerPortalEvent;
import java.util.Set;
public class NetherModule extends DisableableModule implements Listener {
protected static final String ICON_NAME = "Nether";
public NetherModule() {
this.iconName = ICON_NAME;
this.icon.setType(Material.NETHER_STALK);
}
@Override
public void rerender() {
super.rerender();
if (isEnabled()) {
icon.setLore("Travelling to the nether is enabled");
} else {
icon.setLore("Travelling to the nether is disabled");
}
}
@Override
public void onDisable() {
Set<OfflinePlayer> players = Sets.newHashSet();
Set<String> worlds = Sets.newHashSet();
for (World world : Bukkit.getWorlds()) {
if (world.getEnvironment() == World.Environment.NETHER) {
worlds.add(world.getName());
players.addAll(world.getPlayers());
}
}
if (players.size() == 0) return;
Joiner joiner = Joiner.on(", ");
String playerNames = joiner.join(Iterables.transform(players, FunctionalUtil.PLAYER_NAME_FETCHER));
String worldNames = joiner.join(worlds);
String message = "The player/s [" + playerNames + "] are within the nether world/s: [" + worldNames + "].";
Bukkit.getConsoleSender().sendMessage(message);
Bukkit.broadcast(ChatColor.DARK_GRAY + message, "uhc.broadcast.netherdisable");
}
@EventHandler(ignoreCancelled = true)
public void on(EntityPortalEvent event) {
if (isEnabled()) return;
if (event.getTo().getWorld().getEnvironment() == World.Environment.NETHER)
event.setCancelled(true);
}
@EventHandler(ignoreCancelled = true)
public void on(PlayerPortalEvent event) {
if (isEnabled()) return;
if (event.getTo().getWorld().getEnvironment() == World.Environment.NETHER)
event.setCancelled(true);
}
@Override
protected boolean isEnabledByDefault() {
return true;
}
}
|
package i5.las2peer.httpConnector.client;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Constructor;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import i5.las2peer.httpConnector.coder.InvalidCodingException;
import i5.las2peer.httpConnector.coder.ParamCoder;
import i5.las2peer.httpConnector.coder.ParamDecoder;
/**
* The connector client is the basic class for accessing a remote LAS2peer server via the http connector within any java
* application.
*
*/
public class Client {
public static final int DEFAULT_PORT = 8080;
public static final long DEFAULT_TIMEOUT_MS = 60 * 60 * 10; // 10 minutes
public static final long DEFAULT_OUTDATE_S = 60 * 60 * 24; // 1 day
public static final int WAIT_INTERVAL = 200;
public static final int MAX_WAIT = 10 * 1000;
public static final String DEFAULT_CODER = "i5.las2peer.httpConnector.coder.XmlCoder";
public static final String DEFAULT_DECODER = "i5.las2peer.httpConnector.coder.XmlDecoder";
private String coderClass = DEFAULT_CODER;
private String decoderClass = DEFAULT_DECODER;
private String sHost;
private int iPort = DEFAULT_PORT;
private String sUser = null;
private String sPasswd = null;
private long lTimeOutMs = DEFAULT_TIMEOUT_MS;
private boolean bConnected = false;
private String sSessionId = null;
// private boolean bUsePersistent = false;
private long lOutdateS = DEFAULT_OUTDATE_S;
private boolean bTryPersistent = false;
private boolean bIsPersistent = false;
private boolean bUseHttps = false;
/**
* Constructor
*
* @param host target host name
*
*/
public Client(String host) {
sHost = host;
}
/**
* Constructor
*
* @param host target host name
* @param port http connector port on the target host
*
*/
public Client(String host, int port) {
sHost = host;
iPort = port;
}
/**
* Constructor
*
* @param host target host name
* @param port http connector port on the target host
* @param user login name
* @param passwd password
*
*/
public Client(String host, int port, String user, String passwd) {
this(host, port);
sUser = user;
sPasswd = passwd;
}
/**
* Constructor for reataching to a remote session
*
* @param host a String
* @param port an int
* @param user a String
* @param passwd a String
* @param session a String
*
*/
public Client(String host, int port, String user, String passwd, String session) {
this(host, port, user, passwd);
this.sSessionId = session;
this.bTryPersistent = true;
}
/**
* Constructor
*
* @param host target host name
* @param port http connector port on the target host
* @param timeout timeout of the generated session in milliseconds
*
*/
public Client(String host, int port, long timeout) {
sHost = host;
iPort = port;
lTimeOutMs = timeout;
}
/**
* Constructor
*
* @param host target host name
* @param timeout timeout of the generated session in milliseconds
*
*/
public Client(String host, long timeout) {
sHost = host;
lTimeOutMs = timeout;
}
/**
* Constructor
*
* @param host target host name
* @param port http connector port on the target host
* @param timeout timeout of the generated session in milliseconds
* @param user login name
* @param passwd password
*
*/
public Client(String host, int port, long timeout, String user, String passwd) {
sHost = host;
iPort = port;
lTimeOutMs = timeout;
sUser = user;
sPasswd = passwd;
}
/**
* set the password for the current user
*
* @param passwd new password to use
*
* @exception ConnectorClientException client is currently connected
*
*/
public void setPasswd(String passwd) throws ConnectorClientException {
if (bConnected)
throw new ConnectorClientException("Don't change the client setting during a session!");
sPasswd = passwd;
}
/**
*
* @return name of the LAS2peer user
*
*/
public String getUser() {
return sUser;
}
/**
* set the user login name for connecting to the remote las server
*
* @param user a String
*
* @exception ConnectorClientException client is currently connected
*
*/
public void setUser(String user) throws ConnectorClientException {
if (bConnected)
throw new ConnectorClientException("Don't change the client setting during a session!");
sUser = user;
}
/**
*
* @return name or ip of the las server host
*
*/
public String getHost() {
return sHost;
}
/**
* Set the target host of the las server to connect to
*
* @param host new hostname
*
* @exception ConnectorClientException client is currently connected
*
*/
public void setHost(String host) throws ConnectorClientException {
if (bConnected)
throw new ConnectorClientException("Don't change the client setting during a session!");
sHost = host;
}
/**
*
* @return the number of the used port at the las server
*
*/
public int getPort() {
return iPort;
}
/**
* Set the port of the connector
*
* @param port new port number
*
* @exception ConnectorClientException client is currently connected
*
*/
public void setPort(int port) throws ConnectorClientException {
if (bConnected)
throw new ConnectorClientException("Don't change the client setting during a session!");
iPort = port;
}
/**
* set the flag if the client is to try to open persistent sessions
*
* @param tryP a boolean
*
* @exception ConnectorClientException client is currently connected
*
*/
public void setTryPersistent(boolean tryP) throws ConnectorClientException {
if (bConnected)
throw new ConnectorClientException("Don't change the client setting during a session!");
bTryPersistent = tryP;
}
/**
* returns of the client tries to open persistent sessions
*
* @return a boolean
*
*/
public boolean getTryPersistent() {
return bTryPersistent;
}
/**
* returns true if the client is connected and the session is persistent
*
* @return a boolean
*
*/
public boolean isPersistent() {
return bConnected && bIsPersistent;
}
/**
* return the (tried or real) session timeout in ms
*
* @return a long
*
*/
public long getSessionTimeout() {
return lTimeOutMs;
}
/**
* Set the session timeout value to be requested on the next connection opening
*
* @param time timespan in ms
*
* @exception ConnectorClientException client is currently connected
*
*/
public void setSessionTimeout(long time) throws ConnectorClientException {
if (bConnected)
throw new ConnectorClientException("Don't change the client setting during a session!");
lTimeOutMs = time;
}
/**
* return the (tried or real) session outdate time in s
*
* @return a long
*
*/
public long getSessionOutdate() {
return lOutdateS;
}
/**
* set the outedate time to use for opening new sessions
*
* @param outdate timespan in s
*
* @exception ConnectorClientException client is currently connected
*
*/
public void setSessionOutdate(long outdate) throws ConnectorClientException {
if (bConnected)
throw new ConnectorClientException("Don't change the client setting during a session!");
lOutdateS = outdate;
}
/**
* returns if the client uses an https connection to the remote las
*
* @return a boolean
*
*/
public boolean isUsingHttps() {
return bUseHttps;
}
/**
* change the setting for the usage of the https protocol
*
* @param use a boolean
*
* @exception ConnectorClientException
*
*/
public void setUseHttps(boolean use) throws ConnectorClientException {
if (bConnected)
throw new ConnectorClientException("Don't change client settings during a session!");
bUseHttps = use;
}
/**
* Tries to connect to the LAS2peer server with the current connection data.
*
* This method will be implicitly called on an attempt to use a not existing connection.
*
* @exception AuthenticationFailedException
* @exception UnableToConnectException
*
*/
public void connect() throws AuthenticationFailedException, UnableToConnectException {
if (bConnected)
return;
if (sSessionId != null)
reattachToSession();
else
createSession();
}
/**
* Tries to open a new session with the current connection data
*
* @exception UnableToConnectException
*
*/
private void createSession() throws UnableToConnectException, AuthenticationFailedException {
if (bConnected)
return;
bIsPersistent = false;
String sProtocol = (bUseHttps) ? "https:
String sTimeout = "timeout=" + lTimeOutMs;
try {
String sUrl = "";
if (sUser == null)
sUrl = sProtocol + sHost + ":" + iPort + "/createsession?" + sTimeout;
else
sUrl = sProtocol + sHost + ":" + iPort + "/createsession?user=" + sUser + "&passwd=" + sPasswd + "&"
+ sTimeout;
if (bTryPersistent) {
if (sUser == null)
sUrl += "?";
else
sUrl += "&";
sUrl += "persistent=1&outdate=" + lOutdateS;
}
URL url = new URL(sUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
int length = conn.getContentLength();
if (conn.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)
throw new AuthenticationFailedException();
String type = conn.getContentType();
if (!"text/xml".equals(type))
throw new UnableToConnectException("Invalid Server answer: " + type + " - is this a LAS2peer server?");
String content = readHttpContent((InputStream) conn.getContent(), length);
try {
interpretSessionContent(content);
} catch (InvalidServerAnswerException e) {
throw new UnableToConnectException("Problems interpreting server response to create session request!",
e);
}
bConnected = true;
} catch (IOException e) {
throw new UnableToConnectException(e);
} catch (UnableToConnectException e) {
if (bTryPersistent) {
// try a non-persistent session!
bTryPersistent = false;
createSession();
} else {
throw e;
}
}
}
/**
* tries to reattach to an existing (persitent) session using the current connection data
*
*/
private void reattachToSession() throws UnableToConnectException {
if (bConnected)
return;
String sProtocol = (bUseHttps) ? "https:
if (sUser == null || sPasswd == null)
throw new UnableToConnectException("No user / Password given for reattaching");
if (sSessionId == null)
throw new UnableToConnectException("No session id given for reattaching");
try {
URL url = new URL(sProtocol + sHost + ":" + iPort + "/attachsession?user=" + sUser + "&passwd=" + sPasswd
+ "&SESSION=" + sSessionId);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)
throw new UnableToConnectException(
"Unable to connect to remote session - response code: " + conn.getResponseCode());
bConnected = true;
bIsPersistent = true;
} catch (IOException e) {
throw new UnableToConnectException("IOException during connection attempt!", e);
}
}
/**
* disconnects an open connection
*
* @exception InvalidServerAnswerException
* @exception UnableToConnectException
*
*/
public void disconnect() throws InvalidServerAnswerException, UnableToConnectException {
if (!bConnected)
return;
String sProtocol = (bUseHttps) ? "https:
try {
URL url = new URL(sProtocol + sHost + ":" + iPort + "/closesession?SESSION=" + sSessionId);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// int length = conn.getContentLength();
if (conn.getResponseCode() == HttpURLConnection.HTTP_PRECON_FAILED) {
// session expired
} else if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new InvalidServerAnswerException("Returncode from server: " + conn.getResponseCode());
}
bConnected = false;
sSessionId = null;
} catch (IOException e) {
bConnected = false;
throw new UnableToConnectException(e);
}
}
/**
* tries to detach from the current session
*
* @exception InvalidServerAnswerException
* @exception ConnectorClientException
*
*/
public void detach() throws InvalidServerAnswerException, ConnectorClientException {
if (!bConnected)
return;
String sProtocol = (bUseHttps) ? "https:
try {
URL url = new URL(sProtocol + sHost + ":" + iPort + "/detachsession?SESSION=" + sSessionId);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() != HttpURLConnection.HTTP_OK)
throw new ConnectorClientException("Unable to detach - response code: " + conn.getResponseCode());
else
bConnected = false;
} catch (IOException e) {
throw new ConnectorClientException("Unable to detach - IOException in connection", e);
}
}
/**
* reads the content of an http answer into a resulting string the length of the expected content if given by the
* length parameter
*
* @param content an InputStream
* @param length an int
*
* @return a String
*
*/
private String readHttpContent(InputStream content, int length) throws UnableToConnectException, IOException {
int iWait = 0;
while (content.available() < length) {
iWait += WAIT_INTERVAL;
try {
Thread.sleep(WAIT_INTERVAL);
} catch (InterruptedException e) {
}
if (iWait >= MAX_WAIT)
throw new UnableToConnectException("Timeout at " + iWait + " milliseconds!");
}
InputStreamReader isr = new InputStreamReader(content);
char[] con = new char[length];
isr.read(con);
String sContent = new String(con);
return sContent;
}
/**
* Set the code class to be used for encoding message parameters
*
* @param className a String
*
*/
public void setCoderClass(String className) {
coderClass = className;
}
/**
* returns the currently used coder class
*
* @return a String
*
*/
public String getCoder() {
return coderClass;
}
/**
* returns if the client is currently connected
*
* @return a boolean
*
*/
public boolean isConnected() {
return isConnected(false);
}
/**
* returns if the client is currently connected
*
* depending on the tryTouch parameter a touchSession is invoked before returning the connective flag
*
* @param tryTouch a boolean
*
* @return a boolean
*
*/
public boolean isConnected(boolean tryTouch) {
try {
if (tryTouch)
touchSession();
} catch (ConnectorClientException e) {
bConnected = false;
return false;
}
return bConnected;
}
/**
* returns the id of the currently used session at the server
*
* @return a String
*
*/
public String getSessionId() {
return sSessionId;
}
/**
* returns the timeout in milliseconds of the currently open session.
*
* @return a long
*
*/
public long getTimeoutMs() {
return lTimeOutMs;
}
/**
* Invokes a service method at the server. If not connected a connections attempt will be performed. The result of
* the call will be returned as an object.
*
*
* @param service a String
* @param method a String
* @param params an Object[]
*
* @return an Object
*
* @exception UnableToConnectException
* @exception AuthenticationFailedException
* @exception TimeoutException
* @exception ParameterTypeNotImplementedException
* @exception ServerErrorException
* @exception AccessDeniedException
* @exception NotFoundException
* @exception ConnectorClientException
*
*/
public Object invoke(String service, String method, Object... params)
throws UnableToConnectException, AuthenticationFailedException, TimeoutException, ServerErrorException,
AccessDeniedException, NotFoundException, ConnectorClientException {
if (!bConnected)
connect();
try {
URL url = new URL((bUseHttps) ? "https" : "http", sHost, iPort,
"/" + service + "/" + method + "?SESSION=" + sSessionId);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Content-Type", "text/xml");
if (params != null && params.length > 0) {
String paramCode = getParameterCoding(params);
// ok, code the parameters into a post call
connection.setDoOutput(true);
OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
osw.write(paramCode);
osw.flush();
osw.close();
}
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_FORBIDDEN)
throw new AccessDeniedException();
if (responseCode == HttpURLConnection.HTTP_NOT_FOUND // method unavailable
|| responseCode == 503) // service unavailable
throw new NotFoundException();
if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
String mess = "Remote Exception during invocation";
try {
if ("text/xml".equals(connection.getContentType())) {
// we have a object array response describing the exception
Object[] result = (Object[]) interpretInvocationResult(
(InputStream) connection.getErrorStream());
throw new ServerErrorException((Exception) result[3]);
} else
// simple text message (to stay compatible to older versions of the connector
mess = readHttpContent((InputStream) connection.getErrorStream(),
connection.getContentLength());
} catch (ServerErrorException e) {
throw e;
} catch (Exception e) {
e.printStackTrace();
mess += "Unable to create cause Exception: " + e;
}
throw new ServerErrorException(mess);
}
if (responseCode == HttpURLConnection.HTTP_PRECON_FAILED)
throw new TimeoutException();
if (responseCode == HttpURLConnection.HTTP_NO_CONTENT)
return null;
if (responseCode == HttpURLConnection.HTTP_NOT_ACCEPTABLE)
throw new ConnectorClientException("The server could no read the invocation parameters!");
if (responseCode == HttpURLConnection.HTTP_NOT_IMPLEMENTED) {
// String mess = ""; //readHttpContent( (InputStream) connection.getContent(),
// connection.getContentLength() );
throw new ReturnTypeNotImplementedException();
}
String type = connection.getContentType();
// int length = connection.getContentLength();
if (!"text/xml".equals(type))
throw new ConnectorClientException(
"Problems to interpret the server's answer - content type not text/xml!");
Object result = interpretInvocationResult((InputStream) connection.getContent());
return result;
} catch (IOException e) {
bConnected = false;
throw new UnableToConnectException("IOException with the connection!", e);
}
}
/**
* writes an encoding of the object parameter array to the outputStream
*
* @param params an Object[]
*
* @exception ParameterTypeNotImplementedException
* @exception IOException
* @exception ConnectorClientException
*
*/
public String getParameterCoding(Object[] params)
throws ParameterTypeNotImplementedException, IOException, ConnectorClientException {
try {
ParamCoder coder = null;
StringWriter sw = new StringWriter();
try {
@SuppressWarnings("rawtypes")
Constructor constr = Class.forName(coderClass).getConstructor(new Class[] { Writer.class });
coder = (ParamCoder) constr.newInstance(new Object[] { sw });
} catch (Exception e) {
throw new ConnectorClientException("Unable to loadecoader!", e);
}
coder.header(params.length);
for (int i = 0; i < params.length; i++) {
coder.write(params[i]);
}
coder.footer();
return sw.toString();
} catch (i5.las2peer.httpConnector.coder.ParameterTypeNotImplementedException e) {
throw new ParameterTypeNotImplementedException(
"One or more of the invocation parameters could not be coded for transfer!", e);
}
}
/**
* tries to touch the session at the server
*
* @exception ConnectorClientException
*
*/
public void touchSession() throws ConnectorClientException {
if (!bConnected)
return;
try {
URL url = new URL(bUseHttps ? "https" : "http", sHost, iPort, "/touchsession?SESSION=" + sSessionId);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// int length = conn.getContentLength();
int response = conn.getResponseCode();
if (response == 401) { // 401 = UNAUTHORIZED
throw new ConnectorClientException("The Session I tried to access does not exist!!");
} else if (response != HttpURLConnection.HTTP_NO_CONTENT) {
throw new ConnectorClientException("Unkown Answer!");
}
// ok, touch was successfull
} catch (IOException e) {
bConnected = false;
throw new ConnectorClientException("I/O-Exception in the http connection!", e);
}
}
/**
* interprets the content of a open session request an sets the attributes of the connection
*
* @param content a String
*
* @exception InvalidServerAnswerException
*
*/
private void interpretSessionContent(String content) throws InvalidServerAnswerException {
String[] lines = content.split("\\s*\r?\n\\s*");
if (!lines[0].matches("<\\?xml\\s+version=\"1.0\"\\s*\\?>"))
throw new InvalidServerAnswerException("answer is not xml conform ( lacking header )");
if (lines[1].matches("<session persistent=\"true\">"))
bIsPersistent = true;
else if (!lines[1].trim().matches("<session>"))
throw new InvalidServerAnswerException(
"answer has not the expected root node (<session>)" + lines[1] + "..." + content);
Matcher m = Pattern.compile("<id>([^>]+)</id>").matcher(lines[2]);
if (m.matches()) {
sSessionId = m.group(1);
} else
throw new InvalidServerAnswerException("first element of session is not the id!");
m = Pattern.compile("<timeout>([0-9]+)</timeout>").matcher(lines[3]);
if (m.matches()) {
lTimeOutMs = Long.valueOf(m.group(1)).longValue();
} else
throw new InvalidServerAnswerException("Second element of session is not the timeout!");
m = Pattern.compile("<outdate>([0-9]+)</outdate>").matcher(lines[4]);
if (m.matches()) {
lOutdateS = Long.valueOf(m.group(1)).longValue();
}
}
/**
* tries to interpret the content of the urlConnections (given as InputStream) either as a single object or an
* array.
*
* @param content an InputStream
*
* @return an Object
*
* @exception ConnectorClientException
* @exception IOException
* @exception InvalidCodingException
*
*/
private Object interpretInvocationResult(InputStream content) throws ConnectorClientException {
ParamDecoder decoder = null;
try {
@SuppressWarnings("rawtypes")
Constructor constr = Class.forName(decoderClass).getConstructor(new Class[] { InputStream.class });
decoder = (ParamDecoder) constr.newInstance(new Object[] { content });
} catch (Exception e) {
throw new ConnectorClientException("Unable to instanciate decoder class " + decoderClass + "!", e);
}
Object result = null;
try {
int count = decoder.checkHeader();
if (count != 1)
result = decoder.decodeArray();
else
result = decoder.decodeSingle();
decoder.checkFooter();
} catch (IOException e) {
throw new ConnectorClientException("Error with the connections input stream", e);
} catch (InvalidCodingException e) {
throw new ConnectorClientException("Response of the server is not interpretable as an Object!", e);
}
return result;
}
}
|
package com.cube.storm.ui.lib.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.text.TextUtils;
import com.cube.storm.UiSettings;
import com.cube.storm.ui.data.FragmentIntent;
import com.cube.storm.ui.data.FragmentPackage;
import com.cube.storm.ui.model.descriptor.TabbedPageDescriptor;
import com.cube.storm.ui.model.property.ImageProperty;
import com.cube.storm.ui.view.PagerSlidingTabStrip.IconTabProvider;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
/**
* // TODO: Add class description
*
* @author Callum Taylor
* @project StormUI
*/
public class StormPageAdapter extends FragmentStatePagerAdapter implements IconTabProvider
{
protected final Context context;
protected final FragmentManager manager;
@Setter @Getter protected int index = 0;
@Getter private List<FragmentPackage> pages = new ArrayList<FragmentPackage>(0);
public StormPageAdapter(Context context, FragmentManager manager)
{
super(manager);
this.context = context;
this.manager = manager;
}
public void setPages(@NonNull Collection<FragmentPackage> pages)
{
this.pages = new ArrayList<FragmentPackage>(pages.size());
this.pages.addAll(pages);
}
@Override public Fragment getItem(int index)
{
FragmentIntent intent = pages.get(index).getFragmentIntent();
return Fragment.instantiate(context, intent.getFragment().getName(), intent.getArguments());
}
@Override public CharSequence getPageTitle(int position)
{
FragmentPackage fragmentPackage = pages.get(position % pages.size());
if (fragmentPackage.getPageDescriptor() != null)
{
if (fragmentPackage.getPageDescriptor() instanceof TabbedPageDescriptor)
{
if (((TabbedPageDescriptor)fragmentPackage.getPageDescriptor()).getTabBarItem().getTitle() != null)
{
return UiSettings.getInstance().getTextProcessor().process(((TabbedPageDescriptor)fragmentPackage.getPageDescriptor()).getTabBarItem().getTitle().getContent());
}
}
String tabName = "";
if (!TextUtils.isEmpty(fragmentPackage.getPageDescriptor().getName()))
{
tabName = fragmentPackage.getPageDescriptor().getName();
}
return UiSettings.getInstance().getTextProcessor().process(tabName);
}
else if (!TextUtils.isEmpty(fragmentPackage.getFragmentIntent().getTitle()))
{
return fragmentPackage.getFragmentIntent().getTitle();
}
return "";
}
@Override public int getPageIconResId(int position)
{
return 0;
}
@Override public Bitmap getPageIconBitmap(int position)
{
FragmentPackage fragmentPackage = pages.get(position % pages.size());
Bitmap image = null;
if (fragmentPackage.getPageDescriptor() instanceof TabbedPageDescriptor)
{
if (((TabbedPageDescriptor)fragmentPackage.getPageDescriptor()).getTabBarItem().getImage() != null)
{
ImageProperty imageProperty = ((TabbedPageDescriptor)fragmentPackage.getPageDescriptor()).getTabBarItem().getImage();
image = UiSettings.getInstance().getImageLoader().loadImageSync(imageProperty.getSrc());
if (image == null && !TextUtils.isEmpty(imageProperty.getFallbackSrc()))
{
image = UiSettings.getInstance().getImageLoader().loadImageSync(imageProperty.getFallbackSrc());
}
return image;
}
}
return null;
}
@Override public int getCount()
{
return this.pages.size();
}
}
|
package com.ewolff.orderhandling.fileparser;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.springframework.stereotype.Component;
import com.ewolff.orderhandling.domain.Order;
import com.ewolff.orderhandling.domain.OrderItem;
@Component
public class FileParser {
public List<Order> parse(String content) {
List<Order> result = new ArrayList<Order>();
StringTokenizer stringTokenizer = new StringTokenizer(content, ",");
while (stringTokenizer.hasMoreTokens()) {
Order order = new Order(false, Integer.parseInt(stringTokenizer
.nextToken()));
order.addOrderItem(new OrderItem(Integer.parseInt(stringTokenizer
.nextToken()), stringTokenizer.nextToken(), Integer
.parseInt(stringTokenizer.nextToken())));
order.setExpress(stringTokenizer.nextToken().equalsIgnoreCase(
"express"));
result.add(order);
}
return result;
}
}
|
package com.foundationdb.ais.util;
import com.foundationdb.ais.model.AbstractVisitor;
import com.foundationdb.ais.model.Column;
import com.foundationdb.ais.model.ColumnName;
import com.foundationdb.ais.model.ForeignKey;
import com.foundationdb.ais.model.GroupIndex;
import com.foundationdb.ais.model.Index;
import com.foundationdb.ais.model.IndexColumn;
import com.foundationdb.ais.model.Join;
import com.foundationdb.ais.model.JoinColumn;
import com.foundationdb.ais.model.Sequence;
import com.foundationdb.ais.model.Table;
import com.foundationdb.ais.model.TableIndex;
import com.foundationdb.ais.model.TableName;
import com.foundationdb.server.store.format.columnkeys.ColumnKeysStorageDescription;
import com.foundationdb.util.ArgumentValidation;
import com.google.common.base.Objects;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import static com.foundationdb.ais.util.ChangedTableDescription.ParentChange;
import static com.foundationdb.ais.util.TableChangeValidatorException.*;
public class TableChangeValidator {
private static final Map<String,String> EMPTY_STRING_MAP = Collections.emptyMap();
private static final List<TableName> EMPTY_TABLE_NAME_LIST = Collections.emptyList();
public static enum ChangeLevel {
NONE,
METADATA,
METADATA_CONSTRAINT,
INDEX,
// TODO: Ugly. Final change level should be a Set and/or constraint changes passed separately.
INDEX_CONSTRAINT,
TABLE,
GROUP
}
private final Table oldTable;
private final Table newTable;
private final TableChangeValidatorState state;
private final List<RuntimeException> unmodifiedChanges;
private ChangeLevel finalChangeLevel;
private ChangedTableDescription.ParentChange parentChange;
private boolean primaryKeyChanged;
private boolean didCompare;
public TableChangeValidator(Table oldTable,
Table newTable,
List<TableChange> columnChanges,
List<TableChange> tableIndexChanges) {
ArgumentValidation.notNull("oldTable", oldTable);
ArgumentValidation.notNull("newTable", newTable);
ArgumentValidation.notNull("columnChanges", columnChanges);
ArgumentValidation.notNull("tableIndexChanges", tableIndexChanges);
this.oldTable = oldTable;
this.newTable = newTable;
this.state = new TableChangeValidatorState(columnChanges, tableIndexChanges);
this.unmodifiedChanges = new ArrayList<>();
this.finalChangeLevel = ChangeLevel.NONE;
this.parentChange = ParentChange.NONE;
}
public ChangeLevel getFinalChangeLevel() {
return finalChangeLevel;
}
public TableChangeValidatorState getState() {
return state;
}
public boolean isParentChanged() {
return (parentChange == ParentChange.ADD) || (parentChange == ParentChange.DROP);
}
public boolean isPrimaryKeyChanged() {
return primaryKeyChanged;
}
public List<RuntimeException> getUnmodifiedChanges() {
return unmodifiedChanges;
}
public void compare() {
if(!didCompare) {
compareTable();
compareColumns();
compareIndexes();
compareGrouping();
compareGroupIndexes();
compareForeignKeys();
updateFinalChangeLevel(ChangeLevel.NONE);
checkFinalChangeLevel();
didCompare = true;
}
}
private void updateFinalChangeLevel(ChangeLevel level) {
if(level.ordinal() > finalChangeLevel.ordinal()) {
finalChangeLevel = level;
}
}
private void compareTable() {
TableName oldName = oldTable.getName();
TableName newName = newTable.getName();
if(!oldName.equals(newName) ||
!Objects.equal(oldTable.getCharsetName(), newTable.getCharsetName()) ||
!Objects.equal(oldTable.getCollationName(), newTable.getCollationName())) {
updateFinalChangeLevel(ChangeLevel.METADATA);
}
}
private void compareColumns() {
Map<String,Column> oldColumns = new HashMap<>();
Map<String,Column> newColumns = new HashMap<>();
for(Column column : oldTable.getColumnsIncludingInternal()) {
oldColumns.put(column.getName(), column);
}
for(Column column : newTable.getColumnsIncludingInternal()) {
newColumns.put(column.getName(), column);
}
checkChanges(ChangeLevel.TABLE, state.columnChanges, oldColumns, newColumns, false);
// Look for position changes, not required to be declared
for(Map.Entry<String, Column> oldEntry : oldColumns.entrySet()) {
Column newColumn = newColumns.get(findNewName(state.columnChanges, oldEntry.getKey()));
if((newColumn != null) && !oldEntry.getValue().getPosition().equals(newColumn.getPosition())) {
updateFinalChangeLevel(ChangeLevel.TABLE);
break;
}
}
}
private void compareIndexes() {
Map<String,TableIndex> oldIndexes = new HashMap<>();
Map<String,TableIndex> newIndexes = new HashMap<>();
for(TableIndex index : oldTable.getIndexesIncludingInternal()) {
oldIndexes.put(index.getIndexName().getName(), index);
}
// Look for incompatible spatial changes
for(TableIndex oldIndex : oldTable.getIndexesIncludingInternal()) {
String oldName = oldIndex.getIndexName().getName();
String newName = findNewName(state.tableIndexChanges, oldName);
TableIndex newIndex = (newName != null) ? newTable.getIndexIncludingInternal(newName) : null;
if((newIndex != null) && oldIndex.isSpatial() && !Index.isSpatialCompatible(newIndex)) {
newTable.removeIndexes(Collections.singleton(newIndex));
// Remove any entry that already exists (e.g. MODIFY from compareColumns())
Iterator<TableChange> it = state.tableIndexChanges.iterator();
while(it.hasNext()) {
TableChange c = it.next();
if(oldName.equals(c.getOldName())) {
it.remove();
break;
}
}
}
}
for(TableIndex index : newTable.getIndexesIncludingInternal()) {
newIndexes.put(index.getIndexName().getName(), index);
}
checkChanges(ChangeLevel.INDEX, state.tableIndexChanges, oldIndexes, newIndexes, true);
}
private void compareGroupIndexes() {
final Set<Table> keepTables = new HashSet<>();
final Table traverseStart;
if(parentChange == ParentChange.DROP) {
traverseStart = oldTable;
} else {
traverseStart = oldTable.getGroup().getRoot();
}
traverseStart.visit(new AbstractVisitor() {
@Override
public void visit(Table table) {
keepTables.add(table);
}
});
for(GroupIndex index : oldTable.getGroupIndexes()) {
boolean dataChange = (finalChangeLevel == ChangeLevel.GROUP);
List<ColumnName> remainingCols = new ArrayList<>();
for(IndexColumn iCol : index.getKeyColumns()) {
Column column = iCol.getColumn();
if(!keepTables.contains(column.getTable())) {
remainingCols.clear();
break;
}
String oldName = column.getName();
boolean isTargetTable = column.getTable() == oldTable;
String newName = isTargetTable ? findNewName(state.columnChanges, oldName) : oldName;
if(newName != null) {
TableName tableName = isTargetTable ? newTable.getName() : column.getTable().getName();
remainingCols.add(new ColumnName(tableName, newName));
if(column.getTable() == oldTable) {
Column oldColumn = oldTable.getColumn(oldName);
Column newColumn = newTable.getColumn(newName);
dataChange |= (compare(oldColumn, newColumn) == ChangeLevel.TABLE);
}
} else {
dataChange = true;
}
}
if(remainingCols.size() <= 1) {
remainingCols.clear();
state.droppedGI.add(index.getIndexName().getName());
} else {
state.affectedGI.put(index.getIndexName().getName(), remainingCols);
if(dataChange) {
state.dataAffectedGI.put(index.getIndexName().getName(), remainingCols);
}
}
}
}
private <T> void checkChanges(ChangeLevel level, List<TableChange> changeList, Map<String,T> oldMap, Map<String,T> newMap, boolean doAutoChanges) {
final boolean isIndex = (level == ChangeLevel.INDEX);
Set<String> oldExcludes = new HashSet<>();
Set<String> newExcludes = new HashSet<>();
List<TableChange> autoChanges = doAutoChanges ? new ArrayList<TableChange>() : null;
// Check declared changes
for(TableChange change : changeList) {
String oldName = change.getOldName();
String newName = change.getNewName();
switch(change.getChangeType()) {
case ADD: {
if(newMap.get(newName) == null) {
if(doAutoChanges) {
autoChanges.add(TableChange.createAdd(newName));
} else {
addNotPresent(isIndex, change);
}
} else {
updateFinalChangeLevel(level);
newExcludes.add(newName);
}
}
break;
case DROP: {
if(oldMap.get(oldName) == null) {
dropNotPresent(isIndex, change);
} else {
updateFinalChangeLevel(level);
oldExcludes.add(oldName);
}
}
break;
case MODIFY: {
T oldVal = oldMap.get(oldName);
T newVal = newMap.get(newName);
if((oldVal == null) || (newVal == null)) {
modifyNotPresent(isIndex, change);
} else {
ChangeLevel curChange = compare(oldVal, newVal);
if(curChange == ChangeLevel.NONE) {
unmodifiedChanges.add(modifyNotChanged(isIndex, change));
} else {
updateFinalChangeLevel(curChange);
oldExcludes.add(oldName);
newExcludes.add(newName);
}
}
}
break;
}
}
// Check remaining elements in old table
for(Map.Entry<String,T> entry : oldMap.entrySet()) {
String name = entry.getKey();
if(!oldExcludes.contains(name)) {
T newVal = newMap.get(name);
if(newVal == null) {
if(doAutoChanges) {
autoChanges.add(TableChange.createDrop(name));
} else {
unchangedNotPresent(isIndex, name);
}
} else {
ChangeLevel change = compare(entry.getValue(), newVal);
if(change != ChangeLevel.NONE) {
if(doAutoChanges) {
autoChanges.add(TableChange.createModify(name, name));
} else {
undeclaredChange(isIndex, name);
}
}
newExcludes.add(name);
}
}
}
// Check remaining elements in new table (should be none)
for(String name : newMap.keySet()) {
if(!newExcludes.contains(name)) {
if(doAutoChanges) {
autoChanges.add(TableChange.createAdd(name));
} else {
undeclaredChange(isIndex, name);
}
}
}
if(doAutoChanges && !autoChanges.isEmpty()) {
changeList.addAll(autoChanges);
updateFinalChangeLevel(level);
}
}
private void compareGrouping() {
parentChange = compareParentJoin(state.columnChanges, oldTable.getParentJoin(), newTable.getParentJoin());
primaryKeyChanged = containsOldOrNew(state.tableIndexChanges, Index.PRIMARY);
List<TableName> droppedSequences = new ArrayList<>();
List<String> addedIdentity = new ArrayList<>();
Map<String,String> renamedColumns = new HashMap<>();
for(TableChange change : state.columnChanges) {
switch(change.getChangeType()) {
case MODIFY: {
if(!change.getOldName().equals(change.getNewName())) {
renamedColumns.put(change.getOldName(), change.getNewName());
}
Column oldColumn = oldTable.getColumn(change.getOldName());
Column newColumn = newTable.getColumn(change.getNewName());
if((oldColumn != null)) {
Sequence oldSeq = oldColumn.getIdentityGenerator();
Sequence newSeq = newColumn.getIdentityGenerator();
if((oldSeq == null) && (newSeq != null)) {
addedIdentity.add(newColumn.getName());
} else if((oldSeq != null) && (newSeq == null)) {
droppedSequences.add(oldSeq.getSequenceName());
}
// else both not null and not equal, not yet supported
}
} break;
case DROP: {
Column oldColumn = oldTable.getColumn(change.getOldName());
if((oldColumn != null) && (oldColumn.getIdentityGenerator() != null)) {
droppedSequences.add(oldColumn.getIdentityGenerator().getSequenceName());
}
} break;
case ADD: {
Column newColumn = newTable.getColumn(change.getNewName());
Sequence newSeq = newColumn.getIdentityGenerator();
if(newSeq != null) {
addedIdentity.add(newColumn.getName());
}
} break;
}
}
boolean renamed = !oldTable.getName().equals(newTable.getName()) || !renamedColumns.isEmpty();
Map<String,String> preserveIndexes = new TreeMap<>();
TableName parentName = (newTable.getParentJoin() != null) ? newTable.getParentJoin().getParent().getName() : null;
state.descriptions.add(
new ChangedTableDescription(
oldTable.getTableId(),
oldTable.getName(),
newTable,
renamedColumns,
parentChange,
parentName,
EMPTY_STRING_MAP,
preserveIndexes,
droppedSequences,
addedIdentity,
finalChangeLevel == ChangeLevel.TABLE,
isParentChanged() || primaryKeyChanged
)
);
if(!isParentChanged() && !primaryKeyChanged) {
for(Index index : newTable.getIndexesIncludingInternal()) {
String oldName = index.getIndexName().getName();
String newName = findNewName(state.tableIndexChanges, oldName);
if(!containsOldOrNew(state.tableIndexChanges, oldName)) {
preserveIndexes.put(oldName, newName);
}
}
}
Collection<Join> oldChildJoins = new ArrayList<>(oldTable.getCandidateChildJoins());
for(Join join : oldChildJoins) {
Table oldChildTable = join.getChild();
// If referenced column has anymore has a TABLE change (or is missing), join needs dropped
boolean dropParent = false;
for(JoinColumn joinCol : join.getJoinColumns()) {
Column oldColumn = joinCol.getParent().getColumn();
String newName = findNewName(state.columnChanges, oldColumn.getName());
if(newName == null) {
dropParent = true;
} else {
Column newColumn = newTable.getColumn(newName);
if(compare(oldColumn, newColumn) == ChangeLevel.TABLE) {
dropParent = true;
}
}
}
boolean preserve = false;
ParentChange change = null;
// If PK changed and table had children, PK was dropped
if(primaryKeyChanged || dropParent) {
updateFinalChangeLevel(ChangeLevel.GROUP);
change = ParentChange.DROP;
} else if(isParentChanged() || (parentChange == ParentChange.ADD)) {
updateFinalChangeLevel(ChangeLevel.GROUP);
change = ParentChange.UPDATE;
} else if(renamed) {
updateFinalChangeLevel(ChangeLevel.METADATA);
change = ParentChange.META;
preserve = true;
}
if(change != null) {
TableName newParent = (change == ParentChange.DROP) ? null : newTable.getName();
trackChangedTable(oldChildTable, change, newParent, renamedColumns, preserve);
propagateChildChange(oldChildTable, ParentChange.UPDATE, preserve);
}
}
if(isParentChanged() || primaryKeyChanged) {
updateFinalChangeLevel(ChangeLevel.GROUP);
}
}
private void compareForeignKeys() {
// Flag referenced table as having metadata changed
// No way to rename or alter a FK definition so only need to check presence change.
Set<TableName> referencedChanges = new HashSet<>();
for(ForeignKey fk : oldTable.getReferencingForeignKeys()) {
if(newTable.getReferencingForeignKey(fk.getConstraintName().getTableName()) == null) {
referencedChanges.add(fk.getReferencedTable().getName());
}
}
for(ForeignKey fk : newTable.getReferencingForeignKeys()) {
if(oldTable.getReferencingForeignKey(fk.getConstraintName().getTableName()) == null) {
referencedChanges.add(fk.getReferencedTable().getName());
}
}
// TODO: Would be nice to track complete details (e.g. constraint name) instead of just table
for(TableName refName : referencedChanges) {
if(!state.hasOldTable(refName)) {
Table table = oldTable.getAIS().getTable(refName);
TableName parentName = (table.getParentJoin() != null) ? table.getParentJoin().getParent().getName() : null;
trackChangedTable(table, ParentChange.NONE, parentName, null, true);
}
}
if(!referencedChanges.isEmpty()) {
switch(finalChangeLevel) {
case NONE:
case METADATA:
case METADATA_CONSTRAINT:
updateFinalChangeLevel(ChangeLevel.METADATA_CONSTRAINT);
break;
case INDEX:
if(!state.dataAffectedGI.isEmpty()) {
throw new IllegalStateException("New FOREIGN KEY and group index?");
}
updateFinalChangeLevel(ChangeLevel.INDEX_CONSTRAINT);
case TABLE:
case GROUP:
// None. These already have constraints checked.
break;
default:
assert false : finalChangeLevel;
}
}
}
private void propagateChildChange(final Table table, final ParentChange change, final boolean allIndexes) {
table.visitBreadthFirst(new AbstractVisitor() {
@Override
public void visit(Table curTable) {
if(table != curTable) {
TableName parentName = curTable.getParentJoin().getParent().getName();
trackChangedTable(curTable, change, parentName, null, allIndexes);
}
}
});
}
private void trackChangedTable(Table table, ParentChange parentChange, TableName parentName,
Map<String, String> parentRenames, boolean doPreserve) {
Map<String,String> preserved = new HashMap<>();
if(doPreserve) {
for(Index index : table.getIndexesIncludingInternal()) {
preserved.put(index.getIndexName().getName(), index.getIndexName().getName());
}
}
parentRenames = (parentRenames != null) ? parentRenames : EMPTY_STRING_MAP;
state.descriptions.add(
new ChangedTableDescription(
table.getTableId(),
table.getName(),
null,
EMPTY_STRING_MAP,
parentChange,
parentName,
parentRenames,
preserved,
EMPTY_TABLE_NAME_LIST,
Collections.<String>emptyList(),
false,
!doPreserve
)
);
}
private static boolean containsOldOrNew(List<TableChange> changes, String name) {
for(TableChange change : changes) {
if(name.equals(change.getOldName()) || name.equals(change.getNewName())) {
return true;
}
}
return false;
}
private static String findNewName(List<TableChange> changes, String oldName) {
for(TableChange change : changes) {
if(oldName.equals(change.getOldName())) {
switch(change.getChangeType()) {
case ADD: throw new IllegalStateException("Old name was added? " + oldName);
case DROP: return null;
case MODIFY: return change.getNewName();
}
}
}
return oldName;
}
private <T> ChangeLevel compare(T oldVal, T newVal) {
if(oldVal instanceof Column) {
return compare((Column)oldVal, (Column)newVal);
}
if(oldVal instanceof Index) {
return compare((Index)oldVal, (Index)newVal);
}
throw new IllegalStateException("Cannot compare: " + oldVal + " and " + newVal);
}
private static ChangeLevel compare(Column oldCol, Column newCol) {
if(!oldCol.getType().equalsExcludingNullable(newCol.getType())) {
return ChangeLevel.TABLE;
}
if(oldCol.getTable().getGroup().getStorageDescription() instanceof ColumnKeysStorageDescription &&
!oldCol.getName().equals(newCol.getName())) {
return ChangeLevel.TABLE;
}
boolean oldNull = oldCol.getNullable();
boolean newNull = newCol.getNullable();
if((oldNull == true) && (newNull == false)) {
return ChangeLevel.METADATA_CONSTRAINT;
}
if((oldNull != newNull) ||
!oldCol.getName().equals(newCol.getName()) ||
!Objects.equal(oldCol.getDefaultValue(), newCol.getDefaultValue()) ||
!Objects.equal(oldCol.getDefaultIdentity(), newCol.getDefaultIdentity()) ||
sequenceChanged(oldCol.getIdentityGenerator(), newCol.getIdentityGenerator())) {
return ChangeLevel.METADATA;
}
return ChangeLevel.NONE;
}
private ChangeLevel compare(Index oldIndex, Index newIndex) {
if(oldIndex.getKeyColumns().size() != newIndex.getKeyColumns().size()) {
return ChangeLevel.INDEX;
}
Iterator<IndexColumn> oldIt = oldIndex.getKeyColumns().iterator();
Iterator<IndexColumn> newIt = newIndex.getKeyColumns().iterator();
while(oldIt.hasNext()) {
IndexColumn oldICol = oldIt.next();
IndexColumn newICol = newIt.next();
String newColName = findNewName(state.columnChanges, oldICol.getColumn().getName());
// Column the same?
if((newColName == null) || !newICol.getColumn().getName().equals(newColName)) {
return ChangeLevel.INDEX;
}
// IndexColumn properties
if(!Objects.equal(oldICol.getIndexedLength(), newICol.getIndexedLength()) ||
!Objects.equal(oldICol.isAscending(), newICol.isAscending())) {
return ChangeLevel.INDEX;
}
// Column being indexed
if(compare(oldICol.getColumn(), newICol.getColumn()) == ChangeLevel.TABLE) {
return ChangeLevel.INDEX;
}
}
if(!oldIndex.getIndexName().getName().equals(newIndex.getIndexName().getName())) {
return ChangeLevel.METADATA;
}
return ChangeLevel.NONE;
}
private static boolean sequenceChanged(Sequence oldSeq, Sequence newSeq) {
if(oldSeq == null && newSeq == null) {
return false;
}
if(oldSeq != null && newSeq == null) {
return true;
}
if(oldSeq == null /*&& newSeq != null**/) {
return true;
}
return (oldSeq.getStartsWith() != newSeq.getStartsWith()) ||
(oldSeq.getIncrement() != newSeq.getIncrement()) ||
(oldSeq.getMinValue() != newSeq.getMinValue()) ||
(oldSeq.getMaxValue() != newSeq.getMaxValue()) ||
(oldSeq.isCycle() != newSeq.isCycle());
}
private static ParentChange compareParentJoin(List<TableChange> columnChanges, Join oldJoin, Join newJoin) {
if(oldJoin == null && newJoin == null) {
return ParentChange.NONE;
}
if(oldJoin != null && newJoin == null) {
return ParentChange.DROP;
}
if(oldJoin == null /*&& newJoin != null*/) {
return ParentChange.ADD;
}
Table oldParent = oldJoin.getParent();
Table newParent = newJoin.getParent();
if(!oldParent.getName().equals(newParent.getName()) ||
(oldJoin.getJoinColumns().size() != newJoin.getJoinColumns().size())) {
return ParentChange.ADD;
}
boolean sawRename = false;
Iterator<JoinColumn> oldIt = oldJoin.getJoinColumns().iterator();
Iterator<JoinColumn> newIt = newJoin.getJoinColumns().iterator();
while(oldIt.hasNext()) {
Column oldCol = oldIt.next().getChild();
String newName = findNewName(columnChanges, newIt.next().getChild().getName());
if(newName == null) {
return ParentChange.DROP;
} else {
Column newCol = newJoin.getChild().getColumn(newName);
if(compare(oldCol, newCol) == ChangeLevel.TABLE) {
return ParentChange.DROP;
} else if(!oldCol.getName().equals(newName)) {
sawRename = true;
}
}
}
return sawRename ? ParentChange.META : ParentChange.NONE;
}
private void addNotPresent(boolean isIndex, TableChange change) {
String detail = change.toString();
throw isIndex ? new AddIndexNotPresentException(detail) : new AddColumnNotPresentException(detail);
}
private void dropNotPresent(boolean isIndex, TableChange change) {
String detail = change.toString();
throw isIndex ? new DropIndexNotPresentException(detail) : new DropColumnNotPresentException(detail);
}
private static RuntimeException modifyNotChanged(boolean isIndex, TableChange change) {
String detail = change.toString();
return isIndex ? new ModifyIndexNotChangedException(detail) : new ModifyColumnNotChangedException(detail);
}
private void modifyNotPresent(boolean isIndex, TableChange change) {
String detail = change.toString();
throw isIndex ? new ModifyIndexNotPresentException(detail) : new ModifyColumnNotPresentException(detail);
}
private void unchangedNotPresent(boolean isIndex, String detail) {
assert !isIndex;
throw new UnchangedColumnNotPresentException(detail);
}
private void undeclaredChange(boolean isIndex, String detail) {
assert !isIndex;
throw new UndeclaredColumnChangeException(detail);
}
private void checkFinalChangeLevel() {
if(finalChangeLevel == null) {
return;
}
// Internal consistency checks
switch(finalChangeLevel) {
case NONE:
if(!state.affectedGI.isEmpty()) {
throw new IllegalStateException("NONE but had affected GI: " + state.affectedGI);
}
break;
case METADATA:
case METADATA_CONSTRAINT:
if(!state.droppedGI.isEmpty()) {
throw new IllegalStateException("META but had dropped GI: " + state.droppedGI);
}
if(!state.dataAffectedGI.isEmpty()) {
throw new IllegalStateException("META but had data affected GI: " + state.dataAffectedGI);
}
break;
case INDEX:
case INDEX_CONSTRAINT:
if(!state.dataAffectedGI.isEmpty()) {
throw new IllegalStateException("INDEX but had data affected GI: " + state.dataAffectedGI);
}
break;
case TABLE:
case GROUP:
break;
default:
throw new IllegalStateException(finalChangeLevel.toString());
}
}
}
|
package kcsaba.image.viewer;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class ImageSequenceViewer extends JPanel {
private final ImageViewer imageViewer;
private int number, position;
private JButton forwardButton, backwardButton;
private JLabel locationLabel;
public ImageSequenceViewer(int number) {
this(number, 0);
}
public ImageSequenceViewer(int number, int startPos) {
super(new BorderLayout());
if (number <= 0 || startPos < 0 || startPos >= number)
throw new IllegalArgumentException();
imageViewer = new ImageViewer();
this.number = number;
this.position = startPos;
add(imageViewer.getComponent(), BorderLayout.CENTER);
forwardButton = new JButton(">");
backwardButton = new JButton("<");
JPanel locationPanel = new JPanel(new FlowLayout());
locationPanel.add(backwardButton);
locationPanel.add(createLocationDefinition());
locationPanel.add(forwardButton);
forwardButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setPosition(position + 1);
}
});
backwardButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
setPosition(position - 1);
}
});
add(locationPanel, BorderLayout.NORTH);
setPosition(position);
}
/**
* Overridden to call {@link #positionChanged()}.
*/
@Override
public void addNotify() {
super.addNotify();
positionChanged();
}
/**
* Called when the current position of the viewer has changed. The default implementation does nothing.
* Subclasses should override this method to update the image.
* <p>
* This method is not called from the constructor, but it is called before the viewer is made visible,
* so subclasses can safely use this method to set the initial image.
*/
protected void positionChanged() {
}
public ImageViewer getImageViewer() {
return imageViewer;
}
public void setPosition(int pos) {
if (pos < 0 || pos >= number)
throw new IllegalArgumentException("Position " + pos + " out of range");
position = pos;
updateLocationDefinition(position);
forwardButton.setEnabled(position < number - 1);
backwardButton.setEnabled(position > 0);
if (getParent()!=null) positionChanged();
}
/**
* Returns the current position of this image sequence shower.
* @param pos the current position, at least zero, less than the number of images
*/
public int getPosition() {
return position;
}
/**
* Creates and returns the component that displays the current position to the user. The default implementation
* creates a <code>JLabel</code>.
* @return the location component
*/
protected JComponent createLocationDefinition() {
locationLabel = new JLabel();
return locationLabel;
}
/**
* Called when the current position changes to update the location component.
* @param pos the current position
*/
protected void updateLocationDefinition(int pos) {
locationLabel.setText(String.format("%d/%d", pos + 1, number));
}
}
|
package com.frameworkium.core.ui.driver;
import com.frameworkium.core.common.properties.Property;
import com.frameworkium.core.ui.capture.ScreenshotCapture;
import com.frameworkium.core.ui.driver.remotes.BrowserStack;
import com.frameworkium.core.ui.driver.remotes.Sauce;
import com.frameworkium.core.ui.listeners.CaptureListener;
import com.frameworkium.core.ui.listeners.LoggingListener;
import com.frameworkium.core.ui.proxy.SeleniumProxyFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.ImmutableCapabilities;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.support.events.EventFiringWebDriver;
import static java.util.concurrent.TimeUnit.SECONDS;
public abstract class AbstractDriver implements Driver {
protected static final Logger logger = LogManager.getLogger();
private EventFiringWebDriver webDriverWrapper;
@Override
public EventFiringWebDriver getWebDriver() {
return this.webDriverWrapper;
}
/**
* Creates the Wrapped Driver object and maximises if required.
*/
public void initialise() {
this.webDriverWrapper = setupEventFiringWebDriver(getCapabilities());
maximiseBrowserIfRequired();
}
private EventFiringWebDriver setupEventFiringWebDriver(Capabilities capabilities) {
Capabilities caps = addProxyIfRequired(capabilities);
logger.debug("Browser Capabilities: " + caps);
EventFiringWebDriver eventFiringWD = new EventFiringWebDriver(getWebDriver(caps));
eventFiringWD.register(new LoggingListener());
if (ScreenshotCapture.isRequired()) {
eventFiringWD.register(new CaptureListener());
}
if (!Driver.isNative()) {
eventFiringWD.manage().timeouts().setScriptTimeout(10, SECONDS);
}
return eventFiringWD;
}
private static Capabilities addProxyIfRequired(Capabilities caps) {
if (Property.PROXY.isSpecified()) {
return caps.merge(createProxyCapabilities(Property.PROXY.getValue()));
} else {
return caps;
}
}
private static Capabilities createProxyCapabilities(String proxyProperty) {
return new ImmutableCapabilities(
CapabilityType.PROXY,
SeleniumProxyFactory.createProxy(proxyProperty));
}
private void maximiseBrowserIfRequired() {
if (isMaximiseRequired()) {
this.webDriverWrapper.manage().window().maximize();
}
}
private static boolean isMaximiseRequired() {
boolean ableToMaximise = !Sauce.isDesired()
&& !BrowserStack.isDesired()
&& !Driver.isNative();
return ableToMaximise && Property.MAXIMISE.getBoolean();
}
}
|
package com.github.blindpirate.gogradle.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
/**
* Utils for http access.
* To support mocking, it does not use public static method intentionally.
*/
public class HttpUtils {
private static final int TEN_SECONDS = 10000;
private static final int FOUR_KB = 4096;
/**
* Send a get request
*
* @param url
* @return response
* @throws IOException
*/
public String get(String url) throws IOException {
return get(url, null);
}
/**
* Send a get request
*
* @param url Url as string
* @param headers Optional map with headers
* @return response Response as string
* @throws IOException
*/
public String get(String url,
Map<String, String> headers) throws IOException {
return fetch("GET", url, null, headers);
}
/**
* Send a post request
*
* @param url Url as string
* @param body Request body as string
* @param headers Optional map with headers
* @return response Response as string
* @throws IOException
*/
public String post(String url, String body,
Map<String, String> headers) throws IOException {
return fetch("POST", url, body, headers);
}
/**
* Send a post request
*
* @param url Url as string
* @param body Request body as string
* @return response Response as string
* @throws IOException
*/
public String post(String url, String body) throws IOException {
return post(url, body, null);
}
/**
* Post a form with parameters
*
* @param url Url as string
* @param params map with parameters/values
* @return response Response as string
* @throws IOException
*/
public String postForm(String url, Map<String, String> params)
throws IOException {
return postForm(url, params, null);
}
/**
* Post a form with parameters
*
* @param url Url as string
* @param params Map with parameters/values
* @param headers Optional map with headers
* @return response Response as string
* @throws IOException
*/
public String postForm(String url, Map<String, String> params,
Map<String, String> headers) throws IOException {
// set content type
if (headers == null) {
headers = new HashMap<String, String>();
}
headers.put("Content-Type", "application/x-www-form-urlencoded");
// parse parameters
StringBuilder body = new StringBuilder();
if (params != null) {
boolean first = true;
for (Map.Entry<String, String> param : params.entrySet()) {
if (first) {
first = false;
} else {
body.append("&");
}
String value = param.getValue();
body.append(URLEncoder.encode(param.getKey(), "UTF-8") + "=");
body.append(URLEncoder.encode(value, "UTF-8"));
}
}
return post(url, body.toString(), headers);
}
/**
* Send a put request
*
* @param url Url as string
* @param body Request body as string
* @param headers Optional map with headers
* @return response Response as string
* @throws IOException
*/
public String put(String url, String body,
Map<String, String> headers) throws IOException {
return fetch("PUT", url, body, headers);
}
/**
* Send a put request
*
* @param url Url as string
* @return response Response as string
* @throws IOException
*/
public String put(String url, String body) throws IOException {
return put(url, body, null);
}
/**
* Send a delete request
*
* @param url Url as string
* @param headers Optional map with headers
* @return response Response as string
* @throws IOException
*/
public String delete(String url,
Map<String, String> headers) throws IOException {
return fetch("DELETE", url, null, headers);
}
/**
* Send a delete request
*
* @param url Url as string
* @return response Response as string
* @throws IOException
*/
public String delete(String url) throws IOException {
return delete(url, null);
}
/**
* Append query parameters to given url
*
* @param url Url as string
* @param params Map with query parameters
* @return url Url with query parameters appended
* @throws IOException
*/
public String appendQueryParams(String url,
Map<String, String> params) {
StringBuilder fullUrl = new StringBuilder(url);
if (params != null) {
boolean first = (url.indexOf('?') == -1);
for (Map.Entry<String, String> param : params.entrySet()) {
if (first) {
fullUrl.append('?');
first = false;
} else {
fullUrl.append('&');
}
try {
fullUrl.append(URLEncoder.encode(param.getKey(), "UTF-8")).append('=');
fullUrl.append(URLEncoder.encode(param.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
// ok to ignore
}
}
}
return fullUrl.toString();
}
/**
* Retrieve the query parameters from given url
*
* @param url Url containing query parameters
* @return params Map with query parameters
* @throws IOException
*/
public Map<String, String> getQueryParams(String url)
throws IOException {
Map<String, String> params = new HashMap<String, String>();
int start = url.indexOf('?');
while (start != -1) {
// read parameter name
int equals = url.indexOf('=', start);
String param = "";
if (equals != -1) {
param = url.substring(start + 1, equals);
} else {
param = url.substring(start + 1);
}
// read parameter value
String value = "";
if (equals != -1) {
start = url.indexOf('&', equals);
if (start != -1) {
value = url.substring(equals + 1, start);
} else {
value = url.substring(equals + 1);
}
}
params.put(URLDecoder.decode(param, "UTF-8"),
URLDecoder.decode(value, "UTF-8"));
}
return params;
}
/**
* Returns the url without query parameters
*
* @param url Url containing query parameters
* @return url Url without query parameters
* @throws IOException
*/
public String removeQueryParams(String url)
throws IOException {
int q = url.indexOf('?');
if (q != -1) {
return url.substring(0, q);
} else {
return url;
}
}
/**
* Send a request
*
* @param method HTTP method, for example "GET" or "POST"
* @param url Url as string
* @param body Request body as string
* @param headers Optional map with headers
* @return response Response as string
* @throws IOException
*/
public String fetch(String method, String url, String body,
Map<String, String> headers) throws IOException {
// connection
URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
conn.setConnectTimeout(TEN_SECONDS);
conn.setReadTimeout(TEN_SECONDS);
// method
if (method != null) {
conn.setRequestMethod(method);
}
// headers
if (headers != null) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
conn.addRequestProperty(entry.getKey(), entry.getValue());
}
}
// body
if (body != null) {
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
os.write(body.getBytes("UTF-8"));
os.flush();
os.close();
}
// response
InputStream is = conn.getInputStream();
String response = streamToString(is);
is.close();
// handle redirects
if (conn.getResponseCode() == HttpURLConnection.HTTP_MOVED_PERM) {
String location = conn.getHeaderField("Location");
return fetch(method, location, body, headers);
}
return response;
}
/**
* Read an input stream into a string
*
* @param in
* @return
* @throws IOException
*/
public String streamToString(InputStream in) throws IOException {
StringBuilder out = new StringBuilder();
byte[] b = new byte[FOUR_KB];
int n;
while (true) {
n = in.read(b);
if (n == -1) {
break;
}
out.append(new String(b, 0, n, Charset.forName("UTF-8")));
}
return out.toString();
}
}
|
package mcjty.rftools.blocks.crafter;
import mcjty.lib.base.StyleConfig;
import mcjty.lib.container.GenericGuiContainer;
import mcjty.lib.entity.GenericEnergyStorageTileEntity;
import mcjty.lib.gui.RenderHelper;
import mcjty.lib.gui.Window;
import mcjty.lib.gui.events.DefaultSelectionEvent;
import mcjty.lib.gui.layout.HorizontalAlignment;
import mcjty.lib.gui.layout.HorizontalLayout;
import mcjty.lib.gui.layout.PositionalLayout;
import mcjty.lib.gui.widgets.*;
import mcjty.lib.gui.widgets.Button;
import mcjty.lib.gui.widgets.Label;
import mcjty.lib.gui.widgets.Panel;
import mcjty.lib.network.Argument;
import mcjty.lib.varia.RedstoneMode;
import mcjty.rftools.BlockInfo;
import mcjty.rftools.RFTools;
import mcjty.rftools.network.RFToolsMessages;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.ResourceLocation;
import java.awt.*;
public class GuiCrafter extends GenericGuiContainer<CrafterBaseTE> {
public static final int CRAFTER_WIDTH = 256;
public static final int CRAFTER_HEIGHT = 238;
private EnergyBar energyBar;
private WidgetList recipeList;
private ChoiceLabel keepItem;
private ChoiceLabel internalRecipe;
private Button applyButton;
private ImageChoiceLabel redstoneMode;
private ImageChoiceLabel speedMode;
private Button rememberButton;
private Button forgetButton;
private static final ResourceLocation iconLocation = new ResourceLocation(RFTools.MODID, "textures/gui/crafter.png");
private static final ResourceLocation iconGuiElements = new ResourceLocation(RFTools.MODID, "textures/gui/guielements.png");
private static int lastSelected = -1;
public GuiCrafter(CrafterBlockTileEntity1 te, CrafterContainer container) {
super(RFTools.instance, RFToolsMessages.INSTANCE, te, container, RFTools.GUI_MANUAL_MAIN, "crafter");
GenericEnergyStorageTileEntity.setCurrentRF(te.getEnergyStored(EnumFacing.DOWN));
xSize = CRAFTER_WIDTH;
ySize = CRAFTER_HEIGHT;
}
public GuiCrafter(CrafterBlockTileEntity2 te, CrafterContainer container) {
super(RFTools.instance, RFToolsMessages.INSTANCE, te, container, RFTools.GUI_MANUAL_MAIN, "crafter");
GenericEnergyStorageTileEntity.setCurrentRF(te.getEnergyStored(EnumFacing.DOWN));
xSize = CRAFTER_WIDTH;
ySize = CRAFTER_HEIGHT;
}
public GuiCrafter(CrafterBlockTileEntity3 te, CrafterContainer container) {
super(RFTools.instance, RFToolsMessages.INSTANCE, te, container, RFTools.GUI_MANUAL_MAIN, "crafter");
GenericEnergyStorageTileEntity.setCurrentRF(te.getEnergyStored(EnumFacing.DOWN));
xSize = CRAFTER_WIDTH;
ySize = CRAFTER_HEIGHT;
}
@Override
public void initGui() {
super.initGui();
int maxEnergyStored = tileEntity.getMaxEnergyStored(EnumFacing.DOWN);
energyBar = new EnergyBar(mc, this).setVertical().setMaxValue(maxEnergyStored).setLayoutHint(new PositionalLayout.PositionalHint(12, 141, 10, 76)).setShowText(false);
energyBar.setValue(GenericEnergyStorageTileEntity.getCurrentRF());
initKeepMode();
initInternalRecipe();
Slider listSlider = initRecipeList();
applyButton = new Button(mc, this).
setText("Apply").
setTooltips("Press to apply the", "recipe to the crafter").
addButtonEvent(parent -> applyRecipe()).
setEnabled(false).
setLayoutHint(new PositionalLayout.PositionalHint(212, 65, 34, 16));
rememberButton = new Button(mc, this)
.setText("R")
.setTooltips("Remember the current items", "in the internal and", "external buffers")
.addButtonEvent(widget -> rememberItems())
.setLayoutHint(new PositionalLayout.PositionalHint(148, 74, 18, 16));
forgetButton = new Button(mc, this)
.setText("F")
.setTooltips("Forget the remembered layout")
.addButtonEvent(widget -> forgetItems())
.setLayoutHint(new PositionalLayout.PositionalHint(168, 74, 18, 16));
initRedstoneMode();
initSpeedMode();
Widget toplevel = new Panel(mc, this).setBackground(iconLocation).setLayout(new PositionalLayout()).addChild(energyBar).addChild(keepItem).addChild(internalRecipe).
addChild(recipeList).addChild(listSlider).addChild(applyButton).addChild(redstoneMode).addChild(speedMode).addChild(rememberButton).addChild(forgetButton);
toplevel.setBounds(new Rectangle(guiLeft, guiTop, xSize, ySize));
if (lastSelected != -1 && lastSelected < tileEntity.getSizeInventory()) {
recipeList.setSelected(lastSelected);
}
selectRecipe();
sendChangeToServer(-1, null, null, false, CraftingRecipe.CraftMode.EXT);
window = new Window(this, toplevel);
tileEntity.requestRfFromServer(RFTools.MODID);
}
private Slider initRecipeList() {
recipeList = new WidgetList(mc, this)
.addSelectionEvent(new DefaultSelectionEvent() {
@Override
public void select(Widget parent, int index) {
selectRecipe();
}
})
.setLayoutHint(new PositionalLayout.PositionalHint(10, 7, 126, 84));
populateList();
return new Slider(mc, this).setVertical().setScrollable(recipeList).setLayoutHint(new PositionalLayout.PositionalHint(137, 7, 10, 84));
}
private void initInternalRecipe() {
internalRecipe = new ChoiceLabel(mc, this).
addChoices("Ext", "Int", "ExtC").
setTooltips("'Int' will put result of", "crafting operation in", "inventory instead of", "output buffer").
addChoiceEvent((parent, newChoice) -> updateRecipe()).
setEnabled(false).
setLayoutHint(new PositionalLayout.PositionalHint(148, 24, 41, 14));
internalRecipe.setChoiceTooltip("Ext", "Result of crafting operation", "will go to output buffer");
internalRecipe.setChoiceTooltip("Int", "Result of crafting operation", "will stay in input buffer");
internalRecipe.setChoiceTooltip("ExtC", "Result of crafting operation", "will go to output buffer",
"but remaining items (like", "buckets) will stay in input");
}
private void initKeepMode() {
keepItem = new ChoiceLabel(mc, this).
addChoices("All", "Keep").
setTooltips("'Keep' will keep one", "item in every inventory", "slot").
addChoiceEvent((parent, newChoice) -> updateRecipe()).
setEnabled(false).
setLayoutHint(new PositionalLayout.PositionalHint(148, 7, 41, 14));
}
private void initSpeedMode() {
speedMode = new ImageChoiceLabel(mc, this).
addChoiceEvent((parent, newChoice) -> changeSpeedMode()).
addChoice("Slow", "Speed mode:\nSlow", iconGuiElements, 48, 0).
addChoice("Fast", "Speed mode:\nFast", iconGuiElements, 64, 0);
speedMode.setLayoutHint(new PositionalLayout.PositionalHint(49, 186, 16, 16));
speedMode.setCurrentChoice(tileEntity.getSpeedMode());
}
private void initRedstoneMode() {
redstoneMode = new ImageChoiceLabel(mc, this).
addChoiceEvent((parent, newChoice) -> changeRedstoneMode()).
addChoice(RedstoneMode.REDSTONE_IGNORED.getDescription(), "Redstone mode:\nIgnored", iconGuiElements, 0, 0).
addChoice(RedstoneMode.REDSTONE_OFFREQUIRED.getDescription(), "Redstone mode:\nOff to activate", iconGuiElements, 16, 0).
addChoice(RedstoneMode.REDSTONE_ONREQUIRED.getDescription(), "Redstone mode:\nOn to activate", iconGuiElements, 32, 0);
redstoneMode.setLayoutHint(new PositionalLayout.PositionalHint(31, 186, 16, 16));
redstoneMode.setCurrentChoice(tileEntity.getRSMode().ordinal());
}
private void changeRedstoneMode() {
tileEntity.setRSMode(RedstoneMode.values()[redstoneMode.getCurrentChoiceIndex()]);
sendChangeToServer();
}
private void changeSpeedMode() {
tileEntity.setSpeedMode(speedMode.getCurrentChoiceIndex());
sendChangeToServer();
}
private void rememberItems() {
sendServerCommand(RFToolsMessages.INSTANCE, CrafterBaseTE.CMD_REMEMBER);
}
private void forgetItems() {
sendServerCommand(RFToolsMessages.INSTANCE, CrafterBaseTE.CMD_FORGET);
}
private void sendChangeToServer() {
sendServerCommand(RFToolsMessages.INSTANCE, CrafterBaseTE.CMD_MODE,
new Argument("rs", RedstoneMode.values()[redstoneMode.getCurrentChoiceIndex()].getDescription()),
new Argument("speed", speedMode.getCurrentChoiceIndex()));
}
private void populateList() {
recipeList.removeChildren();
for (int i = 0 ; i < tileEntity.getSupportedRecipes() ; i++) {
CraftingRecipe recipe = tileEntity.getRecipe(i);
ItemStack stack = recipe.getResult();
addRecipeLine(stack);
}
}
private void addRecipeLine(Object craftingResult) {
String readableName = BlockInfo.getReadableName(craftingResult, 0);
int color = StyleConfig.colorTextInListNormal;
if (craftingResult == null) {
readableName = "<no recipe>";
color = 0xFF505050;
}
Panel panel = new Panel(mc, this).setLayout(new HorizontalLayout()).
addChild(new BlockRender(mc, this).setRenderItem(craftingResult)).
addChild(new Label(mc, this).setColor(color).setHorizontalAlignment(HorizontalAlignment.ALIGH_LEFT).setDynamic(true).setText(readableName));
recipeList.addChild(panel);
}
private void selectRecipe() {
int selected = recipeList.getSelected();
lastSelected = selected;
if (selected == -1) {
for (int i = 0 ; i < 10 ; i++) {
inventorySlots.getSlot(i).putStack(null);
}
keepItem.setChoice("All");
internalRecipe.setChoice("Ext");
keepItem.setEnabled(false);
internalRecipe.setEnabled(false);
applyButton.setEnabled(false);
return;
}
CraftingRecipe craftingRecipe = tileEntity.getRecipe(selected);
InventoryCrafting inv = craftingRecipe.getInventory();
for (int i = 0 ; i < 9 ; i++) {
inventorySlots.getSlot(i).putStack(inv.getStackInSlot(i));
}
inventorySlots.getSlot(9).putStack(craftingRecipe.getResult());
keepItem.setChoice(craftingRecipe.isKeepOne() ? "Keep" : "All");
internalRecipe.setChoice(craftingRecipe.getCraftMode().getDescription());
keepItem.setEnabled(true);
internalRecipe.setEnabled(true);
applyButton.setEnabled(true);
}
private void testRecipe() {
int selected = recipeList.getSelected();
if (selected == -1) {
return;
}
InventoryCrafting inv = new InventoryCrafting(new Container() {
@Override
public boolean canInteractWith(EntityPlayer var1) {
return false;
}
}, 3, 3);
for (int i = 0 ; i < 9 ; i++) {
inv.setInventorySlotContents(i, inventorySlots.getSlot(i).getStack());
}
// Compare current contents to avoid unneeded slot update.
IRecipe recipe = CraftingRecipe.findRecipe(mc.theWorld, inv);
ItemStack newResult;
if (recipe == null) {
newResult = null;
} else {
newResult = recipe.getCraftingResult(inv);
}
inventorySlots.getSlot(9).putStack(newResult);
}
private void applyRecipe() {
int selected = recipeList.getSelected();
if (selected == -1) {
return;
}
CraftingRecipe craftingRecipe = tileEntity.getRecipe(selected);
InventoryCrafting inv = craftingRecipe.getInventory();
for (int i = 0 ; i < 9 ; i++) {
ItemStack oldStack = inv.getStackInSlot(i);
ItemStack newStack = inventorySlots.getSlot(i).getStack();
if (!itemStacksEqual(oldStack, newStack)) {
inv.setInventorySlotContents(i, newStack);
}
}
// Compare current contents to avoid unneeded slot update.
IRecipe recipe = CraftingRecipe.findRecipe(mc.theWorld, inv);
ItemStack newResult;
if (recipe == null) {
newResult = null;
} else {
newResult = recipe.getCraftingResult(inv);
}
ItemStack oldResult = inventorySlots.getSlot(9).getStack();
if (!itemStacksEqual(oldResult, newResult)) {
inventorySlots.getSlot(9).putStack(newResult);
}
craftingRecipe.setResult(newResult);
updateRecipe();
populateList();
}
private void updateRecipe() {
int selected = recipeList.getSelected();
if (selected == -1) {
return;
}
CraftingRecipe craftingRecipe = tileEntity.getRecipe(selected);
boolean keepOne = "Keep".equals(keepItem.getCurrentChoice());
CraftingRecipe.CraftMode mode;
if ("Int".equals(internalRecipe.getCurrentChoice())) {
mode = CraftingRecipe.CraftMode.INT;
} else if ("Ext".equals(internalRecipe.getCurrentChoice())) {
mode = CraftingRecipe.CraftMode.EXT;
} else {
mode = CraftingRecipe.CraftMode.EXTC;
}
craftingRecipe.setKeepOne(keepOne);
craftingRecipe.setCraftMode(mode);
sendChangeToServer(selected, craftingRecipe.getInventory(), craftingRecipe.getResult(), keepOne, mode);
}
private boolean itemStacksEqual(ItemStack matches, ItemStack oldStack) {
if (matches == null) {
return oldStack == null;
} else {
return oldStack != null && matches.isItemEqual(oldStack);
}
}
private void sendChangeToServer(int index, InventoryCrafting inv, ItemStack result, boolean keepOne,
CraftingRecipe.CraftMode mode) {
RFToolsMessages.INSTANCE.sendToServer(new PacketCrafter(tileEntity.getPos(), index, inv,
result, keepOne, mode));
}
/**
* Draws the screen and all the components in it.
*/
@Override
public void drawScreen(int par1, int par2, float par3) {
super.drawScreen(par1, par2, par3);
testRecipe();
}
@Override
protected void drawGuiContainerBackgroundLayer(float v, int x, int y) {
drawWindow();
int currentRF = GenericEnergyStorageTileEntity.getCurrentRF();
energyBar.setValue(currentRF);
tileEntity.requestRfFromServer(RFTools.MODID);
// Draw the ghost slots here
drawGhostSlots();
}
private void drawGhostSlots() {
net.minecraft.client.renderer.RenderHelper.enableGUIStandardItemLighting();
GlStateManager.pushMatrix();
GlStateManager.translate((float) guiLeft, (float) guiTop, 0.0F);
GlStateManager.color(1.0F, 0.0F, 0.0F, 1.0F);
GlStateManager.enableRescaleNormal();
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float) (short) 240 / 1.0F, (float) (short) 240 / 1.0F);
ItemStack[] ghostSlots = tileEntity.getGhostSlots();
zLevel = 100.0F;
itemRender.zLevel = 100.0F;
GlStateManager.enableDepth();
GlStateManager.disableBlend();
GlStateManager.enableLighting();
for (int i = 0 ; i < ghostSlots.length ; i++) {
ItemStack stack = ghostSlots[i];
if (stack != null) {
int slotIdx;
if (i < CrafterContainer.BUFFER_SIZE) {
slotIdx = i + CrafterContainer.SLOT_BUFFER;
} else {
slotIdx = i + CrafterContainer.SLOT_BUFFEROUT - CrafterContainer.BUFFER_SIZE;
}
Slot slot = inventorySlots.getSlot(slotIdx);
if (!slot.getHasStack()) {
itemRender.renderItemAndEffectIntoGUI(stack, slot.xDisplayPosition, slot.yDisplayPosition);
GlStateManager.disableLighting();
GlStateManager.enableBlend();
GlStateManager.disableDepth();
this.mc.getTextureManager().bindTexture(iconGuiElements);
RenderHelper.drawTexturedModalRect(slot.xDisplayPosition, slot.yDisplayPosition, 14 * 16, 3 * 16, 16, 16);
GlStateManager.enableDepth();
GlStateManager.disableBlend();
GlStateManager.enableLighting();
}
}
}
itemRender.zLevel = 0.0F;
zLevel = 0.0F;
GlStateManager.popMatrix();
net.minecraft.client.renderer.RenderHelper.disableStandardItemLighting();
}
}
|
package me.coley.recaf.bytecode.analysis;
import javafx.scene.image.Image;
import jregex.Matcher;
import jregex.Pattern;
import me.coley.recaf.Input;
import me.coley.recaf.Logging;
import me.coley.recaf.ui.FxCode;
import me.coley.recaf.util.Icons;
import me.coley.recaf.util.Lang;
import org.objectweb.asm.tree.*;
import org.objectweb.asm.tree.analysis.*;
import org.objectweb.asm.util.CheckClassAdapter;
import org.objectweb.asm.util.TraceClassVisitor;
import java.io.PrintWriter;
import java.io.StringWriter;
public class Verify {
//@formatter:off
private static final String[] KEYWORDS = new String[] { "R", "I", "J", "F", "D"};
private static final String[] OPCODES = new String[] { "AALOAD", "AASTORE", "ACONST_NULL", "ARETURN", "ARRAYLENGTH", "ATHROW",
"BALOAD", "BASTORE", "CALOAD", "CASTORE", "D2F", "D2I", "D2L", "DADD", "DALOAD", "DASTORE", "DCMPG", "DCMPL",
"DCONST_0", "DCONST_1", "DDIV", "DMUL", "DNEG", "DREM", "DRETURN", "DSUB", "DUP", "DUP2", "DUP2_X1", "DUP2_X2",
"DUP_X1", "DUP_X2", "F2D", "F2I", "F2L", "FADD", "FALOAD", "FASTORE", "FCMPG", "FCMPL", "FCONST_0", "FCONST_1",
"FCONST_2", "FDIV", "FMUL", "FNEG", "FREM", "FRETURN", "FSUB", "I2B", "I2C", "I2D", "I2F", "I2L", "I2S", "IADD",
"IALOAD", "IAND", "IASTORE", "ICONST_0", "ICONST_1", "ICONST_2", "ICONST_3", "ICONST_4", "ICONST_5", "ICONST_M1",
"IDIV", "IMUL", "INEG", "IOR", "IREM", "IRETURN", "ISHL", "ISHR", "ISUB", "IUSHR", "IXOR", "L2D", "L2F", "L2I",
"LADD", "LALOAD", "LAND", "LASTORE", "LCMP", "LCONST_0", "LCONST_1", "LDIV", "LMUL", "LNEG", "LOR", "LREM", "LRETURN",
"LSHL", "LSHR", "LSUB", "LUSHR", "LXOR", "MONITORENTER", "MONITOREXIT", "NOP", "POP", "POP2", "RETURN", "SALOAD",
"SASTORE", "SWAP", "BIPUSH", "SIPUSH", "NEWARRAY", "ALOAD", "ASTORE", "DLOAD", "DSTORE", "FLOAD", "FSTORE", "ILOAD",
"ISTORE", "LLOAD", "LSTORE", "RET", "ANEWARRAY", "CHECKCAST", "INSTANCEOF", "NEW", "GETSTATIC", "PUTSTATIC",
"GETFIELD", "PUTFIELD", "INVOKEVIRTUAL", "INVOKESPECIAL", "INVOKESTATIC", "INVOKEINTERFACE", "INVOKEDYNAMIC" ,
"GOTO", "IF_ACMPEQ", "IF_ACMPNE", "IF_ICMPEQ", "IF_ICMPGE", "IF_ICMPGT", "IF_ICMPLE", "IF_ICMPLT", "IF_ICMPNE",
"IFEQ", "IFGE", "IFGT", "IFLE", "IFLT", "IFNE", "IFNONNULL", "IFNULL", "JSR", "LDC", "IINC", "TABLESWITCH",
"LOOKUPSWITCH", "F_NEW", "F_FULL", "F_APPEND", "F_CHOP", "F_SAME", "F_APPEND", "F_SAME1", "LINENUMBER" };
//@formatter:on
private static final String KEYWORD_PATTERN = "\\b(" + String.join("|", KEYWORDS) + ")\\b";
private static final String OPCODE_PATTERN = "\\b(" + String.join("|", OPCODES) + ")\\b";
private static final String LINE_PREFIX_GOOD_PATTERN = "([0-9]{5})(?= \\w)";
private static final String LINE_PREFIX_ERRR_PATTERN = "([0-9]{5})(?= \\?)";
private static final String CONST_VAL_PATTERN = "(\\b([\\d._]*[\\d])\\b)";
private static final String LINENUM_PATTERN = "L[0-9]+";
//@formatter:off
private static final Pattern PATTERN = new Pattern(
"({OPCODE}" + OPCODE_PATTERN + ")" +
"|({KEYWORD}" + KEYWORD_PATTERN + ")" +
"|({GOODPREFIX}" + LINE_PREFIX_GOOD_PATTERN + ")" +
"|({ERRRPREFIX}" + LINE_PREFIX_ERRR_PATTERN + ")" +
"|({LINENUM}" + LINENUM_PATTERN + ")" +
"|({CONST}" + CONST_VAL_PATTERN + ")");
//@formatter:on
/**
* Verify correctness of a MethodNode.
*
* @param method
* The MethodNode to check.
* @return Check if this method has passed verification.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static VerifyResults checkValid(String owner, MethodNode method) {
Exception ex = null;
try {
new Analyzer(new BasicVerifier()).analyze(owner, method);
} catch(AnalyzerException e) {
// Thrown on failure.
ex = e;
} catch(IndexOutOfBoundsException e) {
// Thrown when local variables are messed up.
ex = e;
} catch(Exception e) {
// Unknown origin
Logging.error(e);
}
return new VerifyResults(ex);
}
/**
* Verify correctness of a ClassNode. Since this is expected to be used in a
* wide-scope, this does not gather extra information about errors that
* {@link #checkValid(String,MethodNode)} would.
*
* @param clazz
* The ClassNode to check.
* @return Check if this class has passed verification.
*/
public static VerifyResults checkValid(ClassNode clazz) {
StringWriter sw = new StringWriter();
Exception ex = null;
try {
PrintWriter printer = new PrintWriter(sw);
TraceClassVisitor trace = new TraceClassVisitor(printer);
CheckClassAdapter check = new CheckClassAdapter(trace);
clazz.accept(check);
} catch (IllegalArgumentException e) {
// Thrown by CheckClassAdapter
ex = e;
} catch (Exception e) {
// Unknown origin
Logging.error(e);
}
return new VerifyResults(ex, sw.toString());
}
/**
* @return Check if the current Input instance is valid.
*/
public static boolean isValid() {
try {
Input in = Input.get();
for (String name : in.getModifiedClasses()) {
VerifyResults res = checkValid(in.getClass(name));
if (!res.valid()) {
res.showWindow();
return false;
}
}
} catch (Exception e) {
return false;
}
return true;
}
public static class VerifyResults {
/**
* Exception thrown by verifier. {@code null} if verification was a
* success <i>(see {@link #valid()})</i>.
*/
public final Exception ex;
private final String content;
public VerifyResults(Exception ex, String content) {
this.ex = ex;
this.content = content;
}
public VerifyResults(Exception ex) {
this(ex, ex == null ? "" : ex.toString());
}
public void showWindow() {
new FxVerify(ex.getMessage()).show();
}
/**
* @return Cause of verification failure.
*/
public AbstractInsnNode getCause() {
if (ex instanceof AnalyzerException) {
return ((AnalyzerException) ex).node;
}
return null;
}
/**
* @return {@code true} if no exception was raised by
*/
public boolean valid() {
return ex == null;
}
@Override
public String toString() {
return content;
}
}
public static class FxVerify extends FxCode {
protected FxVerify(String initialText) {
super();
setInitialText(initialText);
}
@Override
protected String createTitle() {
return Lang.get("ui.verify");
}
@Override
protected Image createIcon() {
return Icons.L_ERROR;
}
@Override
protected Pattern createPattern() {
return PATTERN;
}
@Override
protected String getStyleClass(Matcher matcher) {
//@formatter:off
return matcher.group("OPCODE") != null ? "ver-op"
: matcher.group("KEYWORD") != null ? "ver-key"
: matcher.group("GOODPREFIX") != null ? "ver-pre-good"
: matcher.group("ERRRPREFIX") != null ? "ver-pre-err"
: matcher.group("LINENUM") != null ? "ver-line"
: matcher.group("CONST") != null ? "ver-const" : null;
//@formatter:on
}
@Override
protected void onCodeChange(String code) {}
}
}
|
package com.github.jomnipod.logrecord;
public interface LogRecordVisitor {
default public void visit(ActivateLogRecordDetails details) {
};
default public void visit(EndMarkerLogRecordDetails details) {
};
default public void visit(DeactivateLogRecordDetails details) {
};
default public void visit(TimeChangeLogRecordDetails details) {
};
default public void visit(BolusLogRecordDetails details) {
};
default public void visit(BasalLogRecordDetails details) {
};
default public void visit(SuspendLogRecordDetails details) {
};
default public void visit(DateChangeLogRecordDetails details) {
};
default public void visit(SuggestedCalcLogRecordDetails details) {
};
default public void visit(RemoteHazardAlarmLogRecordDetails details) {
};
default public void visit(AlarmLogRecordDetails details) {
};
default public void visit(BloodGlucoseLogRecordDetails details) {
};
default public void visit(CarbLogRecordDetails details) {
};
default public void visit(TerminateBolusLogRecordDetails details) {
};
default public void visit(TerminateBasalLogRecordDetails details) {
};
default public void visit(ResumeLogRecordDetails details) {
};
default public void visit(DownloadLogRecordDetails details) {
};
default public void visit(OcclusionLogRecordDetails details) {
};
default public void visit(UnknownLogRecordDetails details) {
};
default public void visit(PumpAlarmDetails details) {
};
default public void visit(DeletedLogRecordDetails details) {
};
default public void visit(IgnoreLogRecordDetails details) {
};
}
|
package me.nallar.modpatcher;
import me.nallar.javatransformer.api.JavaTransformer;
class ModPatcherLoadHook {
private static final int API_VERSION = 1; //Keep in sync with version in ModPatcher.java
private static final String VERSION = "@MOD_VERSION@";
static void loadHook(ModPatcher.Version requiredVersion, String modPatcherRelease, int apiVersion) {
PatcherLog.info("Loaded ModPatcher. Version: @MOD_VERSION@ API version: " + API_VERSION);
if (API_VERSION != apiVersion) {
PatcherLog.warn("API version mismatch. Expected " + API_VERSION + ", got " + apiVersion);
PatcherLog.warn("API was loaded from: " + JavaTransformer.pathFromClass(ModPatcher.class));
}
ModPatcher.Version current = ModPatcher.Version.of(VERSION);
if (requiredVersion != ModPatcher.Version.LATEST && current.compareTo(requiredVersion) < 0) {
String autoUpdate = "\nWill auto-update on next start.";
if (ModPatcher.neverUpdate())
autoUpdate = "";
else
JavaTransformer.pathFromClass(ModPatcherTransformer.class).toFile().deleteOnExit();
throw new RuntimeException("ModPatcher outdated. Have version: " + VERSION + ", requested version: " + requiredVersion + autoUpdate);
}
}
}
|
package com.github.onsdigital.perkin.json;
import com.google.gson.*;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
@Slf4j
public class SurveyParser {
public Survey parse(String json) throws SurveyParserException {
try {
Survey survey = deserialize(json);
//TODO validation - type, origin, respondent should be 12 chars, 11 digits and a check letter
if (!"0.0.1".equals(survey.getVersion())) {
String message = "Unsupported version (0.0.1 supported), while parsing survey from json: " + json;
log.error("SURVEY|PARSE|" + message);
throw new SurveyParserException(message);
}
if (survey.getCollection() == null) {
String message = "'collection' missing while parsing survey from json: " + json;
log.error("SURVEY|PARSE|" + message);
throw new SurveyParserException(message);
}
if (survey.getMetadata() == null) {
String message = "'metadata' missing while parsing survey from json: " + json;
log.error("SURVEY|PARSE|" + message);
throw new SurveyParserException(message);
}
if (log.isDebugEnabled()) {
log.debug("SURVEY|PARSE|parsed json as {}", survey);
}
return survey;
} catch(JsonParseException e) {
String message = "Problem parsing survey from json " + json;
log.error("SURVEY|PARSE|{}", message, e);
throw new SurveyParserException(message, json, e);
}
}
public String prettyPrint(Survey survey) {
return serialize(survey);
}
private String serialize(Survey survey) {
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(Collection.class, new CollectionSerializer())
.registerTypeAdapter(Date.class, new DateSerializer())
.create();
return gson.toJson(survey);
}
private Survey deserialize(String json) {
Gson gson = new GsonBuilder()
.setPrettyPrinting()
.registerTypeAdapter(Date.class, new DateDeserializer())
.create();
return gson.fromJson(json, Survey.class);
}
private class CollectionSerializer implements JsonSerializer<Collection> {
@Override
public JsonElement serialize(Collection collection, Type type, JsonSerializationContext jsonSerializationContext) {
JsonObject object = new JsonObject();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
object.add("exercise_sid", new JsonPrimitive(collection.getExerciseSid()));
object.add("instrument_id", new JsonPrimitive(collection.getInstrumentId()));
object.add("period", new JsonPrimitive(sdf.format(collection.getPeriod())));
return object;
}
}
public static final String ISO8601 = "yyyy-MM-dd'T'HH:mm:ssX";
private static final String[] DATE_FORMATS = new String[] {
ISO8601,
"yyyy-MM-dd"
};
private class DateSerializer implements JsonSerializer<Date> {
@Override
public JsonElement serialize(Date date, Type type, JsonSerializationContext jsonSerializationContext) {
SimpleDateFormat sdf = new SimpleDateFormat(ISO8601);
return new JsonPrimitive(sdf.format(date));
}
}
private class DateDeserializer implements JsonDeserializer<Date> {
@Override
public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
for (String format : DATE_FORMATS) {
try {
return new SimpleDateFormat(format).parse(jsonElement.getAsString());
} catch (ParseException e) {
//ignore, will be handled below if none of the formats could be parsed
}
}
//TODO: hack
return new Date();
// + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
}
}
}
|
package net.glowstone.block.blocktype;
import net.glowstone.EventFactory;
import net.glowstone.GlowChunk;
import net.glowstone.GlowServer;
import net.glowstone.block.GlowBlock;
import net.glowstone.block.GlowBlockState;
import net.glowstone.block.ItemTable;
import net.glowstone.block.entity.TileEntity;
import net.glowstone.block.itemtype.ItemType;
import net.glowstone.entity.GlowPlayer;
import net.glowstone.util.SoundInfo;
import org.bukkit.*;
import org.bukkit.block.BlockFace;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.block.BlockCanBuildEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.material.MaterialData;
import org.bukkit.util.Vector;
import java.util.*;
/**
* Base class for specific types of blocks.
*/
public class BlockType extends ItemType {
protected static final Random random = new Random();
protected List<ItemStack> drops;
protected SoundInfo placeSound = new SoundInfo(Sound.BLOCK_WOOD_BREAK, 1F, 0.75F);
// Setters for subclass use
/**
* Gets the BlockFace opposite of the direction the location is facing.
* Usually used to set the way container blocks face when being placed.
*
* @param location Location to get opposite of
* @param inverted If up/down should be used
* @return Opposite BlockFace or EAST if yaw is invalid
*/
protected static BlockFace getOppositeBlockFace(Location location, boolean inverted) {
double rot = location.getYaw() % 360;
if (inverted) {
// todo: Check the 67.5 pitch in source. This is based off of WorldEdit's number for this.
double pitch = location.getPitch();
if (pitch < -67.5D) {
return BlockFace.DOWN;
} else if (pitch > 67.5D) {
return BlockFace.UP;
}
}
if (rot < 0) {
rot += 360.0;
}
if (0 <= rot && rot < 45) {
return BlockFace.NORTH;
} else if (45 <= rot && rot < 135) {
return BlockFace.EAST;
} else if (135 <= rot && rot < 225) {
return BlockFace.SOUTH;
} else if (225 <= rot && rot < 315) {
return BlockFace.WEST;
} else if (315 <= rot && rot < 360.0) {
return BlockFace.NORTH;
} else {
return BlockFace.EAST;
}
}
// Public accessors
protected final void setDrops(ItemStack... drops) {
this.drops = Arrays.asList(drops);
}
/**
* Get the items that will be dropped by digging the block.
*
* @param block The block being dug.
* @param tool The tool used or {@code null} if fists or no tool was used.
* @return The drops that should be returned.
*/
public Collection<ItemStack> getDrops(GlowBlock block, ItemStack tool) {
if (drops == null) {
// default calculation
return Arrays.asList(new ItemStack(block.getType(), 1, block.getData()));
} else {
return Collections.unmodifiableList(drops);
}
}
/**
* Gets the sound that will be played when a player places the block.
*
* @return The sound to be played
*/
public SoundInfo getPlaceSound() {
return placeSound;
}
/**
* Sets the sound that will be played when a player places the block.
*
* @param sound The sound.
*/
public void setPlaceSound(Sound sound) {
placeSound = new SoundInfo(sound, 1F, 0.75F);
}
// Actions
/**
* Get the items that will be dropped as if the block would be successfully mined.
* This is used f.e. to calculate TNT drops.
*
* @param block The block.
* @return The drops from that block.
*/
public Collection<ItemStack> getMinedDrops(GlowBlock block) {
return getDrops(block, null);
}
/**
* Create a new tile entity at the given location.
*
* @param chunk The chunk to create the tile entity at.
* @param cx The x coordinate in the chunk.
* @param cy The y coordinate in the chunk.
* @param cz The z coordinate in the chunk.
* @return The new TileEntity, or null if no tile entity is used.
*/
public TileEntity createTileEntity(GlowChunk chunk, int cx, int cy, int cz) {
return null;
}
/**
* Check whether the block can be placed at the given location.
*
* @param block The location the block is being placed at.
* @param against The face the block is being placed against.
* @return Whether the placement is valid.
*/
public boolean canPlaceAt(GlowBlock block, BlockFace against) {
return true;
}
/**
* Called when a block is placed to calculate what the block will become.
*
* @param player the player who placed the block
* @param state the BlockState to edit
* @param holding the ItemStack that was being held
* @param face the face off which the block is being placed
* @param clickedLoc where in the block the click occurred
*/
public void placeBlock(GlowPlayer player, GlowBlockState state, BlockFace face, ItemStack holding, Vector clickedLoc) {
state.setType(holding.getType());
state.setData(holding.getData());
}
/**
* Called after a block has been placed by a player.
*
* @param player the player who placed the block
* @param block the block that was placed
* @param holding the the ItemStack that was being held
* @param oldState The old block state before the block was placed.
*/
public void afterPlace(GlowPlayer player, GlowBlock block, ItemStack holding, GlowBlockState oldState) {
block.applyPhysics(oldState.getType(), block.getTypeId(), oldState.getRawData(), block.getData());
}
/**
* Called when a player attempts to interact with (right-click) a block of
* this type already in the world.
*
* @param player the player interacting
* @param block the block interacted with
* @param face the clicked face
* @param clickedLoc where in the block the click occurred
* @return Whether the interaction occurred.
*/
public boolean blockInteract(GlowPlayer player, GlowBlock block, BlockFace face, Vector clickedLoc) {
return false;
}
/**
* Called when a player attempts to destroy a block.
*
* @param player The player interacting
* @param block The block the player destroyed
* @param face The block face
*/
public void blockDestroy(GlowPlayer player, GlowBlock block, BlockFace face) {
// do nothing
}
/**
* Called after a player successfully destroys a block.
*
* @param player The player interacting
* @param block The block the player destroyed
* @param face The block face
* @param oldState The block state of the block the player destroyed.
*/
public void afterDestroy(GlowPlayer player, GlowBlock block, BlockFace face, GlowBlockState oldState) {
block.applyPhysics(oldState.getType(), block.getTypeId(), oldState.getRawData(), block.getData());
}
/**
* Called when the BlockType gets pulsed as requested.
*
* @param block The block that was pulsed pulsed
*/
public void receivePulse(GlowBlock block) {
block.getWorld().cancelPulse(block);
}
/**
* Called when a player attempts to place a block on an existing block of
* this type. Used to determine if the placement should occur into the air
* adjacent to the block (normal behavior), or absorbed into the block
* clicked on.
*
* @param block The block the player right-clicked
* @param face The face on which the click occurred
* @param holding The ItemStack the player was holding
* @return Whether the place should occur into the block given.
*/
public boolean canAbsorb(GlowBlock block, BlockFace face, ItemStack holding) {
return false;
}
/**
* Called to check if this block can be overridden by a block place
* which would occur inside it.
*
* @param block The block being targeted by the placement
* @param face The face on which the click occurred
* @param holding The ItemStack the player was holding
* @return Whether this block can be overridden.
*/
public boolean canOverride(GlowBlock block, BlockFace face, ItemStack holding) {
return block.isLiquid();
}
/**
* Called when a neighboring block (within a 3x3x3 cube) has changed its
* type or data and physics checks should occur.
*
* @param block The block to perform physics checks for
* @param face The BlockFace to the changed block, or null if unavailable
* @param changedBlock The neighboring block that has changed
* @param oldType The old type of the changed block
* @param oldData The old data of the changed block
* @param newType The new type of the changed block
* @param newData The new data of the changed block
*/
public void onNearBlockChanged(GlowBlock block, BlockFace face, GlowBlock changedBlock, Material oldType, byte oldData, Material newType, byte newData) {
}
/**
* Called when this block has just changed to some other type. This is
* called whenever {@link GlowBlock#setTypeIdAndData}, {@link GlowBlock#setType}
* or {@link GlowBlock#setData} is called with physics enabled, and might
* be called from plugins or other means of changing the block.
*
* @param block The block that was changed
* @param oldType The old Material
* @param oldData The old data
* @param newType The new Material
* @param data The new data
*/
public void onBlockChanged(GlowBlock block, Material oldType, byte oldData, Material newType, byte data) {
// do nothing
}
/**
* Called when the BlockType should calculate the current physics.
*
* @param block The block
*/
public void updatePhysics(GlowBlock block) {
// do nothing
}
@Override
public final void rightClickBlock(GlowPlayer player, GlowBlock against, BlockFace face, ItemStack holding, Vector clickedLoc) {
GlowBlock target = against.getRelative(face);
// prevent building above the height limit
if (target.getLocation().getY() >= target.getWorld().getMaxHeight()) {
player.sendMessage(ChatColor.RED + "The height limit for this world is " + target.getWorld().getMaxHeight() + " blocks");
return;
}
// check whether the block clicked against should absorb the placement
BlockType againstType = ItemTable.instance().getBlock(against.getTypeId());
if (againstType.canAbsorb(against, face, holding)) {
target = against;
} else if (!target.isEmpty()) {
// air can always be overridden
BlockType targetType = ItemTable.instance().getBlock(target.getTypeId());
if (!targetType.canOverride(target, face, holding)) {
return;
}
}
// call canBuild event
boolean canBuild = canPlaceAt(target, face);
BlockCanBuildEvent canBuildEvent = new BlockCanBuildEvent(target, getId(), canBuild);
if (!EventFactory.callEvent(canBuildEvent).isBuildable()) {
//revert(player, target);
return;
}
// grab states and update block
GlowBlockState oldState = target.getState(), newState = target.getState();
ItemType itemType = ItemTable.instance().getItem(holding.getType());
if (itemType.getPlaceAs() == null) {
placeBlock(player, newState, face, holding, clickedLoc);
} else {
placeBlock(player, newState, face, new ItemStack(itemType.getPlaceAs().getMaterial(), 1), clickedLoc);
}
newState.update(true);
// call blockPlace event
BlockPlaceEvent event = new BlockPlaceEvent(target, oldState, against, holding, player, canBuild);
EventFactory.callEvent(event);
if (event.isCancelled() || !event.canBuild()) {
oldState.update(true);
return;
}
// play a sound effect
getPlaceSound().play(target.getLocation());
// do any after-place actions
afterPlace(player, target, holding, oldState);
// deduct from stack if not in creative mode
if (player.getGameMode() != GameMode.CREATIVE) {
holding.setAmount(holding.getAmount() - 1);
}
}
/**
* Called to check if this block can perform random tick updates.
*
* @return Whether this block updates on tick.
*/
public boolean canTickRandomly() {
return false;
}
/**
* Called when this block needs to be updated.
*
* @param block The block that needs an update
*/
public void updateBlock(GlowBlock block) {
// do nothing
}
// Helper methods
/**
* Called when a player left clicks a block
*
* @param player the player who clicked the block
* @param block the block that was clicked
* @param holding the ItemStack that was being held
*/
public void leftClickBlock(GlowPlayer player, GlowBlock block, ItemStack holding) {
// do nothing
}
/**
* Display the warning for finding the wrong MaterialData subclass.
*
* @param clazz The expected subclass of MaterialData.
* @param data The actual MaterialData found.
*/
protected void warnMaterialData(Class<?> clazz, MaterialData data) {
GlowServer.logger.warning("Wrong MaterialData for " + getMaterial() + " (" + getClass().getSimpleName() + "): expected " + clazz.getSimpleName() + ", got " + data);
}
public void onRedstoneUpdate(GlowBlock block) {
// do nothing
}
/**
* Called when an entity gets updated on top of the block
*
* @param block the block that was stepped on
* @param entity the entity
*/
public void onEntityStep(GlowBlock block, LivingEntity entity) {
// do nothing
}
}
|
package net.glowstone.constants;
import net.glowstone.inventory.MaterialMatcher;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.enchantments.EnchantmentTarget;
import org.bukkit.inventory.ItemStack;
/**
* Definitions of enchantment types.
*/
public final class GlowEnchantment extends Enchantment {
private final Impl impl;
private GlowEnchantment(Impl impl) {
super(impl.id);
this.impl = impl;
}
@Override
public String getName() {
// nb: returns enum name, not text name
return impl.name();
}
@Override
public int getMaxLevel() {
return impl.maxLevel;
}
@Override
public int getStartLevel() {
return 1;
}
@Override
public EnchantmentTarget getItemTarget() {
return impl.target;
}
@Override
public boolean conflictsWith(Enchantment other) {
return impl.group != GROUP_NONE && impl.group == ((GlowEnchantment) other).impl.group;
}
@Override
public boolean canEnchantItem(ItemStack item) {
return impl.matcher.matches(item.getType());
}
/**
* Register all enchantment types with Enchantment.
*/
public static void register() {
for (Impl impl : Impl.values()) {
registerEnchantment(new GlowEnchantment(impl));
}
stopAcceptingRegistrations();
}
private static final MaterialMatcher SWORD_OR_AXE = new MaterialMatcher() {
@Override
public boolean matches(Material item) {
return EnchantmentTarget.WEAPON.includes(item)
|| item.equals(Material.WOOD_AXE)
|| item.equals(Material.STONE_AXE)
|| item.equals(Material.IRON_AXE)
|| item.equals(Material.DIAMOND_AXE)
|| item.equals(Material.GOLD_AXE);
}
};
private static final MaterialMatcher BASE_TOOLS = new MaterialMatcher() {
@Override
public boolean matches(Material item) {
return item.equals(Material.WOOD_SPADE)
|| item.equals(Material.STONE_SPADE)
|| item.equals(Material.IRON_SPADE)
|| item.equals(Material.DIAMOND_SPADE)
|| item.equals(Material.GOLD_SPADE)
|| item.equals(Material.WOOD_PICKAXE)
|| item.equals(Material.STONE_PICKAXE)
|| item.equals(Material.IRON_PICKAXE)
|| item.equals(Material.DIAMOND_PICKAXE)
|| item.equals(Material.GOLD_PICKAXE)
|| item.equals(Material.WOOD_AXE)
|| item.equals(Material.STONE_AXE)
|| item.equals(Material.IRON_AXE)
|| item.equals(Material.DIAMOND_AXE)
|| item.equals(Material.GOLD_AXE);
}
};
private static final MaterialMatcher DIGGING_TOOLS = new MaterialMatcher() {
@Override
public boolean matches(Material material) {
return BASE_TOOLS.matches(material)
|| material == Material.SHEARS;
}
};
private static final MaterialMatcher ALL_THINGS = new MaterialMatcher() {
@Override
public boolean matches(Material material) {
return EnchantmentTarget.TOOL.includes(material)
|| EnchantmentTarget.WEAPON.includes(material)
|| EnchantmentTarget.ARMOR.includes(material)
|| material == Material.FISHING_ROD
|| material == Material.BOW
|| material == Material.CARROT_STICK;
}
};
private static final int GROUP_NONE = 0;
private static final int GROUP_PROTECT = 1;
private static final int GROUP_ATTACK = 2;
private static final int GROUP_DIG = 3;
private static enum Impl {
PROTECTION_ENVIRONMENTAL(0, "Protection", 4, EnchantmentTarget.ARMOR, GROUP_PROTECT),
PROTECTION_FIRE(1, "Fire Protection", 4, EnchantmentTarget.ARMOR, GROUP_PROTECT),
PROTECTION_FALL(2, "Feather Falling", 4, EnchantmentTarget.ARMOR_FEET, GROUP_PROTECT),
PROTECTION_EXPLOSIONS(3, "Blast Protection", 4, EnchantmentTarget.ARMOR),
PROTECTION_PROJECTILE(4, "Projectile Protection", 4, EnchantmentTarget.ARMOR, GROUP_PROTECT),
OXYGEN(5, "Respiration", 3, EnchantmentTarget.ARMOR_HEAD),
WATER_WORKER(6, "Aqua Affinity", 1, EnchantmentTarget.ARMOR_HEAD),
THORNS(7, "Thorns", 3, EnchantmentTarget.ARMOR_TORSO, new MatcherAdapter(EnchantmentTarget.ARMOR)),
DEPTH_STRIDER(8, "Depth Strider", 3, EnchantmentTarget.ARMOR_FEET),
DAMAGE_ALL(16, "Sharpness", 5, EnchantmentTarget.WEAPON, SWORD_OR_AXE, GROUP_ATTACK),
DAMAGE_UNDEAD(17, "Smite", 5, EnchantmentTarget.WEAPON, SWORD_OR_AXE, GROUP_ATTACK),
DAMAGE_ARTHROPODS(18, "Bane of Arthropods", 5, EnchantmentTarget.WEAPON, SWORD_OR_AXE, GROUP_ATTACK),
KNOCKBACK(19, "Knockback", 2, EnchantmentTarget.WEAPON),
FIRE_ASPECT(20, "Fire Aspect", 2, EnchantmentTarget.WEAPON),
LOOT_BONUS_MOBS(21, "Looting", 3, EnchantmentTarget.WEAPON),
DIG_SPEED(32, "Efficiency", 5, EnchantmentTarget.TOOL, DIGGING_TOOLS),
SILK_TOUCH(33, "Silk Touch", 1, EnchantmentTarget.TOOL, DIGGING_TOOLS, GROUP_DIG),
DURABILITY(34, "Unbreaking", 3, EnchantmentTarget.TOOL, ALL_THINGS),
LOOT_BONUS_BLOCKS(35, "Fortune", 3, EnchantmentTarget.TOOL, BASE_TOOLS, GROUP_DIG),
ARROW_DAMAGE(48, "Power", 5, EnchantmentTarget.BOW),
ARROW_KNOCKBACK(49, "Punch", 2, EnchantmentTarget.BOW),
ARROW_FIRE(50, "Flame", 1, EnchantmentTarget.BOW),
ARROW_INFINITE(51, "Infinity", 1, EnchantmentTarget.BOW),
LUCK(61, "Luck of the Sea", 3, EnchantmentTarget.FISHING_ROD),
LURE(62, "Lure", 3, EnchantmentTarget.FISHING_ROD);
private final int id;
private final String name;
private final int maxLevel;
private final EnchantmentTarget target;
private final MaterialMatcher matcher;
private final int group;
Impl(int id, String name, int max, EnchantmentTarget target) {
this(id, name, max, target, new MatcherAdapter(target), GROUP_NONE);
}
Impl(int id, String name, int max, EnchantmentTarget target, int group) {
this(id, name, max, target, new MatcherAdapter(target), group);
}
Impl(int id, String name, int max, EnchantmentTarget target, MaterialMatcher matcher) {
this(id, name, max, target, matcher, GROUP_NONE);
}
Impl(int id, String name, int max, EnchantmentTarget target, MaterialMatcher matcher, int group) {
this.id = id;
this.name = name;
this.maxLevel = max;
this.target = target;
this.matcher = matcher;
this.group = group;
}
}
private static class MatcherAdapter implements MaterialMatcher {
private final EnchantmentTarget target;
public MatcherAdapter(EnchantmentTarget target) {
this.target = target;
}
@Override
public boolean matches(Material material) {
return target.includes(material);
}
}
}
|
package net.gotei.intrinio.common;
import java.math.BigDecimal;
public class PagedResponse<T> {
/** Total number of results.*/
private BigDecimal result_count;
/** Number of results on the page*/
private BigDecimal page_size;
/** Current page number*/
private BigDecimal current_page;
/** Total number of pages in responce*/
private BigDecimal total_pages;
/** Payload */
private T[] data;
public PagedResponse() {
}
public BigDecimal getResult_count() {
return result_count;
}
public void setResult_count(BigDecimal result_count) {
this.result_count = result_count;
}
public BigDecimal getPage_size() {
return page_size;
}
public void setPage_size(BigDecimal page_size) {
this.page_size = page_size;
}
public BigDecimal getCurrent_page() {
return current_page;
}
public void setCurrent_page(BigDecimal current_page) {
this.current_page = current_page;
}
public BigDecimal getTotal_pages() {
return total_pages;
}
public void setTotal_pages(BigDecimal total_pages) {
this.total_pages = total_pages;
}
public T[] getData() {
return data;
}
public void setData(T[] data) {
this.data = data;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.