answer
stringlengths
17
10.2M
package com.epam.ta.reportportal.core.configs; import com.epam.ta.reportportal.commons.ExceptionMappings; import com.epam.ta.reportportal.commons.exception.forwarding.ClientResponseForwardingExceptionHandler; import com.epam.ta.reportportal.commons.exception.rest.DefaultErrorResolver; import com.epam.ta.reportportal.commons.exception.rest.ReportPortalExceptionResolver; import com.epam.ta.reportportal.commons.exception.rest.RestExceptionHandler; import com.epam.ta.reportportal.ws.resolver.*; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.Preconditions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.web.HttpMessageConverters; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.Ordered; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.validation.beanvalidation.BeanValidationPostProcessor; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import java.util.Collections; import java.util.List; import static com.google.common.base.Strings.isNullOrEmpty; /** * Class-based Spring MVC Configuration * * @author Andrei Varabyeu */ @Configuration @EnableConfigurationProperties(MvcConfig.MultipartConfig.class) public class MvcConfig extends WebMvcConfigurerAdapter { @Autowired private ObjectMapper objectMapper; @Autowired private List<HttpMessageConverter<?>> converters; private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/public/", "classpath:/META-INF/resources/", "classpath:/resources/" }; @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { /* to propagate exceptions from downstream services */
package structure.impl.other; import java.util.Arrays; import structure.intf.Binding; /** * Represents the binding for a set of free variables * * @author Helena Cuenca * @author Giles Reger */ public class BindingImpl extends Binding { // TODO Check name /** * Array of values for the objects. The size of the array is equal to the * number of free variables. The position of an object in the array * corresponds to the name of the variable - 1 */ private Object[] values; /** * Creates a new Binding with the specified number of variables * * @param variablesCount * Number of variables for this binding */ public BindingImpl(int variablesCount) { values = new Object[variablesCount]; } /** * Returns the value of the variable with the specified name * * @param variableName * Variable name * @return Value of the variable */ @Override public Object getValue(int variableName) { return values[variableName - 1]; } /** * Sets the value of the variable with the specified name * * @param variableName * Variable name * @param value * Value of the variable */ @Override public void setValue(int variableName, Object value) { values[variableName - 1] = value; } @Override public Binding copy() { Binding binding = new BindingImpl(values.length); for (int i = 0; i < values.length; i++) { binding.setValue(i + 1, values[i]); } return binding; } @Override public void setEmpty() { // Make all references null for (int i = 0; i < values.length; i++) { values[i] = null; } } @Override public String toString() { String[] out = new String[values.length]; for (int i = 0; i < values.length; i++) { if (values[i] == null) { out[i] = "-"; } else { out[i] = values[i].toString(); } } return Arrays.toString(out); } }
package com.fasterxml.jackson.databind.util; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.math.BigDecimal; import java.math.BigInteger; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.core.base.ParserMinimalBase; import com.fasterxml.jackson.core.json.JsonReadContext; import com.fasterxml.jackson.core.json.JsonWriteContext; import com.fasterxml.jackson.core.util.ByteArrayBuilder; import com.fasterxml.jackson.databind.cfg.DatabindVersion; /** * Utility class used for efficient storage of {@link JsonToken} * sequences, needed for temporary buffering. * Space efficient for different sequence lengths (especially so for smaller * ones; but not significantly less efficient for larger), highly efficient * for linear iteration and appending. Implemented as segmented/chunked * linked list of tokens; only modifications are via appends. *<p> * Note that before version 2.0, this class was located in the "core" * bundle, not data-binding; but since it was only used by data binding, * was moved here to reduce size of core package */ public class TokenBuffer /* Won't use JsonGeneratorBase, to minimize overhead for validity * checking */ extends JsonGenerator { protected final static int DEFAULT_PARSER_FEATURES = JsonParser.Feature.collectDefaults(); /** * Object codec to use for stream-based object * conversion through parser/generator interfaces. If null, * such methods can not be used. */ protected ObjectCodec _objectCodec; /** * Bit flag composed of bits that indicate which * {@link com.fasterxml.jackson.core.JsonGenerator.Feature}s * are enabled. *<p> * NOTE: most features have no effect on this class */ protected int _generatorFeatures; protected boolean _closed; /** * First segment, for contents this buffer has */ protected Segment _first; /** * Last segment of this buffer, one that is used * for appending more tokens */ protected Segment _last; /** * Offset within last segment, */ protected int _appendOffset; protected JsonWriteContext _writeContext; /** * @param codec Object codec to use for stream-based object * conversion through parser/generator interfaces. If null, * such methods can not be used. */ public TokenBuffer(ObjectCodec codec) { _objectCodec = codec; _generatorFeatures = DEFAULT_PARSER_FEATURES; _writeContext = JsonWriteContext.createRootContext(); // at first we have just one segment _first = _last = new Segment(); _appendOffset = 0; } @Override public Version version() { return DatabindVersion.instance.version(); } /** * Method used to create a {@link JsonParser} that can read contents * stored in this buffer. Will use default <code>_objectCodec</code> for * object conversions. *<p> * Note: instances are not synchronized, that is, they are not thread-safe * if there are concurrent appends to the underlying buffer. * * @return Parser that can be used for reading contents stored in this buffer */ public JsonParser asParser() { return asParser(_objectCodec); } /** * Method used to create a {@link JsonParser} that can read contents * stored in this buffer. *<p> * Note: instances are not synchronized, that is, they are not thread-safe * if there are concurrent appends to the underlying buffer. * * @param codec Object codec to use for stream-based object * conversion through parser/generator interfaces. If null, * such methods can not be used. * * @return Parser that can be used for reading contents stored in this buffer */ public JsonParser asParser(ObjectCodec codec) { return new Parser(_first, codec); } /** * @param src Parser to use for accessing source information * like location, configured codec */ public JsonParser asParser(JsonParser src) { Parser p = new Parser(_first, src.getCodec()); p.setLocation(src.getTokenLocation()); return p; } /** * Helper method that will append contents of given buffer into this * buffer. * Not particularly optimized; can be made faster if there is need. * * @return This buffer */ public TokenBuffer append(TokenBuffer other) throws IOException, JsonGenerationException { JsonParser jp = other.asParser(); while (jp.nextToken() != null) { this.copyCurrentEvent(jp); } return this; } /** * Helper method that will write all contents of this buffer * using given {@link JsonGenerator}. *<p> * Note: this method would be enough to implement * <code>JsonSerializer</code> for <code>TokenBuffer</code> type; * but we can not have upwards * references (from core to mapper package); and as such we also * can not take second argument. */ public void serialize(JsonGenerator jgen) throws IOException, JsonGenerationException { Segment segment = _first; int ptr = -1; while (true) { if (++ptr >= Segment.TOKENS_PER_SEGMENT) { ptr = 0; segment = segment.next(); if (segment == null) break; } JsonToken t = segment.type(ptr); if (t == null) break; // Note: copied from 'copyCurrentEvent'... switch (t) { case START_OBJECT: jgen.writeStartObject(); break; case END_OBJECT: jgen.writeEndObject(); break; case START_ARRAY: jgen.writeStartArray(); break; case END_ARRAY: jgen.writeEndArray(); break; case FIELD_NAME: { // 13-Dec-2010, tatu: Maybe we should start using different type tokens to reduce casting? Object ob = segment.get(ptr); if (ob instanceof SerializableString) { jgen.writeFieldName((SerializableString) ob); } else { jgen.writeFieldName((String) ob); } } break; case VALUE_STRING: { Object ob = segment.get(ptr); if (ob instanceof SerializableString) { jgen.writeString((SerializableString) ob); } else { jgen.writeString((String) ob); } } break; case VALUE_NUMBER_INT: { Number n = (Number) segment.get(ptr); if (n instanceof BigInteger) { jgen.writeNumber((BigInteger) n); } else if (n instanceof Long) { jgen.writeNumber(n.longValue()); } else { jgen.writeNumber(n.intValue()); } } break; case VALUE_NUMBER_FLOAT: { Object n = segment.get(ptr); if (n instanceof BigDecimal) { jgen.writeNumber((BigDecimal) n); } else if (n instanceof Float) { jgen.writeNumber(((Float) n).floatValue()); } else if (n instanceof Double) { jgen.writeNumber(((Double) n).doubleValue()); } else if (n == null) { jgen.writeNull(); } else if (n instanceof String) { jgen.writeNumber((String) n); } else { throw new JsonGenerationException("Unrecognized value type for VALUE_NUMBER_FLOAT: "+n.getClass().getName()+", can not serialize"); } } break; case VALUE_TRUE: jgen.writeBoolean(true); break; case VALUE_FALSE: jgen.writeBoolean(false); break; case VALUE_NULL: jgen.writeNull(); break; case VALUE_EMBEDDED_OBJECT: jgen.writeObject(segment.get(ptr)); break; default: throw new RuntimeException("Internal error: should never end up through this code path"); } } } @Override public String toString() { // Let's print up to 100 first tokens... final int MAX_COUNT = 100; StringBuilder sb = new StringBuilder(); sb.append("[TokenBuffer: "); JsonParser jp = asParser(); int count = 0; while (true) { JsonToken t; try { t = jp.nextToken(); if (t == null) break; if (count < MAX_COUNT) { if (count > 0) { sb.append(", "); } sb.append(t.toString()); if (t == JsonToken.FIELD_NAME) { sb.append('('); sb.append(jp.getCurrentName()); sb.append(')'); } } } catch (IOException ioe) { // should never occur throw new IllegalStateException(ioe); } ++count; } if (count >= MAX_COUNT) { sb.append(" ... (truncated ").append(count-MAX_COUNT).append(" entries)"); } sb.append(']'); return sb.toString(); } @Override public JsonGenerator enable(Feature f) { _generatorFeatures |= f.getMask(); return this; } @Override public JsonGenerator disable(Feature f) { _generatorFeatures &= ~f.getMask(); return this; } //public JsonGenerator configure(SerializationFeature f, boolean state) { } @Override public boolean isEnabled(Feature f) { return (_generatorFeatures & f.getMask()) != 0; } @Override public JsonGenerator useDefaultPrettyPrinter() { // No-op: we don't indent return this; } @Override public JsonGenerator setCodec(ObjectCodec oc) { _objectCodec = oc; return this; } @Override public ObjectCodec getCodec() { return _objectCodec; } @Override public final JsonWriteContext getOutputContext() { return _writeContext; } @Override public void flush() throws IOException { /* NOP */ } @Override public void close() throws IOException { _closed = true; } @Override public boolean isClosed() { return _closed; } @Override public final void writeStartArray() throws IOException, JsonGenerationException { _append(JsonToken.START_ARRAY); _writeContext = _writeContext.createChildArrayContext(); } @Override public final void writeEndArray() throws IOException, JsonGenerationException { _append(JsonToken.END_ARRAY); // Let's allow unbalanced tho... i.e. not run out of root level, ever JsonWriteContext c = _writeContext.getParent(); if (c != null) { _writeContext = c; } } @Override public final void writeStartObject() throws IOException, JsonGenerationException { _append(JsonToken.START_OBJECT); _writeContext = _writeContext.createChildObjectContext(); } @Override public final void writeEndObject() throws IOException, JsonGenerationException { _append(JsonToken.END_OBJECT); // Let's allow unbalanced tho... i.e. not run out of root level, ever JsonWriteContext c = _writeContext.getParent(); if (c != null) { _writeContext = c; } } @Override public final void writeFieldName(String name) throws IOException, JsonGenerationException { _append(JsonToken.FIELD_NAME, name); _writeContext.writeFieldName(name); } @Override public void writeFieldName(SerializableString name) throws IOException, JsonGenerationException { _append(JsonToken.FIELD_NAME, name); _writeContext.writeFieldName(name.getValue()); } @Override public void writeString(String text) throws IOException,JsonGenerationException { if (text == null) { writeNull(); } else { _append(JsonToken.VALUE_STRING, text); } } @Override public void writeString(char[] text, int offset, int len) throws IOException, JsonGenerationException { writeString(new String(text, offset, len)); } @Override public void writeString(SerializableString text) throws IOException, JsonGenerationException { if (text == null) { writeNull(); } else { _append(JsonToken.VALUE_STRING, text); } } @Override public void writeRawUTF8String(byte[] text, int offset, int length) throws IOException, JsonGenerationException { // could add support for buffering if we really want it... _reportUnsupportedOperation(); } @Override public void writeUTF8String(byte[] text, int offset, int length) throws IOException, JsonGenerationException { // could add support for buffering if we really want it... _reportUnsupportedOperation(); } @Override public void writeRaw(String text) throws IOException, JsonGenerationException { _reportUnsupportedOperation(); } @Override public void writeRaw(String text, int offset, int len) throws IOException, JsonGenerationException { _reportUnsupportedOperation(); } public void writeRaw(SerializableString text) throws IOException, JsonGenerationException { _reportUnsupportedOperation(); } @Override public void writeRaw(char[] text, int offset, int len) throws IOException, JsonGenerationException { _reportUnsupportedOperation(); } @Override public void writeRaw(char c) throws IOException, JsonGenerationException { _reportUnsupportedOperation(); } @Override public void writeRawValue(String text) throws IOException, JsonGenerationException { _reportUnsupportedOperation(); } @Override public void writeRawValue(String text, int offset, int len) throws IOException, JsonGenerationException { _reportUnsupportedOperation(); } @Override public void writeRawValue(char[] text, int offset, int len) throws IOException, JsonGenerationException { _reportUnsupportedOperation(); } @Override public void writeNumber(int i) throws IOException, JsonGenerationException { _append(JsonToken.VALUE_NUMBER_INT, Integer.valueOf(i)); } @Override public void writeNumber(long l) throws IOException, JsonGenerationException { _append(JsonToken.VALUE_NUMBER_INT, Long.valueOf(l)); } @Override public void writeNumber(double d) throws IOException,JsonGenerationException { _append(JsonToken.VALUE_NUMBER_FLOAT, Double.valueOf(d)); } @Override public void writeNumber(float f) throws IOException, JsonGenerationException { _append(JsonToken.VALUE_NUMBER_FLOAT, Float.valueOf(f)); } @Override public void writeNumber(BigDecimal dec) throws IOException,JsonGenerationException { if (dec == null) { writeNull(); } else { _append(JsonToken.VALUE_NUMBER_FLOAT, dec); } } @Override public void writeNumber(BigInteger v) throws IOException, JsonGenerationException { if (v == null) { writeNull(); } else { _append(JsonToken.VALUE_NUMBER_INT, v); } } @Override public void writeNumber(String encodedValue) throws IOException, JsonGenerationException { /* 03-Dec-2010, tatu: related to [JACKSON-423], should try to keep as numeric * identity as long as possible */ _append(JsonToken.VALUE_NUMBER_FLOAT, encodedValue); } @Override public void writeBoolean(boolean state) throws IOException,JsonGenerationException { _append(state ? JsonToken.VALUE_TRUE : JsonToken.VALUE_FALSE); } @Override public void writeNull() throws IOException, JsonGenerationException { _append(JsonToken.VALUE_NULL); } @Override public void writeObject(Object value) throws IOException, JsonProcessingException { // embedded means that no conversions should be done... _append(JsonToken.VALUE_EMBEDDED_OBJECT, value); } @Override public void writeTree(TreeNode rootNode) throws IOException, JsonProcessingException { /* 31-Dec-2009, tatu: no need to convert trees either is there? * (note: may need to re-evaluate at some point) */ _append(JsonToken.VALUE_EMBEDDED_OBJECT, rootNode); } @Override public void writeBinary(Base64Variant b64variant, byte[] data, int offset, int len) throws IOException, JsonGenerationException { /* 31-Dec-2009, tatu: can do this using multiple alternatives; but for * now, let's try to limit number of conversions. * The only (?) tricky thing is that of whether to preserve variant, * seems pointless, so let's not worry about it unless there's some * compelling reason to. */ byte[] copy = new byte[len]; System.arraycopy(data, offset, copy, 0, len); writeObject(copy); } /** * Although we could support this method, it does not necessarily make * sense: we can not make good use of streaming because buffer must * hold all the data. Because of this, currently this will simply * throw {@link UnsupportedOperationException} */ @Override public int writeBinary(Base64Variant b64variant, InputStream data, int dataLength) { throw new UnsupportedOperationException(); } @Override public void copyCurrentEvent(JsonParser jp) throws IOException, JsonProcessingException { switch (jp.getCurrentToken()) { case START_OBJECT: writeStartObject(); break; case END_OBJECT: writeEndObject(); break; case START_ARRAY: writeStartArray(); break; case END_ARRAY: writeEndArray(); break; case FIELD_NAME: writeFieldName(jp.getCurrentName()); break; case VALUE_STRING: if (jp.hasTextCharacters()) { writeString(jp.getTextCharacters(), jp.getTextOffset(), jp.getTextLength()); } else { writeString(jp.getText()); } break; case VALUE_NUMBER_INT: switch (jp.getNumberType()) { case INT: writeNumber(jp.getIntValue()); break; case BIG_INTEGER: writeNumber(jp.getBigIntegerValue()); break; default: writeNumber(jp.getLongValue()); } break; case VALUE_NUMBER_FLOAT: switch (jp.getNumberType()) { case BIG_DECIMAL: writeNumber(jp.getDecimalValue()); break; case FLOAT: writeNumber(jp.getFloatValue()); break; default: writeNumber(jp.getDoubleValue()); } break; case VALUE_TRUE: writeBoolean(true); break; case VALUE_FALSE: writeBoolean(false); break; case VALUE_NULL: writeNull(); break; case VALUE_EMBEDDED_OBJECT: writeObject(jp.getEmbeddedObject()); break; default: throw new RuntimeException("Internal error: should never end up through this code path"); } } @Override public void copyCurrentStructure(JsonParser jp) throws IOException, JsonProcessingException { JsonToken t = jp.getCurrentToken(); // Let's handle field-name separately first if (t == JsonToken.FIELD_NAME) { writeFieldName(jp.getCurrentName()); t = jp.nextToken(); // fall-through to copy the associated value } switch (t) { case START_ARRAY: writeStartArray(); while (jp.nextToken() != JsonToken.END_ARRAY) { copyCurrentStructure(jp); } writeEndArray(); break; case START_OBJECT: writeStartObject(); while (jp.nextToken() != JsonToken.END_OBJECT) { copyCurrentStructure(jp); } writeEndObject(); break; default: // others are simple: copyCurrentEvent(jp); } } protected final void _append(JsonToken type) { Segment next = _last.append(_appendOffset, type); if (next == null) { ++_appendOffset; } else { _last = next; _appendOffset = 1; // since we added first at 0 } } protected final void _append(JsonToken type, Object value) { Segment next = _last.append(_appendOffset, type, value); if (next == null) { ++_appendOffset; } else { _last = next; _appendOffset = 1; } } protected final void _appendRaw(int rawType, Object value) { Segment next = _last.appendRaw(_appendOffset, rawType, value); if (next == null) { ++_appendOffset; } else { _last = next; _appendOffset = 1; } } protected void _reportUnsupportedOperation() { throw new UnsupportedOperationException("Called operation not supported for TokenBuffer"); } protected final static class Parser extends ParserMinimalBase { protected ObjectCodec _codec; /** * Currently active segment */ protected Segment _segment; /** * Pointer to current token within current segment */ protected int _segmentPtr; /** * Information about parser context, context in which * the next token is to be parsed (root, array, object). */ protected JsonReadContext _parsingContext; protected boolean _closed; protected transient ByteArrayBuilder _byteBuilder; protected JsonLocation _location = null; public Parser(Segment firstSeg, ObjectCodec codec) { super(0); _segment = firstSeg; _segmentPtr = -1; // not yet read _codec = codec; _parsingContext = JsonReadContext.createRootContext(-1, -1); } public void setLocation(JsonLocation l) { _location = l; } @Override public ObjectCodec getCodec() { return _codec; } @Override public void setCodec(ObjectCodec c) { _codec = c; } @Override public Version version() { return DatabindVersion.instance.version(); } public JsonToken peekNextToken() throws IOException, JsonParseException { // closed? nothing more to peek, either if (_closed) return null; Segment seg = _segment; int ptr = _segmentPtr+1; if (ptr >= Segment.TOKENS_PER_SEGMENT) { ptr = 0; seg = (seg == null) ? null : seg.next(); } return (seg == null) ? null : seg.type(ptr); } @Override public void close() throws IOException { if (!_closed) { _closed = true; } } @Override public JsonToken nextToken() throws IOException, JsonParseException { // If we are closed, nothing more to do if (_closed || (_segment == null)) return null; // Ok, then: any more tokens? if (++_segmentPtr >= Segment.TOKENS_PER_SEGMENT) { _segmentPtr = 0; _segment = _segment.next(); if (_segment == null) { return null; } } _currToken = _segment.type(_segmentPtr); // Field name? Need to update context if (_currToken == JsonToken.FIELD_NAME) { Object ob = _currentObject(); String name = (ob instanceof String) ? ((String) ob) : ob.toString(); _parsingContext.setCurrentName(name); } else if (_currToken == JsonToken.START_OBJECT) { _parsingContext = _parsingContext.createChildObjectContext(-1, -1); } else if (_currToken == JsonToken.START_ARRAY) { _parsingContext = _parsingContext.createChildArrayContext(-1, -1); } else if (_currToken == JsonToken.END_OBJECT || _currToken == JsonToken.END_ARRAY) { // Closing JSON Object/Array? Close matching context _parsingContext = _parsingContext.getParent(); // but allow unbalanced cases too (more close markers) if (_parsingContext == null) { _parsingContext = JsonReadContext.createRootContext(-1, -1); } } return _currToken; } @Override public boolean isClosed() { return _closed; } @Override public JsonStreamContext getParsingContext() { return _parsingContext; } @Override public JsonLocation getTokenLocation() { return getCurrentLocation(); } @Override public JsonLocation getCurrentLocation() { return (_location == null) ? JsonLocation.NA : _location; } @Override public String getCurrentName() { return _parsingContext.getCurrentName(); } @Override public void overrideCurrentName(String name) { // Simple, but need to look for START_OBJECT/ARRAY's "off-by-one" thing: JsonReadContext ctxt = _parsingContext; if (_currToken == JsonToken.START_OBJECT || _currToken == JsonToken.START_ARRAY) { ctxt = ctxt.getParent(); } ctxt.setCurrentName(name); } @Override public String getText() { // common cases first: if (_currToken == JsonToken.VALUE_STRING || _currToken == JsonToken.FIELD_NAME) { Object ob = _currentObject(); if (ob instanceof String) { return (String) ob; } return (ob == null) ? null : ob.toString(); } if (_currToken == null) { return null; } switch (_currToken) { case VALUE_NUMBER_INT: case VALUE_NUMBER_FLOAT: Object ob = _currentObject(); return (ob == null) ? null : ob.toString(); } return _currToken.asString(); } @Override public char[] getTextCharacters() { String str = getText(); return (str == null) ? null : str.toCharArray(); } @Override public int getTextLength() { String str = getText(); return (str == null) ? 0 : str.length(); } @Override public int getTextOffset() { return 0; } @Override public boolean hasTextCharacters() { // We never have raw buffer available, so: return false; } @Override public BigInteger getBigIntegerValue() throws IOException, JsonParseException { Number n = getNumberValue(); if (n instanceof BigInteger) { return (BigInteger) n; } switch (getNumberType()) { case BIG_DECIMAL: return ((BigDecimal) n).toBigInteger(); } // int/long is simple, but let's also just truncate float/double: return BigInteger.valueOf(n.longValue()); } @Override public BigDecimal getDecimalValue() throws IOException, JsonParseException { Number n = getNumberValue(); if (n instanceof BigDecimal) { return (BigDecimal) n; } switch (getNumberType()) { case INT: case LONG: return BigDecimal.valueOf(n.longValue()); case BIG_INTEGER: return new BigDecimal((BigInteger) n); } // float or double return BigDecimal.valueOf(n.doubleValue()); } @Override public double getDoubleValue() throws IOException, JsonParseException { return getNumberValue().doubleValue(); } @Override public float getFloatValue() throws IOException, JsonParseException { return getNumberValue().floatValue(); } @Override public int getIntValue() throws IOException, JsonParseException { // optimize common case: if (_currToken == JsonToken.VALUE_NUMBER_INT) { return ((Number) _currentObject()).intValue(); } return getNumberValue().intValue(); } @Override public long getLongValue() throws IOException, JsonParseException { return getNumberValue().longValue(); } @Override public NumberType getNumberType() throws IOException, JsonParseException { Number n = getNumberValue(); if (n instanceof Integer) return NumberType.INT; if (n instanceof Long) return NumberType.LONG; if (n instanceof Double) return NumberType.DOUBLE; if (n instanceof BigDecimal) return NumberType.BIG_DECIMAL; if (n instanceof Float) return NumberType.FLOAT; if (n instanceof BigInteger) return NumberType.BIG_INTEGER; return null; } @Override public final Number getNumberValue() throws IOException, JsonParseException { _checkIsNumber(); return (Number) _currentObject(); } @Override public Object getEmbeddedObject() { if (_currToken == JsonToken.VALUE_EMBEDDED_OBJECT) { return _currentObject(); } return null; } @Override public byte[] getBinaryValue(Base64Variant b64variant) throws IOException, JsonParseException { // First: maybe we some special types? if (_currToken == JsonToken.VALUE_EMBEDDED_OBJECT) { // Embedded byte array would work nicely... Object ob = _currentObject(); if (ob instanceof byte[]) { return (byte[]) ob; } // fall through to error case } if (_currToken != JsonToken.VALUE_STRING) { throw _constructError("Current token ("+_currToken+") not VALUE_STRING (or VALUE_EMBEDDED_OBJECT with byte[]), can not access as binary"); } final String str = getText(); if (str == null) { return null; } ByteArrayBuilder builder = _byteBuilder; if (builder == null) { _byteBuilder = builder = new ByteArrayBuilder(100); } else { _byteBuilder.reset(); } _decodeBase64(str, builder, b64variant); return builder.toByteArray(); } @Override public int readBinaryValue(Base64Variant b64variant, OutputStream out) throws IOException, JsonParseException { byte[] data = getBinaryValue(b64variant); if (data != null) { out.write(data, 0, data.length); return data.length; } return 0; } protected final Object _currentObject() { return _segment.get(_segmentPtr); } protected final void _checkIsNumber() throws JsonParseException { if (_currToken == null || !_currToken.isNumeric()) { throw _constructError("Current token ("+_currToken+") not numeric, can not use numeric value accessors"); } } @Override protected void _handleEOF() throws JsonParseException { _throwInternal(); } } /** * Individual segment of TokenBuffer that can store up to 16 tokens * (limited by 4 bits per token type marker requirement). * Current implementation uses fixed length array; could alternatively * use 16 distinct fields and switch statement (slightly more efficient * storage, slightly slower access) */ protected final static class Segment { public final static int TOKENS_PER_SEGMENT = 16; /** * Static array used for fast conversion between token markers and * matching {@link JsonToken} instances */ private final static JsonToken[] TOKEN_TYPES_BY_INDEX; static { // ... here we know that there are <= 16 values in JsonToken enum TOKEN_TYPES_BY_INDEX = new JsonToken[16]; JsonToken[] t = JsonToken.values(); System.arraycopy(t, 1, TOKEN_TYPES_BY_INDEX, 1, Math.min(15, t.length - 1)); } // // // Linking protected Segment _next; // // // State /** * Bit field used to store types of buffered tokens; 4 bits per token. * Value 0 is reserved for "not in use" */ protected long _tokenTypes; // Actual tokens protected final Object[] _tokens = new Object[TOKENS_PER_SEGMENT]; public Segment() { } // // // Accessors public JsonToken type(int index) { long l = _tokenTypes; if (index > 0) { l >>= (index << 2); } int ix = ((int) l) & 0xF; return TOKEN_TYPES_BY_INDEX[ix]; } public int rawType(int index) { long l = _tokenTypes; if (index > 0) { l >>= (index << 2); } int ix = ((int) l) & 0xF; return ix; } public Object get(int index) { return _tokens[index]; } public Segment next() { return _next; } // // // Mutators public Segment append(int index, JsonToken tokenType) { if (index < TOKENS_PER_SEGMENT) { set(index, tokenType); return null; } _next = new Segment(); _next.set(0, tokenType); return _next; } public Segment append(int index, JsonToken tokenType, Object value) { if (index < TOKENS_PER_SEGMENT) { set(index, tokenType, value); return null; } _next = new Segment(); _next.set(0, tokenType, value); return _next; } public Segment appendRaw(int index, int rawTokenType, Object value) { if (index < TOKENS_PER_SEGMENT) { set(index, rawTokenType, value); return null; } _next = new Segment(); _next.set(0, rawTokenType, value); return _next; } public void set(int index, JsonToken tokenType) { /* Assumption here is that there are no overwrites, just appends; * and so no masking is needed (nor explicit setting of null) */ long typeCode = tokenType.ordinal(); if (index > 0) { typeCode <<= (index << 2); } _tokenTypes |= typeCode; } public void set(int index, JsonToken tokenType, Object value) { _tokens[index] = value; long typeCode = tokenType.ordinal(); /* Assumption here is that there are no overwrites, just appends; * and so no masking is needed */ if (index > 0) { typeCode <<= (index << 2); } _tokenTypes |= typeCode; } private void set(int index, int rawTokenType, Object value) { _tokens[index] = value; long typeCode = (long) rawTokenType; if (index > 0) { typeCode <<= (index << 2); } _tokenTypes |= typeCode; } } }
package com.github.cqljmeter.sampler; import org.apache.commons.lang3.StringUtils; import org.apache.jmeter.samplers.AbstractSampler; import org.apache.jmeter.samplers.Entry; import org.apache.jmeter.samplers.SampleResult; import org.apache.jmeter.testbeans.TestBean; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; import com.datastax.driver.core.ConsistencyLevel; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.Session; import com.datastax.driver.core.Statement; import com.github.cqljmeter.config.ClusterHolder; import com.google.common.base.Joiner; public abstract class AbstractCqlSampler extends AbstractSampler implements TestBean { private static final long serialVersionUID = -996507992186021290L; private static final Logger log = LoggingManager.getLoggerForClass(); private String query = ""; private String keySpace = ""; private String clusterId = ""; private String consistency = null; public SampleResult sample(Entry arg0) { SampleResult result = new SampleResult(); result.setDataType(SampleResult.TEXT); result.setContentType("text/plain"); result.setSampleLabel(getName()); result.setSamplerData(query); // Assume we will be successful result.setSuccessful(true); result.setResponseMessageOK(); result.setResponseCodeOK(); Statement statement = configure(getStatement()); result.sampleStart(); try { ResultSet data = getSession(keySpace).execute(statement); result.setResponseData(getStringFrom(data).getBytes()); result.setResponseMessage(data.toString()); } catch (Exception ex) { log.error(String.format("Error executing CQL statement [%s]", getQuery()), ex); result.setResponseMessage(ex.toString()); result.setResponseData(ex.getMessage().getBytes()); result.setSuccessful(false); } result.sampleEnd(); return result; } private Statement configure(Statement statement) { if (StringUtils.isNotBlank(consistency)) { statement.setConsistencyLevel(ConsistencyLevel.valueOf(consistency)); } return statement; } protected abstract Statement getStatement(); private Session getSession(String input) { return ClusterHolder.getSesssion(getClusterId(), input); } public String getQuery() { return query; } public void setQuery(String query) { this.query = query; } public String getKeySpace() { return keySpace; } public void setKeySpace(String keySpace) { this.keySpace = keySpace; } public String getClusterId() { return clusterId; } public void setClusterId(String clusterId) { this.clusterId = clusterId; } public String getConsistency() { return consistency; } public void setConsistency(String consistency) { this.consistency = consistency; } private String getStringFrom(ResultSet input) { return Joiner.on("\n").join(input); } }
package com.github.ferstl.depgraph.graph.style; import java.util.Objects; import org.apache.commons.lang3.StringUtils; import com.google.common.base.Joiner; public final class StyleKey implements Comparable<StyleKey> { private static final int NUM_ELEMENTS = 5; String groupId; String artifactId; String scope; String type; String version; private StyleKey(String[] parts) { if (parts.length > NUM_ELEMENTS) { throw new IllegalArgumentException("Too many parts. Expecting '<groupId>:<artifactId>:<version>:<scope>:<type>'"); } String[] expanded = new String[NUM_ELEMENTS]; for (int i = 0; i < parts.length; i++) { expanded[i] = StringUtils.defaultIfEmpty(parts[i], null); } this.groupId = expanded[0]; this.artifactId = expanded[1]; this.scope = expanded[2]; this.type = expanded[3]; this.version = expanded[4]; } public static StyleKey fromString(String keyString) { String[] parts = keyString.split(","); return new StyleKey(parts); } public static StyleKey create(String groupId, String artifactId, String scope, String type, String version) { return new StyleKey(new String[]{groupId, artifactId, scope, type, version}); } public boolean matches(StyleKey other) { return (this.groupId == null || wildcardMatch(this.groupId, other.groupId)) && (this.artifactId == null || wildcardMatch(this.artifactId, other.artifactId)) && (this.scope == null || match(this.scope, other.scope)) && (this.type == null || match(this.type, other.type)) && (this.version == null || wildcardMatch(this.version, other.version)); } @Override public int compareTo(StyleKey o) { return getRank() - o.getRank(); } @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof StyleKey)) { return false; } StyleKey other = (StyleKey) obj; return Objects.equals(this.groupId, other.groupId) && Objects.equals(this.artifactId, other.artifactId) && Objects.equals(this.scope, other.scope) && Objects.equals(this.type, other.type) && Objects.equals(this.version, other.version); } @Override public int hashCode() { return Objects.hash(this.groupId, this.artifactId, this.scope, this.type, this.version); } @Override public String toString() { return Joiner.on(",").useForNull("").join(this.groupId, this.artifactId, this.scope, this.type, this.version); } private int getRank() { int rank = 0; rank += this.groupId != null ? 16 : 0; rank += this.artifactId != null ? 8 : 0; rank += this.scope != null ? 4 : 0; rank += this.type != null ? 2 : 0; rank += this.version != null ? 1 : 0; return rank; } private static boolean wildcardMatch(String value1, String value2) { if (StringUtils.endsWith(value1, "*")) { return StringUtils.startsWith(value2, value1.substring(0, value1.length() - 1)); } return match(value1, value2); } private static boolean match(String value1, String value2) { return StringUtils.equals(value1, value2); } }
package com.github.platinumrondo.shavedwords; import java.io.*; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.util.*; public class DictClient { private final String serverName; private final int serverPort; private Socket serverSocket; private BufferedReader serverIn; private BufferedWriter serverOut; public DictClient(String serverName, int port) { this.serverName = serverName; this.serverPort = port; } public void connect() throws IOException { if (isConnected()) throw new IllegalStateException(); serverSocket = new Socket(serverName, serverPort); serverIn = new BufferedReader( new InputStreamReader(serverSocket.getInputStream(), StandardCharsets.UTF_8)); serverOut = new BufferedWriter( new OutputStreamWriter(serverSocket.getOutputStream(), StandardCharsets.UTF_8)); StatusResponse status = readStatusResponse(); System.out.println(status); if (status.getCode() != 220) { serverSocket.close(); throw new DictException(status); } } /** * Check if we are connected. * * @return connection status. */ public boolean isConnected() { return serverSocket != null && serverSocket.isConnected() && !serverSocket.isClosed(); } private void checkAndConnect() throws IOException { if (!isConnected()) connect(); } /** * Ask the server for the definition of the word provided. * * @param database the database in which the server should lookup. * @param word the word. * @return all the definitions returned; a empty array if no definition * where found. * @throws IOException */ public DefineResult[] define(String database, String word) throws IOException { if (database == null || word == null) throw new IllegalArgumentException(); checkAndConnect(); sendCommand("define", database, word); StatusResponse result = readStatusResponse(); if (result.getCode() == 150) { return getDefinitions(); } else if (result.getCode() == 552) { return new DefineResult[0]; } //550: nonexistent db throw new DictException(result); } private DefineResult[] getDefinitions() throws IOException { checkAndConnect(); List<DefineResult> l = new ArrayList<>(); StatusResponse result = readStatusResponse(); while (result.getCode() != 250) { String str = readTextualResponse(); DefineResult dr = new DefineResult(result.getParam(0), result.getParam(1), result.getParam(2), str); l.add(dr); result = readStatusResponse(); } return l.toArray(new DefineResult[l.size()]); } /** * Find similar words to the one provided. * * @param database the database where to look for. * @param strategy the strategy to use for the search. * @param word the word (or part of it, or regex) * @return a list of possible words, or an empty string if nothing is found. * @throws IOException */ public Set<MatchResult> match(String database, String strategy, String word) throws IOException { if (database == null || strategy == null || word == null) throw new IllegalArgumentException(); checkAndConnect(); sendCommand("match", database, strategy, word); StatusResponse result = readStatusResponse(); if (result.getCode() == 152) { String matchedWords = readTextualResponse(); readStatusResponse(); return matchResponseToSet(matchedWords); } else if (result.getCode() == 552) { return new HashSet<>(); } //550: wrong db //552: wrong strategy throw new DictException(result); } private Set<MatchResult> matchResponseToSet(String str) { Set<MatchResult> resultSet = new HashSet<>(); String[] lines = str.split("\n"); for (String line : lines) { int middleSpace = line.indexOf(' '); String database = line.substring(0, middleSpace); String word = removeDoubleQuotes(line.substring(middleSpace + 1)); resultSet.add(new MatchResult(word, database)); } return resultSet; } /** * Gives you the dictionary the server will let you use. Some server may * have dictionary available only to * logged in users. * * @return map providing the db name in the key, and its description as the * value. * @throws IOException */ public Map<String, String> showDatabases() throws IOException { checkAndConnect(); sendCommand("show db"); StatusResponse result = readStatusResponse(); if (result.getCode() == 554) return new HashMap<>(); if (result.getCode() == 110) { String dbs = readTextualResponse(); readStatusResponse(); return parseStringToMap(dbs); } throw new DictException(result); } /** * Gives you all the strategies supported by the server, to be used with the * MATCH command. * * @return map providing the strategy in the key and its description in the * value. * @throws IOException */ public Map<String, String> showStrategies() throws IOException { checkAndConnect(); sendCommand("show strat"); StatusResponse result = readStatusResponse(); if (result.getCode() == 111) { //return: name description String strats = readTextualResponse(); readStatusResponse(); return parseStringToMap(strats); } throw new DictException(result); } private Map<String, String> parseStringToMap(String str) { String[] lines = str.split("\n"); Map<String, String> map = new HashMap<>(); for (String line : lines) { String[] parts = line.split(" ", 2); map.put(parts[0], removeDoubleQuotes(parts[1])); } return map; } private String removeDoubleQuotes(String s) { if (s.charAt(0) == '"') s = s.substring(1); if (s.charAt(s.length() - 1) == '"') s = s.substring(0, s.length() - 1); return s; } /** * Retrieve the information for the chosen database. * * @param database the chosen one. * @return the info. * @throws IOException */ public String showInfo(String database) throws IOException { if (database == null || database.trim().isEmpty()) throw new IllegalArgumentException(); checkAndConnect(); sendCommand("show info", database); StatusResponse result = readStatusResponse(); if (result.getCode() == 112) { String info = readTextualResponse(); readStatusResponse(); return info; } throw new DictException(result); } /** * Retrieve information on the server itself. * * @return info. * @throws IOException */ public String showServer() throws IOException { checkAndConnect(); sendCommand("show server"); StatusResponse result = readStatusResponse(); if (result.getCode() == 110) return readTextualResponse(); throw new DictException(result); } /** * Send to the server some information about the client, usually the name * and the version. * * @param text the text to send for identification. * @throws IOException */ public void client(String text) throws IOException { if (text == null || text.trim().isEmpty()) throw new IllegalArgumentException(); checkAndConnect(); sendCommand("client", text); StatusResponse result = readStatusResponse(); if (result.getCode() != 250) throw new DictException(result); } /** * Usually used for debugging purposes, ask the server for its status. * The answer is server dependent. * * @return server status. * @throws IOException */ public String status() throws IOException { checkAndConnect(); sendCommand("status"); StatusResponse result = readStatusResponse(); return result.getMessage(); } /** * Retrieve the help guide of the server. * * @return halp. * @throws IOException */ public String help() throws IOException { checkAndConnect(); sendCommand("help"); StatusResponse result = readStatusResponse(); if (result.getCode() == 113) { String help = readTextualResponse(); readStatusResponse(); return help; } throw new DictException(result); } /** * Authenticate the user. May unlock new dictionaries. * If the user is rejected, a DictException is raised. * * @param username the username * @param authstring an autentication string, a password. * @throws IOException */ public void auth(String username, String authstring) throws IOException { checkAndConnect(); sendCommand("auth", username, authstring); StatusResponse result = readStatusResponse(); if (result.getCode() == 230) return; throw new DictException(result); } /** * Tell the server we're leaving. * * @throws IOException */ public void quit() throws IOException { checkAndConnect(); sendCommand("quit"); StatusResponse result = readStatusResponse(); System.out.println(result); serverSocket.close(); } private void sendCommand(String cmd, String... params) throws IOException { serverOut.write(cmd); for (String param : params) { serverOut.write(" "); serverOut.write(escapeString(param)); } serverOut.write(13); serverOut.write(10); serverOut.flush(); } private String escapeString(String str) { if (str.contains(" ")) return '"' + str + '"'; return str; } private StatusResponse readStatusResponse() throws IOException { return new StatusResponse(serverIn.readLine()); } private String readTextualResponse() throws IOException { StringBuilder sb = new StringBuilder(); String txt = serverIn.readLine(); while (txt.compareTo(".") != 0) { txt = normalizeIncomingTextLine(txt); sb.append(txt); sb.append((char) 10); txt = serverIn.readLine(); } return sb.toString(); } private String normalizeIncomingTextLine(String str) { if (str.startsWith("..")) str = str.substring(1); return str; } }
package com.gmail.lifeofreilly.vanitas; import org.apache.log4j.Logger; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.NetworkParameters; import com.google.common.base.CharMatcher; import java.text.NumberFormat; import java.util.Locale; import java.util.Optional; import java.util.stream.LongStream; /** * A Bitcoin vanity address generator that leverages the Java 8 streams API. */ class AddressGenerator { private static final Logger log = Logger.getLogger(AddressGenerator.class); private static final int BTC_ADDRESS_MAX_LENGTH = 35; private final NetworkParameters netParams; private final String searchString; /** * Sole constructor for AddressGenerator * * @param searchString the desired bitcoin address substring * @param netParams the target bitcoin network */ public AddressGenerator(final String searchString, final NetworkParameters netParams) { this.netParams = netParams; if (isValidSearchString(searchString)) { this.searchString = searchString; } else { log.error("Filed to create AddressGenerator. IllegalArgumentException: " + "The target phrase '" + searchString + "' is not valid in a bitcoin address."); throw new IllegalArgumentException("The target phrase '" + searchString + "' is not valid in a bitcoin address."); } } /** * Generates a stream of keys and returns the first match. * * @return an ECKey with an address that contains the search string */ public ECKey generate() { Optional<ECKey> found = LongStream.iterate(0L, n -> n + 1) .parallel() .peek(AddressGenerator::logAttempts) .mapToObj(ignore -> new ECKey()) .filter(key -> key.toAddress(netParams).toString().contains(searchString)) .findAny(); return found.get(); } public static boolean isValidSearchString(final String substring) { boolean validity = true; if (!CharMatcher.JAVA_LETTER_OR_DIGIT.matchesAllOf(substring) || substring.length() > BTC_ADDRESS_MAX_LENGTH || CharMatcher.anyOf("OIl0").matchesAnyOf(substring)) { validity = false; } return validity; } /** * For every 1 million attempts, log the total number of attempts * * @param attempts the current number of attempts */ private static void logAttempts(long attempts) { if (attempts == 0) { log.debug("Address generation initiated."); } else if (attempts % 1000000 == 0) { log.debug("Address generation in progress, attempts made: " + NumberFormat.getNumberInstance(Locale.US).format(attempts)); } } }
package com.google.appengine.endpoints; import com.google.api.server.spi.config.Api; import com.google.appengine.repackaged.com.google.common.io.Files; import com.google.common.base.Joiner; import eu.infomas.annotation.AnnotationDetector; import java.io.File; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.TreeSet; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.maven.plugin.logging.Log; import org.apache.maven.project.MavenProject; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.SAXException; /** * Process Endpoints annotations and change web.xml accordingly. * */ public class WebXmlProcessing { Log log; String webXmlSourcePath; String outputDirectory; MavenProject project; public WebXmlProcessing(Log log, String webXmlSourcePath, String outputDirectory, MavenProject project) { this.log = log; this.webXmlSourcePath = webXmlSourcePath; this.outputDirectory = outputDirectory; this.project = project; } private Log getLog() { return log; } public List<String> getAPIServicesClasses() { ApiReporter reporter = new ApiReporter(); String targetDir = project.getBuild().getOutputDirectory(); final AnnotationDetector cf = new AnnotationDetector(reporter); try { cf.detect(new File(targetDir)); } catch (IOException ex) { getLog().info(ex); } List<String> classes = reporter.getClasses(); XmlUtil util = new XmlUtil(); try { util.updateWebXml(classes, webXmlSourcePath); } catch (Exception ex) { getLog().info("Error: " + ex); } return classes; } class ApiReporter implements AnnotationDetector.TypeReporter { private List<String> classes = new ArrayList<String>(); @SuppressWarnings("unchecked") @Override public Class<? extends Annotation>[] annotations() { return new Class[]{Api.class}; } @Override public void reportTypeAnnotation(Class<? extends Annotation> annotation, String className) { classes.add(className); } public List<String> getClasses() { return classes; } } /** * Xml Manipulation Utility Class for modifying web.xml for generated APIs. */ class XmlUtil { private static final String COMMA = ","; private static final String WEB_APP = "web-app"; private static final String INIT_PARAM = "init-param"; private static final String SERVLET = "servlet"; private static final String SERVLET_NAME = "servlet-name"; private static final String SERVLET_MAPPING = "servlet-mapping"; private static final String SERVLET_CLASS = "servlet-class"; private static final String URL_PATTERN = "url-pattern"; /** * Finds the WebApp node in web.xml document. Then tries to find * SystemServiceServlet node and returns it. If not found, returns WebApp * node. The returned type is of type Element * * @return SystemServiceServlet node if found, else WebApp node. */ private Node findSystemServiceServlet(Document doc) { Node webAppNode; for (webAppNode = doc.getFirstChild(); webAppNode != null; webAppNode = webAppNode.getNextSibling()) { if (isElementAndNamed(webAppNode, WEB_APP)) { break; } } if (webAppNode == null) { getLog().info("Not a valid web.xml document"); return null; } Node systemServiceServletNode; for (systemServiceServletNode = webAppNode.getFirstChild(); systemServiceServletNode != null; systemServiceServletNode = systemServiceServletNode.getNextSibling()) { if (isElementAndNamed(systemServiceServletNode, SERVLET)) { for (Node n3 = systemServiceServletNode.getFirstChild(); n3 != null; n3 = n3.getNextSibling()) { if (isElementAndNamed(n3, SERVLET_NAME) && n3.getTextContent().equals(SYSTEM_SERVICE_SERVLET)) { return systemServiceServletNode; } } } } return webAppNode; } /** * Insert a SystemServiceServlet node in web.xml inside webApp node. * * @return The inserted SystemServiceServlet node. */ private Node insertSystemServiceServlet(Document doc, Node webAppNode, String spc, String delimiter) { Node n2, n3, n4, n5; n5 = doc.createTextNode(spc); webAppNode.appendChild(n5); n2 = doc.createElement(SERVLET); webAppNode.appendChild(n2); n5 = doc.createTextNode(delimiter + spc); webAppNode.appendChild(n5); n3 = doc.createElement(SERVLET_MAPPING); webAppNode.appendChild(n3); n5 = doc.createTextNode(delimiter); webAppNode.appendChild(n5); n5 = doc.createTextNode("\n" + spc + spc); n2.appendChild(n5); n5 = doc.createElement(SERVLET_NAME); n5.setTextContent(SYSTEM_SERVICE_SERVLET); n2.appendChild(n5); n5 = doc.createTextNode("\n" + spc + spc); n2.appendChild(n5); n5 = doc.createElement(SERVLET_CLASS); n5.setTextContent(SYSTEM_SERVICE_SERVLET_CLASS); n2.appendChild(n5); n5 = doc.createTextNode("\n" + spc + spc); n2.appendChild(n5); n4 = doc.createElement(INIT_PARAM); n2.appendChild(n4); n5 = doc.createTextNode("\n" + spc); n2.appendChild(n5); n5 = doc.createTextNode("\n" + spc + spc); n3.appendChild(n5); n5 = doc.createElement(SERVLET_NAME); n5.setTextContent(SYSTEM_SERVICE_SERVLET); n3.appendChild(n5); n5 = doc.createTextNode("\n" + spc + spc); n3.appendChild(n5); n5 = doc.createElement(URL_PATTERN); n5.setTextContent(SPI_URL_PATTERN); n3.appendChild(n5); n5 = doc.createTextNode("\n" + spc); n3.appendChild(n5); n5 = doc.createTextNode("\n" + spc + spc + spc); n4.appendChild(n5); n5 = doc.createElement(PARAM_NAME); n5.setTextContent(SERVICES); n4.appendChild(n5); n5 = doc.createTextNode("\n" + spc + spc + spc); n4.appendChild(n5); n5 = doc.createElement(PARAM_VALUE); n5.setTextContent(""); n4.appendChild(n5); n5 = doc.createTextNode("\n" + spc + spc); n4.appendChild(n5); return n2; } /** * Checks if a node is an XML element and checks if it has a specific name * * @param node * @param name * @return true if matching element, false if name doesn't match OR if node * type isn't ELEMENT */ private boolean isElementAndNamed(Node node, String name) { if (node == null || name == null) { throw new IllegalArgumentException(); } return (node.getNodeType() == Node.ELEMENT_NODE && node.getNodeName().equals(name)); } private void saveFile(Document doc, String filePath) throws TransformerFactoryConfigurationError, TransformerException, IOException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.transform(new DOMSource(doc), new StreamResult(new File(filePath))); } /** * Update the SystemServiceServlet parameter in web.xml, it doesn't make * changes if nothing new is to be added. If changes are required, it will * modify the file and save * * @param document * @param systemServiceServletNode * @param services * @return */ private boolean updateSystemServiceServletParam(Document doc, Node systemServiceServletNode, List<String> services) { Node initParamNode; for (initParamNode = systemServiceServletNode.getFirstChild(); initParamNode != null; initParamNode = initParamNode.getNextSibling()) { if (isElementAndNamed(initParamNode, INIT_PARAM)) { break; } } if (initParamNode == null) { getLog().info("Not a valid web.xml document"); return false; } Node paramValueNode; for (paramValueNode = initParamNode.getFirstChild(); paramValueNode != null; paramValueNode = paramValueNode.getNextSibling()) { if (isElementAndNamed(paramValueNode, PARAM_VALUE)) { break; } } if (paramValueNode == null) { getLog().info("Not a valid web.xml document"); return false; } // get all services the file currently lists, // put it in a treeset for sorted order, also removes duplicates String serviceXMLString = paramValueNode.getTextContent(); Set<String> servicesOnFile = new TreeSet<String>(); if (serviceXMLString != null && !serviceXMLString.trim().isEmpty()) { String[] servicesArray = serviceXMLString.split(","); for (String s : servicesArray) { servicesOnFile.add(s.trim()); } } // find all services we need to remove List<String> servicesToRemove = new ArrayList<String>(); for (String s : servicesOnFile) { if (!services.contains(s)) { servicesToRemove.add(s); } } // find all services we need to add List<String> servicesToAdd = new ArrayList<String>(); for (String s : services) { if (!servicesOnFile.contains(s)) { servicesToAdd.add(s); } } // if we don't need to make any changes, then return false if (servicesToAdd.isEmpty() && servicesToRemove.isEmpty()) { return false; } // remove those marked for removal for (String s : servicesToRemove) { servicesOnFile.remove(s); } // add those marked for adding for (String s : servicesToAdd) { servicesOnFile.add(s); } // write the appropriate data to the file if (servicesOnFile.isEmpty()) { paramValueNode.setTextContent(""); } else { Joiner joiner = Joiner.on(COMMA); paramValueNode.setTextContent(joiner.join(servicesOnFile)); } // indicate that a save is required return true; } public void updateWebXml(List<String> services, String webXmlPath) throws ParserConfigurationException, SAXException, IOException, TransformerFactoryConfigurationError, TransformerException { boolean saveRequired; String spc = " "; String delimiter = "\n"; DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document document = docBuilder.parse(webXmlPath); Node systemServiceServletNode = findSystemServiceServlet(document); if (systemServiceServletNode == null) { getLog().info("Not a valid web.xml document"); return; } if (isElementAndNamed(systemServiceServletNode, WEB_APP)) { systemServiceServletNode = insertSystemServiceServlet(document, systemServiceServletNode, spc, delimiter); saveRequired = true; } saveRequired = updateSystemServiceServletParam(document, systemServiceServletNode, services); String generatedWebInf = outputDirectory + "/WEB-INF"; new File(generatedWebInf).mkdirs(); saveFile(document, generatedWebInf + "/web.xml"); Files.copy( new File(new File(webXmlPath).getParentFile(), "appengine-web.xml"), new File(generatedWebInf, "appengine-web.xml")); } } }
package com.google.code.siren4j.converter; import com.google.common.base.Preconditions; import org.apache.commons.lang3.builder.ToStringBuilder; import java.lang.reflect.Field; import java.lang.reflect.Method; public class ReflectedInfo { private final Field field; private final Method getter; private final Method setter; private final String effectiveName; public ReflectedInfo(Field field, Method getter, Method setter, String effectiveName) { Preconditions.checkNotNull(field); this.field = field; this.getter = getter; this.setter = setter; this.effectiveName = effectiveName; } public Field getField() { return field; } public Method getGetter() { return getter; } public Method getSetter() { return setter; } public String getEffectiveName() { return effectiveName; } @Override public int hashCode() { return field.hashCode(); } @Override public boolean equals(Object obj) { return field.equals(obj); } @Override public String toString() { return new ToStringBuilder(this) .append(effectiveName) .toString(); } }
package io.scif.formats; import io.scif.AbstractChecker; import io.scif.AbstractFormat; import io.scif.AbstractMetadata; import io.scif.AbstractParser; import io.scif.ByteArrayPlane; import io.scif.ByteArrayReader; import io.scif.Format; import io.scif.FormatException; import io.scif.HasColorTable; import io.scif.ImageMetadata; import io.scif.MetadataLevel; import io.scif.UnsupportedCompressionException; import io.scif.codec.BitBuffer; import io.scif.io.RandomAccessInputStream; import io.scif.util.FormatTools; import io.scif.util.ImageTools; import java.io.IOException; import net.imglib2.display.ColorTable; import net.imglib2.display.ColorTable8; import net.imglib2.meta.Axes; import org.scijava.plugin.Plugin; @Plugin(type = Format.class) public class BMPFormat extends AbstractFormat { // -- Constants -- public static final String BMP_MAGIC_STRING = "BM"; // -- Compression types -- private static final int RAW = 0; private static final int RLE_8 = 1; private static final int RLE_4 = 2; private static final int RGB_MASK = 3; // -- Format API MEthods -- @Override public String getFormatName() { return "Windows Bitmap"; } @Override public String[] getSuffixes() { return new String[] { "bmp" }; } // -- Nested Classes -- /** * @author Mark Hiner */ public static class Metadata extends AbstractMetadata implements HasColorTable { // -- Fields -- /** The palette for indexed color images. */ private ColorTable8 palette; /** Compression type */ private int compression; /** Offset to image data. */ private long global; private boolean invertY = false; // -- Getters and Setters -- public int getCompression() { return compression; } public void setCompression(final int compression) { this.compression = compression; } public long getGlobal() { return global; } public void setGlobal(final long global) { this.global = global; } public boolean isInvertY() { return invertY; } public void setInvertY(final boolean invertY) { this.invertY = invertY; } // -- Metadata API Methods -- @Override public void populateImageMetadata() { log().info("Populating metadata"); int bpp = get(0).getBitsPerPixel(); final ImageMetadata iMeta = get(0); iMeta.setAxisTypes(Axes.X, Axes.Y); iMeta.setPlanarAxisCount(2); int sizeC = bpp != 24 ? 1 : 3; if (bpp == 32) sizeC = 4; if (bpp > 8) bpp /= sizeC; iMeta.setBitsPerPixel(bpp); switch (bpp) { case 16: iMeta.setPixelType(FormatTools.UINT16); break; case 32: iMeta.setPixelType(FormatTools.UINT32); break; default: iMeta.setPixelType(FormatTools.UINT8); } iMeta.setLittleEndian(true); iMeta.setMetadataComplete(true); iMeta.setIndexed(getColorTable(0, 0) != null); if (iMeta.isIndexed()) { sizeC = 1; } if (sizeC > 1 || iMeta.isIndexed()) { iMeta.addAxis(Axes.CHANNEL, sizeC); if (sizeC > 1) iMeta.setAxisTypes(Axes.CHANNEL, Axes.X, Axes.Y); iMeta.setPlanarAxisCount(3); } iMeta.setFalseColor(false); } // -- HasSource API Methods -- @Override public void close(final boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { compression = 0; global = 0; palette = null; invertY = false; } } // -- HasColorTable API Methods -- @Override public ColorTable getColorTable(final int imageIndex, final long planeIndex) { return palette; } } /** * @author Mark Hiner */ public static class Checker extends AbstractChecker { @Override public boolean isFormat(final RandomAccessInputStream stream) throws IOException { final int blockLen = 2; if (!FormatTools.validStream(stream, blockLen, false)) return false; return stream.readString(blockLen).startsWith(BMP_MAGIC_STRING); } } /** * @author Mark Hiner */ public static class Parser extends AbstractParser<Metadata> { @Override protected void typedParse(final RandomAccessInputStream stream, final Metadata meta) throws IOException, FormatException { meta.createImageMetadata(1); final ImageMetadata iMeta = meta.get(0); stream.order(true); // read the first header - 14 bytes addGlobalMeta("Magic identifier", in.readString(2)); addGlobalMeta("File size (in bytes)", in.readInt()); in.skipBytes(4); meta.setGlobal(in.readInt()); // read the second header - 40 bytes in.skipBytes(4); int sizeX = 0, sizeY = 0; // get the dimensions sizeX = in.readInt(); sizeY = in.readInt(); iMeta.addAxis(Axes.X, sizeX); iMeta.addAxis(Axes.Y, sizeY); if (sizeX < 1) { log().trace("Invalid width: " + sizeX + "; using the absolute value"); sizeX = Math.abs(sizeX); } if (sizeY < 1) { log().trace("Invalid height: " + sizeY + "; using the absolute value"); sizeY = Math.abs(sizeY); meta.setInvertY(true); } addGlobalMeta("Color planes", in.readShort()); final short bpp = in.readShort(); iMeta.setBitsPerPixel(bpp); meta.setCompression(in.readInt()); in.skipBytes(4); final int pixelSizeX = in.readInt(); final int pixelSizeY = in.readInt(); int nColors = in.readInt(); if (nColors == 0 && bpp != 32 && bpp != 24) { nColors = bpp < 8 ? 1 << bpp : 256; } in.skipBytes(4); // read the palette, if it exists if (nColors != 0 && bpp == 8) { final byte[][] palette = new byte[3][256]; for (int i = 0; i < nColors; i++) { for (int j = palette.length - 1; j >= 0; j palette[j][i] = in.readByte(); } in.skipBytes(1); } meta.palette = new ColorTable8(palette); } else if (nColors != 0) in.skipBytes(nColors * 4); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { addGlobalMeta("Indexed color", meta.getColorTable(0, 0) != null); addGlobalMeta("Image width", sizeX); addGlobalMeta("Image height", sizeY); addGlobalMeta("Bits per pixel", bpp); String comp = "invalid"; switch (meta.getCompression()) { case RAW: comp = "None"; break; case RLE_8: comp = "8 bit run length encoding"; break; case RLE_4: comp = "4 bit run length encoding"; break; case RGB_MASK: comp = "RGB bitmap with mask"; break; } addGlobalMeta("Compression type", comp); addGlobalMeta("X resolution", pixelSizeX); addGlobalMeta("Y resolution", pixelSizeY); } } } /** * @author Mark Hiner */ public static class Reader extends ByteArrayReader<Metadata> { // -- Constructor -- public Reader() { domains = new String[] { FormatTools.GRAPHICS_DOMAIN }; } // -- Reader API Methods -- @Override public ByteArrayPlane openPlane(final int imageIndex, final long planeIndex, final ByteArrayPlane plane, final long[] planeMin, final long[] planeMax) throws FormatException, IOException { final Metadata meta = getMetadata(); final int xIndex = meta.get(imageIndex).getAxisIndex(Axes.X); final int yIndex = meta.get(imageIndex).getAxisIndex(Axes.Y); final int x = (int) planeMin[xIndex], y = (int) planeMin[yIndex], w = (int) planeMax[xIndex], h = (int) planeMax[yIndex]; final byte[] buf = plane.getData(); final int compression = meta.getCompression(); final int bpp = meta.get(imageIndex).getBitsPerPixel(); final int sizeX = (int)meta.get(imageIndex).getAxisLength(Axes.X); final int sizeY = (int)meta.get(imageIndex).getAxisLength(Axes.Y); final int sizeC = (int)meta.get(imageIndex).getAxisLength(Axes.CHANNEL); FormatTools.checkPlaneForReading(meta, imageIndex, planeIndex, buf.length, planeMin, planeMax); if (compression != RAW && getStream().length() < FormatTools.getPlaneSize(this, imageIndex)) { throw new UnsupportedCompressionException(compression + " not supported"); } final int rowsToSkip = meta.isInvertY() ? y : sizeY - (h + y); final int rowLength = sizeX * (meta.get(imageIndex).isIndexed() ? 1 : sizeC); getStream().seek(meta.getGlobal() + rowsToSkip * rowLength); int pad = ((rowLength * bpp) / 8) % 2; if (pad == 0) pad = ((rowLength * bpp) / 8) % 4; else pad *= sizeC; int planeSize = sizeX * sizeC * h; if (bpp >= 8) planeSize *= (bpp / 8); else planeSize /= (8 / bpp); planeSize += pad * h; if (planeSize + getStream().getFilePointer() > getStream().length()) { planeSize -= (pad * h); // sometimes we have RGB images with a single padding byte if (planeSize + sizeY + getStream().getFilePointer() <= getStream() .length()) { pad = 1; planeSize += h; } else { pad = 0; } } getStream().skipBytes(rowsToSkip * pad); final byte[] rawPlane = new byte[planeSize]; getStream().read(rawPlane); final BitBuffer bb = new BitBuffer(rawPlane); final ColorTable palette = meta.getColorTable(0, 0); plane.setColorTable(palette); final int effectiveC = palette != null && palette.getLength() > 0 ? 1 : sizeC; for (int row = h - 1; row >= 0; row final int rowIndex = meta.isInvertY() ? h - 1 - row : row; bb.skipBits(x * bpp * effectiveC); for (int i = 0; i < w * effectiveC; i++) { if (bpp <= 8) { buf[rowIndex * w * effectiveC + i] = (byte) (bb.getBits(bpp) & 0xff); } else { for (int b = 0; b < bpp / 8; b++) { buf[(bpp / 8) * (rowIndex * w * effectiveC + i) + b] = (byte) (bb.getBits(8) & 0xff); } } } if (row > 0) { bb.skipBits((sizeX - w - x) * bpp * effectiveC + pad * 8); } } if (meta.get(imageIndex).getAxisLength(Axes.CHANNEL) > 1) { ImageTools.bgrToRgb(buf, meta.get(imageIndex).getInterleavedAxisCount() > 0, 1, (int) meta .get(imageIndex).getAxisLength(Axes.CHANNEL)); } return plane; } } }
package net.minecraftforge.common; public class ForgeVersion { //This number is incremented every Minecraft version, and never reset public static final int majorVersion = 4; //This number is incremented every official release, and reset every Minecraft version public static final int minorVersion = 3; //This number is incremented every time a interface changes or new major feature is added, and reset every Minecraft version public static final int revisionVersion = 5; //This number is incremented every time Jenkins builds Forge, and never reset. Should always be 0 in the repo code. public static final int buildVersion = 0; public static int getMajorVersion() { return majorVersion; } public static int getMinorVersion() { return minorVersion; } public static int getRevisionVersion() { return revisionVersion; } public static int getBuildVersion() { return buildVersion; } public static String getVersion() { return String.format("%d.%d.%d.%d", majorVersion, minorVersion, revisionVersion, buildVersion); } }
package com.hackovation.hybo.Controllers; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.hack17.hybo.domain.Allocation; import com.hack17.hybo.domain.IndexPrice; import com.hack17.hybo.domain.One; import com.hack17.hybo.domain.Portfolio; import com.hack17.hybo.domain.Two; import com.hack17.hybo.domain.UserClientMapping; import com.hack17.hybo.repository.PortfolioRepository; import com.hackovation.hybo.bean.ProfileResponse; import com.hackovation.hybo.rebalance.Rebalance; import com.hackovation.hybo.services.PortfolioService; @RestController @RequestMapping(value="/test") @CrossOrigin public class TestController { @Autowired PortfolioRepository portfolioRepository; @Autowired PortfolioService portfolioService; @Autowired Rebalance rebalance; SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); NumberFormat numFormat = new DecimalFormat(" SimpleDateFormat rebFor = new SimpleDateFormat("yyyy-MM"); @RequestMapping(value="/test", method=RequestMethod.GET) @Transactional public void test(){ One one= (One)portfolioRepository.getEntity(1, One.class); Set<Two> twoSet = new HashSet<>(); Two twoOne = new Two(); twoOne.setId(99); twoOne.setName("aman"); twoSet.add(twoOne); one.setSetOfTwo(twoSet); portfolioRepository.merge(one); } @RequestMapping(value="/rebalanceTest", method=RequestMethod.GET) public void testRebalance(){ rebalance.test(); } @RequestMapping(value="/showPortfolioProgress", method=RequestMethod.GET,produces = "application/json") public void showPortfolioProgress(@RequestParam(name="userId") String userId){ String str = "No Data To Display"; try{ int clientId = getClientId(userId); List<Portfolio> portfolioList = portfolioRepository.getPortfolio(clientId); Portfolio portfolio = portfolioList.get(0); Calendar systemDate = Calendar.getInstance(); Calendar cal = Calendar.getInstance(); Date date = portfolio.getTransactionDate(); cal.setTime(date); cal = trimTime(cal); double totalValue=0.0; while(true){ portfolioList = portfolioRepository.getPortfolioBeforeDate(Integer.valueOf(clientId),cal.getTime()); portfolio = portfolioList.get(0); List<Allocation> allocationList = portfolio.getAllocations(); totalValue = 0.0; String allocationStr = ""; for(Allocation allocation:allocationList){ if(allocation.getCostPrice()==0d || allocation.getIsActive().equals("N"))continue; double latestPrice = portfolioRepository.getIndexPriceForGivenDate(allocation.getFund().getTicker(), cal.getTime()); ProfileResponse response = new ProfileResponse(); // System.out.println("Old Value "+allocation.getFund().getTicker()+","+allocation.getCostPrice()); response.setClientId(Integer.valueOf(clientId)); response.setLabel(allocation.getFund().getTicker()+"("+(allocation.getType().substring(0,1))+")"); response.setValue(String.valueOf(latestPrice*allocation.getQuantity())); //System.out.println(" Data "+allocation.getFund().getTicker()+", Quantity: "+allocation.getQuantity()+ // ", old price : "+allocation.getCostPrice()+", Latest price: "+latestPrice+", Value: "+allocation.getQuantity()*latestPrice); totalValue += allocation.getQuantity()*latestPrice; allocationStr += allocation.getFund().getTicker()+","; } System.out.println("Total value of portfolio for user "+userId+" as of date "+cal.getTime()+" is: "+totalValue); System.out.println(" "+allocationStr); cal.add(Calendar.MONTH, 1); if(cal.getTime().after(systemDate.getTime()))break; } }catch(Exception e){ e.printStackTrace(); } } @Transactional private int getClientId(String userId){ Object object = portfolioRepository.getEntityForAny(UserClientMapping.class,userId); if(object==null){ Random random = new Random(); int clientId = random.nextInt(10000000); UserClientMapping newObject = new UserClientMapping(); newObject.setClientId(clientId); newObject.setUserId(userId); portfolioRepository.persist(newObject); return clientId; }else{ UserClientMapping existingObject = (UserClientMapping)object; return existingObject.getClientId(); } } private Calendar trimTime(Calendar cal){ cal.set(Calendar.HOUR_OF_DAY,0); cal.set(Calendar.MINUTE,0); cal.set(Calendar.SECOND,0); cal.set(Calendar.MILLISECOND,0); // cal.set(Calendar.ZONE_OFFSET,0); return cal; } @RequestMapping(value="/reverse", method=RequestMethod.GET) @Transactional public void reverseDate(){ List<IndexPrice> indexPriceList= portfolioRepository.getAllIndexPrice(); for(IndexPrice index:indexPriceList){ Calendar cal = Calendar.getInstance(); cal.setTime(index.getDate()); if(cal.get(Calendar.YEAR)==2014){ int day = cal.get(Calendar.DAY_OF_YEAR); cal.set(Calendar.DAY_OF_YEAR, 365-day); index.setDate(cal.getTime()); portfolioRepository.persist(index); } } } @RequestMapping(value="/reduce30", method=RequestMethod.GET) @Transactional public void reduce30Percent(){ List<IndexPrice> indexPriceList= portfolioRepository.getAllIndexPrice(); Map<String,Double> reducedPriceMap = new HashMap<>(); reducedPriceMap.put("CRSPLC1",988.91); reducedPriceMap.put("CRSPMI1",1000.18); reducedPriceMap.put("CRSPSC1",985.0); reducedPriceMap.put("CRSPTM1",982.01); reducedPriceMap.put("IEMG",34.33); reducedPriceMap.put("IVE",60.54); reducedPriceMap.put("IWN",70.29); reducedPriceMap.put("IWS",47.73); reducedPriceMap.put("LQD",81.98); reducedPriceMap.put("MUB",74.97); reducedPriceMap.put("SCHB",31.86); reducedPriceMap.put("SCHD",25.7); reducedPriceMap.put("SCHF",21.98); reducedPriceMap.put("SCHP",37.86); reducedPriceMap.put("SHV",77.19); reducedPriceMap.put("TFI",32.58); reducedPriceMap.put("VBR",69.92); reducedPriceMap.put("VCIT",59.42); reducedPriceMap.put("VDE",90.0); reducedPriceMap.put("VEA",28.82); reducedPriceMap.put("VIG",52.44); reducedPriceMap.put("VOE",57.55); reducedPriceMap.put("VTI",67.96); reducedPriceMap.put("VTIP",34.54); reducedPriceMap.put("VTV",54.38); reducedPriceMap.put("VWO",28.41); reducedPriceMap.put("XLE",62.48); for(IndexPrice index:indexPriceList){ Calendar cal = Calendar.getInstance(); cal.setTime(index.getDate()); if(cal.get(Calendar.YEAR)==2015 && cal.get(Calendar.MONTH)==Calendar.OCTOBER && cal.get(Calendar.DATE)==07){ index.setPrice(reducedPriceMap.get(index.getIndex())); portfolioRepository.persist(index); } } } @RequestMapping(value="/reset", method=RequestMethod.GET) @Transactional public void reset(){ List<IndexPrice> indexPriceList= portfolioRepository.getAllIndexPrice(); Map<String,Double> reducedPriceMap = new HashMap<>(); reducedPriceMap.put("CRSPLC1",1412.73); reducedPriceMap.put("CRSPMI1",1428.83); reducedPriceMap.put("CRSPSC1",1407.14); reducedPriceMap.put("CRSPTM1",1402.87); reducedPriceMap.put("IEMG",49.04); reducedPriceMap.put("IVE",86.48); reducedPriceMap.put("IWN",100.42); reducedPriceMap.put("IWS",68.19); reducedPriceMap.put("LQD",117.11); reducedPriceMap.put("MUB",107.1); reducedPriceMap.put("SCHB",45.52); reducedPriceMap.put("SCHD",36.71); reducedPriceMap.put("SCHF",31.4); reducedPriceMap.put("SCHP",54.08); reducedPriceMap.put("SHV",110.27); reducedPriceMap.put("TFI",46.54); reducedPriceMap.put("VBR",99.88); reducedPriceMap.put("VCIT",84.88); reducedPriceMap.put("VDE",128.57); reducedPriceMap.put("VEA",41.17); reducedPriceMap.put("VIG",74.92); reducedPriceMap.put("VOE",82.21); reducedPriceMap.put("VTI",97.09); reducedPriceMap.put("VTIP",49.34); reducedPriceMap.put("VTV",77.68); reducedPriceMap.put("VWO",40.58); reducedPriceMap.put("XLE",89.25); for(IndexPrice index:indexPriceList){ Calendar cal = Calendar.getInstance(); cal.setTime(index.getDate()); if(cal.get(Calendar.YEAR)==2015 && cal.get(Calendar.MONTH)==Calendar.OCTOBER && cal.get(Calendar.DATE)==07){ index.setPrice(reducedPriceMap.get(index.getIndex())); portfolioRepository.persist(index); } } } }
/* This file is automatically generated. Do not edit. */ package net.runelite.api; public final class NpcID { public static final int TOOL_LEPRECHAUN = 0; public static final int MOLANISK = 1; public static final int ABERRANT_SPECTRE = 2; public static final int ABERRANT_SPECTRE_3 = 3; public static final int ABERRANT_SPECTRE_4 = 4; public static final int ABERRANT_SPECTRE_5 = 5; public static final int ABERRANT_SPECTRE_6 = 6; public static final int ABERRANT_SPECTRE_7 = 7; public static final int NECHRYAEL = 8; public static final int TWIG = 9; public static final int DEATH_SPAWN = 10; public static final int NECHRYAEL_11 = 11; public static final int HUDO = 12; public static final int PILES = 13; public static final int ROMETTI = 14; public static final int GULLUCK = 15; public static final int HECKEL_FUNCH = 16; public static final int RUG_MERCHANT = 17; public static final int RUG_MERCHANT_18 = 18; public static final int RUG_MERCHANT_19 = 19; public static final int RUG_MERCHANT_20 = 20; public static final int RUG_MERCHANT_22 = 22; public static final int MONKEY = 23; public static final int ZOMBIE = 26; public static final int ZOMBIE_27 = 27; public static final int ZOMBIE_28 = 28; public static final int ZOMBIE_29 = 29; public static final int ZOMBIE_30 = 30; public static final int ZOMBIE_31 = 31; public static final int ZOMBIE_32 = 32; public static final int ZOMBIE_33 = 33; public static final int ZOMBIE_34 = 34; public static final int ZOMBIE_35 = 35; public static final int ZOMBIE_36 = 36; public static final int ZOMBIE_37 = 37; public static final int ZOMBIE_38 = 38; public static final int ZOMBIE_39 = 39; public static final int ZOMBIE_40 = 40; public static final int ZOMBIE_41 = 41; public static final int ZOMBIE_42 = 42; public static final int ZOMBIE_43 = 43; public static final int ZOMBIE_44 = 44; public static final int ZOMBIE_45 = 45; public static final int ZOMBIE_46 = 46; public static final int ZOMBIE_47 = 47; public static final int ZOMBIE_48 = 48; public static final int ZOMBIE_49 = 49; public static final int ZOMBIE_50 = 50; public static final int ZOMBIE_51 = 51; public static final int ZOMBIE_52 = 52; public static final int ZOMBIE_53 = 53; public static final int ZOMBIE_54 = 54; public static final int ZOMBIE_55 = 55; public static final int ZOMBIE_56 = 56; public static final int ZOMBIE_57 = 57; public static final int ZOMBIE_58 = 58; public static final int ZOMBIE_59 = 59; public static final int ZOMBIE_60 = 60; public static final int ZOMBIE_61 = 61; public static final int ZOMBIE_62 = 62; public static final int ZOMBIE_63 = 63; public static final int ZOMBIE_64 = 64; public static final int ZOMBIE_65 = 65; public static final int ZOMBIE_66 = 66; public static final int ZOMBIE_67 = 67; public static final int ZOMBIE_68 = 68; public static final int SUMMONED_ZOMBIE = 69; public static final int SKELETON = 70; public static final int SKELETON_71 = 71; public static final int SKELETON_72 = 72; public static final int SKELETON_73 = 73; public static final int SKELETON_74 = 74; public static final int SKELETON_75 = 75; public static final int SKELETON_76 = 76; public static final int SKELETON_77 = 77; public static final int SKELETON_78 = 78; public static final int SKELETON_79 = 79; public static final int SKELETON_80 = 80; public static final int SKELETON_81 = 81; public static final int SKELETON_82 = 82; public static final int SKELETON_83 = 83; public static final int SKELETON_MAGE = 84; public static final int GHOST = 85; public static final int GHOST_86 = 86; public static final int GHOST_87 = 87; public static final int GHOST_88 = 88; public static final int GHOST_89 = 89; public static final int GHOST_90 = 90; public static final int GHOST_91 = 91; public static final int GHOST_92 = 92; public static final int GHOST_93 = 93; public static final int GHOST_94 = 94; public static final int GHOST_95 = 95; public static final int GHOST_96 = 96; public static final int GHOST_97 = 97; public static final int GHOST_98 = 98; public static final int GHOST_99 = 99; public static final int ROCK_CRAB = 100; public static final int ROCKS = 101; public static final int ROCK_CRAB_102 = 102; public static final int ROCKS_103 = 103; public static final int HELLHOUND = 104; public static final int HELLHOUND_105 = 105; public static final int WOLF = 106; public static final int WHITE_WOLF = 107; public static final int WHITE_WOLF_108 = 108; public static final int BIG_WOLF = 109; public static final int WOLF_110 = 110; public static final int DOG = 111; public static final int WILD_DOG = 112; public static final int WILD_DOG_113 = 113; public static final int GUARD_DOG = 114; public static final int BIG_WOLF_115 = 115; public static final int WOLF_116 = 116; public static final int WOLF_117 = 117; public static final int IGNATIUS_VULCAN = 118; public static final int CRAWLING_HAND = 120; public static final int COCKATRICE = 121; public static final int BASILISK = 122; public static final int KURASK = 123; public static final int ABYSSAL_DEMON = 124; public static final int LEFT_HEAD = 125; public static final int MIDDLE_HEAD = 126; public static final int RIGHT_HEAD = 127; public static final int KALPHITE_QUEEN = 128; public static final int TENTACLE = 129; public static final int SKELETON_130 = 130; public static final int GUARD_DOG_131 = 131; public static final int HOBGOBLIN = 132; public static final int TROLL = 133; public static final int HUGE_SPIDER = 134; public static final int HELLHOUND_135 = 135; public static final int OGRE = 136; public static final int BABY_RED_DRAGON = 137; public static final int KALPHITE_SOLDIER = 138; public static final int STEEL_DRAGON = 139; public static final int DAGANNOTH = 140; public static final int TOKXIL = 141; public static final int DEMON = 142; public static final int ROCNAR = 143; public static final int HANGMAN_GAME = 144; public static final int HANGMAN_GAME_145 = 145; public static final int HANGMAN_GAME_146 = 146; public static final int HANGMAN_GAME_147 = 147; public static final int HANGMAN_GAME_148 = 148; public static final int HANGMAN_GAME_149 = 149; public static final int HANGMAN_GAME_150 = 150; public static final int HANGMAN_GAME_151 = 151; public static final int HANGMAN_GAME_152 = 152; public static final int HANGMAN_GAME_153 = 153; public static final int TREASURE_FAIRY = 154; public static final int JACKY_JESTER = 155; public static final int COMBAT_STONE = 156; public static final int COMBAT_STONE_157 = 157; public static final int COMBAT_STONE_158 = 158; public static final int COMBAT_STONE_159 = 159; public static final int COMBAT_STONE_160 = 160; public static final int COMBAT_STONE_161 = 161; public static final int COMBAT_STONE_162 = 162; public static final int COMBAT_STONE_163 = 163; public static final int COMBAT_STONE_164 = 164; public static final int COMBAT_STONE_165 = 165; public static final int COMBAT_STONE_166 = 166; public static final int COMBAT_STONE_167 = 167; public static final int COMBAT_STONE_168 = 168; public static final int COMBAT_STONE_169 = 169; public static final int COMBAT_STONE_170 = 170; public static final int COMBAT_STONE_171 = 171; public static final int COMBAT_STONE_172 = 172; public static final int COMBAT_STONE_173 = 173; public static final int COMBAT_STONE_174 = 174; public static final int COMBAT_STONE_175 = 175; public static final int COMBAT_STONE_176 = 176; public static final int COMBAT_STONE_177 = 177; public static final int COMBAT_STONE_178 = 178; public static final int COMBAT_STONE_179 = 179; public static final int COMBAT_STONE_180 = 180; public static final int COMBAT_STONE_181 = 181; public static final int COMBAT_STONE_182 = 182; public static final int COMBAT_STONE_183 = 183; public static final int COMBAT_STONE_184 = 184; public static final int COMBAT_STONE_185 = 185; public static final int COMBAT_STONE_186 = 186; public static final int COMBAT_STONE_187 = 187; public static final int COMBAT_STONE_188 = 188; public static final int COMBAT_STONE_189 = 189; public static final int COMBAT_STONE_190 = 190; public static final int COMBAT_STONE_191 = 191; public static final int COMBAT_STONE_192 = 192; public static final int COMBAT_STONE_193 = 193; public static final int COMBAT_STONE_194 = 194; public static final int COMBAT_STONE_195 = 195; public static final int COMBAT_STONE_196 = 196; public static final int COMBAT_STONE_197 = 197; public static final int COMBAT_STONE_198 = 198; public static final int COMBAT_STONE_199 = 199; public static final int COMBAT_STONE_200 = 200; public static final int COMBAT_STONE_201 = 201; public static final int COMBAT_STONE_202 = 202; public static final int COMBAT_STONE_203 = 203; public static final int COMBAT_STONE_204 = 204; public static final int COMBAT_STONE_205 = 205; public static final int COMBAT_STONE_206 = 206; public static final int COMBAT_STONE_207 = 207; public static final int COMBAT_STONE_208 = 208; public static final int COMBAT_STONE_209 = 209; public static final int COMBAT_STONE_210 = 210; public static final int COMBAT_STONE_211 = 211; public static final int COMBAT_STONE_212 = 212; public static final int COMBAT_STONE_213 = 213; public static final int COMBAT_STONE_214 = 214; public static final int COMBAT_STONE_215 = 215; public static final int COMBAT_STONE_216 = 216; public static final int COMBAT_STONE_217 = 217; public static final int COMBAT_STONE_218 = 218; public static final int COMBAT_STONE_219 = 219; public static final int COMBAT_STONE_220 = 220; public static final int RICK = 221; public static final int MAID = 223; public static final int COOK = 225; public static final int BUTLER = 227; public static final int DEMON_BUTLER = 229; public static final int WOLF_231 = 231; public static final int JUNGLE_WOLF = 232; public static final int MACARONI_PENGUIN = 233; public static final int BUTTERFLY = 234; public static final int BUTTERFLY_235 = 235; public static final int BUTTERFLY_236 = 236; public static final int BUTTERFLY_237 = 237; public static final int BUTTERFLY_238 = 238; public static final int KING_BLACK_DRAGON = 239; public static final int BLACK_DEMON = 240; public static final int BABY_BLUE_DRAGON = 241; public static final int BABY_BLUE_DRAGON_242 = 242; public static final int BABY_BLUE_DRAGON_243 = 243; public static final int BABY_RED_DRAGON_244 = 244; public static final int BABY_RED_DRAGON_245 = 245; public static final int BABY_RED_DRAGON_246 = 246; public static final int RED_DRAGON = 247; public static final int RED_DRAGON_248 = 248; public static final int RED_DRAGON_249 = 249; public static final int RED_DRAGON_250 = 250; public static final int RED_DRAGON_251 = 251; public static final int BLACK_DRAGON = 252; public static final int BLACK_DRAGON_253 = 253; public static final int BLACK_DRAGON_254 = 254; public static final int BLACK_DRAGON_255 = 255; public static final int BLACK_DRAGON_256 = 256; public static final int BLACK_DRAGON_257 = 257; public static final int BLACK_DRAGON_258 = 258; public static final int BLACK_DRAGON_259 = 259; public static final int GREEN_DRAGON = 260; public static final int GREEN_DRAGON_261 = 261; public static final int GREEN_DRAGON_262 = 262; public static final int GREEN_DRAGON_263 = 263; public static final int GREEN_DRAGON_264 = 264; public static final int BLUE_DRAGON = 265; public static final int BLUE_DRAGON_266 = 266; public static final int BLUE_DRAGON_267 = 267; public static final int BLUE_DRAGON_268 = 268; public static final int BLUE_DRAGON_269 = 269; public static final int BRONZE_DRAGON = 270; public static final int BRONZE_DRAGON_271 = 271; public static final int IRON_DRAGON = 272; public static final int IRON_DRAGON_273 = 273; public static final int STEEL_DRAGON_274 = 274; public static final int STEEL_DRAGON_275 = 275; public static final int TOWN_CRIER = 276; public static final int TOWN_CRIER_277 = 277; public static final int TOWN_CRIER_278 = 278; public static final int TOWN_CRIER_279 = 279; public static final int TOWN_CRIER_280 = 280; public static final int GULL = 281; public static final int CORMORANT = 282; public static final int PELICAN = 283; public static final int GULL_284 = 284; public static final int GULL_285 = 285; public static final int GULL_286 = 286; public static final int CORMORANT_287 = 287; public static final int PELICAN_288 = 288; public static final int GHOUL = 289; public static final int DWARF = 290; public static final int CHAOS_DWARF = 291; public static final int DWARF_292 = 292; public static final int ADVENTURER_JON = 293; public static final int DWARF_294 = 294; public static final int DWARF_295 = 295; public static final int DWARF_296 = 296; public static final int THORDUR = 297; public static final int THORDUR_298 = 298; public static final int GUNTHOR_THE_BRAVE = 299; public static final int JAILER = 300; public static final int BLACK_HEATHER = 301; public static final int DONNY_THE_LAD = 302; public static final int SPEEDY_KEITH = 303; public static final int SALARIN_THE_TWISTED = 304; public static final int JENNIFER = 305; public static final int LUMBRIDGE_GUIDE = 306; public static final int DR_JEKYLL = 307; public static final int EMBLEM_TRADER = 308; public static final int REACHER = 309; public static final int AYESHA = 310; public static final int IRON_MAN_TUTOR = 311; public static final int FROG = 312; public static final int REACHER_313 = 313; public static final int DR_JEKYLL_314 = 314; public static final int LEAGUES_TUTOR = 315; public static final int LEAGUES_TUTOR_316 = 316; public static final int DARK_CORE = 318; public static final int CORPOREAL_BEAST = 319; public static final int DARK_ENERGY_CORE = 320; public static final int MIME = 321; public static final int DRUNKEN_DWARF = 322; public static final int STRANGE_PLANT = 323; public static final int GENIE = 326; public static final int GENIE_327 = 327; public static final int REACHER_328 = 328; public static final int REACHER_329 = 329; public static final int SWARM = 330; public static final int REACHER_331 = 331; public static final int STRANGE_WATCHER = 332; public static final int STRANGE_WATCHER_333 = 333; public static final int STRANGE_WATCHER_334 = 334; public static final int REACHER_335 = 335; public static final int REACHER_336 = 336; public static final int SERGEANT_DAMIEN = 337; public static final int SUSPECT = 338; public static final int SUSPECT_339 = 339; public static final int SUSPECT_340 = 340; public static final int SUSPECT_341 = 341; public static final int MOLLY = 342; public static final int SUSPECT_343 = 343; public static final int SUSPECT_344 = 344; public static final int SUSPECT_345 = 345; public static final int SUSPECT_346 = 346; public static final int SUSPECT_347 = 347; public static final int SUSPECT_348 = 348; public static final int SUSPECT_349 = 349; public static final int SUSPECT_350 = 350; public static final int SUSPECT_351 = 351; public static final int MOLLY_352 = 352; public static final int SUSPECT_353 = 353; public static final int SUSPECT_354 = 354; public static final int SUSPECT_355 = 355; public static final int MOLLY_356 = 356; public static final int SUSPECT_357 = 357; public static final int SUSPECT_358 = 358; public static final int SUSPECT_359 = 359; public static final int SUSPECT_360 = 360; public static final int MOLLY_361 = 361; public static final int MOLLY_362 = 362; public static final int MOLLY_363 = 363; public static final int MOLLY_364 = 364; public static final int MOLLY_365 = 365; public static final int MOLLY_366 = 366; public static final int MOLLY_367 = 367; public static final int PRISON_PETE = 368; public static final int BALLOON_ANIMAL = 369; public static final int BALLOON_ANIMAL_370 = 370; public static final int BALLOON_ANIMAL_371 = 371; public static final int FREAKY_FORESTER = 372; public static final int PHEASANT = 373; public static final int PHEASANT_374 = 374; public static final int RICK_TURPENTINE = 375; public static final int RICK_TURPENTINE_376 = 376; public static final int PHOSANIS_NIGHTMARE = 377; public static final int THE_NIGHTMARE = 378; public static final int QUIZ_MASTER = 379; public static final int PILLORY_GUARD = 380; public static final int TRAMP = 381; public static final int TRAMP_382 = 382; public static final int TRAMP_383 = 383; public static final int MAN = 385; public static final int AVAN = 386; public static final int AVAN_387 = 387; public static final int DARK_CORE_388 = 388; public static final int REACHER_389 = 389; public static final int EVIL_BOB = 390; public static final int EVIL_BOB_391 = 391; public static final int SERVANT = 392; public static final int SERVANT_393 = 393; public static final int ROD_FISHING_SPOT = 394; public static final int CAT = 395; public static final int JON = 396; public static final int GUARD = 397; public static final int GUARD_398 = 398; public static final int GUARD_399 = 399; public static final int GUARD_400 = 400; public static final int TURAEL = 401; public static final int MAZCHNA = 402; public static final int VANNAKA = 403; public static final int CHAELDAR = 404; public static final int DURADEL = 405; public static final int CAVE_CRAWLER = 406; public static final int CAVE_CRAWLER_407 = 407; public static final int CAVE_CRAWLER_408 = 408; public static final int CAVE_CRAWLER_409 = 409; public static final int KURASK_410 = 410; public static final int KURASK_411 = 411; public static final int GARGOYLE = 412; public static final int GARGOYLE_413 = 413; public static final int BANSHEE = 414; public static final int ABYSSAL_DEMON_415 = 415; public static final int ABYSSAL_DEMON_416 = 416; public static final int BASILISK_417 = 417; public static final int BASILISK_418 = 418; public static final int COCKATRICE_419 = 419; public static final int COCKATRICE_420 = 420; public static final int ROCKSLUG = 421; public static final int ROCKSLUG_422 = 422; public static final int DUST_DEVIL = 423; public static final int SKOTOS = 425; public static final int TUROTH = 426; public static final int TUROTH_427 = 427; public static final int TUROTH_428 = 428; public static final int TUROTH_429 = 429; public static final int TUROTH_430 = 430; public static final int TUROTH_431 = 431; public static final int TUROTH_432 = 432; public static final int PYREFIEND = 433; public static final int PYREFIEND_434 = 434; public static final int PYREFIEND_435 = 435; public static final int PYREFIEND_436 = 436; public static final int JELLY = 437; public static final int JELLY_438 = 438; public static final int JELLY_439 = 439; public static final int JELLY_440 = 440; public static final int JELLY_441 = 441; public static final int JELLY_442 = 442; public static final int INFERNAL_MAGE = 443; public static final int INFERNAL_MAGE_444 = 444; public static final int INFERNAL_MAGE_445 = 445; public static final int INFERNAL_MAGE_446 = 446; public static final int INFERNAL_MAGE_447 = 447; public static final int CRAWLING_HAND_448 = 448; public static final int CRAWLING_HAND_449 = 449; public static final int CRAWLING_HAND_450 = 450; public static final int CRAWLING_HAND_451 = 451; public static final int CRAWLING_HAND_452 = 452; public static final int CRAWLING_HAND_453 = 453; public static final int CRAWLING_HAND_454 = 454; public static final int CRAWLING_HAND_455 = 455; public static final int CRAWLING_HAND_456 = 456; public static final int CRAWLING_HAND_457 = 457; public static final int LIZARD = 458; public static final int DESERT_LIZARD = 459; public static final int DESERT_LIZARD_460 = 460; public static final int DESERT_LIZARD_461 = 461; public static final int SMALL_LIZARD = 462; public static final int SMALL_LIZARD_463 = 463; public static final int HARPIE_BUG_SWARM = 464; public static final int SKELETAL_WYVERN = 465; public static final int SKELETAL_WYVERN_466 = 466; public static final int SKELETAL_WYVERN_467 = 467; public static final int SKELETAL_WYVERN_468 = 468; public static final int KILLERWATT = 469; public static final int KILLERWATT_470 = 470; public static final int GHOST_472 = 472; public static final int GHOST_473 = 473; public static final int GHOST_474 = 474; public static final int HOLE_IN_THE_WALL = 475; public static final int WALL_BEAST = 476; public static final int GIANT_FROG = 477; public static final int BIG_FROG = 478; public static final int FROG_479 = 479; public static final int CAVE_SLIME = 480; public static final int CAVE_BUG = 481; public static final int CAVE_BUG_LARVA = 482; public static final int CAVE_BUG_483 = 483; public static final int BLOODVELD = 484; public static final int BLOODVELD_485 = 485; public static final int BLOODVELD_486 = 486; public static final int BLOODVELD_487 = 487; public static final int STORM_CLOUD = 488; public static final int STORM_CLOUD_489 = 489; public static final int ENTOMOLOGIST = 491; public static final int CAVE_KRAKEN = 492; public static final int WHIRLPOOL = 493; public static final int KRAKEN = 494; public static final int VENENATIS_SPIDERLING = 495; public static final int WHIRLPOOL_496 = 496; public static final int CALLISTO_CUB = 497; public static final int SMOKE_DEVIL = 498; public static final int THERMONUCLEAR_SMOKE_DEVIL = 499; public static final int OLIVIA = 500; public static final int SARAH = 501; public static final int VANESSA = 502; public static final int RICHARD = 503; public static final int ALICE = 504; public static final int GHOST_505 = 505; public static final int GHOST_506 = 506; public static final int GHOST_507 = 507; public static final int SOULLESS = 508; public static final int DEATH_WING = 509; public static final int DARK_WIZARD = 510; public static final int INVRIGAR_THE_NECROMANCER = 511; public static final int DARK_WIZARD_512 = 512; public static final int MUGGER = 513; public static final int WITCH = 514; public static final int WITCH_515 = 515; public static final int BLACK_KNIGHT = 516; public static final int BLACK_KNIGHT_517 = 517; public static final int HIGHWAYMAN = 518; public static final int HIGHWAYMAN_519 = 519; public static final int CHAOS_DRUID = 520; public static final int PIRATE = 521; public static final int PIRATE_522 = 522; public static final int PIRATE_523 = 523; public static final int PIRATE_524 = 524; public static final int THUG = 525; public static final int ROGUE = 526; public static final int MONK_OF_ZAMORAK = 527; public static final int MONK_OF_ZAMORAK_528 = 528; public static final int MONK_OF_ZAMORAK_529 = 529; public static final int TRIBESMAN = 530; public static final int DARK_WARRIOR = 531; public static final int CHAOS_DRUID_WARRIOR = 532; public static final int FUNGI = 533; public static final int FUNGI_535 = 535; public static final int ZYGOMITE = 537; public static final int FUNGI_538 = 538; public static final int ELFINLOCKS = 539; public static final int CLOCKWORK_CAT = 540; public static final int CLOCKWORK_CAT_541 = 541; public static final int MONK = 542; public static final int MONK_543 = 543; public static final int MONK_544 = 544; public static final int MONK_545 = 545; public static final int RUFUS = 546; public static final int MIGOR = 547; public static final int PUFFIN = 548; public static final int PUFFIN_549 = 549; public static final int BROTHER_TRANQUILITY = 550; public static final int BROTHER_TRANQUILITY_551 = 551; public static final int BROTHER_TRANQUILITY_552 = 552; public static final int MONK_553 = 553; public static final int MONK_554 = 554; public static final int MONK_555 = 555; public static final int MONK_556 = 556; public static final int ZOMBIE_MONK = 557; public static final int ZOMBIE_MONK_558 = 558; public static final int ZOMBIE_MONK_559 = 559; public static final int ZOMBIE_MONK_560 = 560; public static final int SOREBONES = 561; public static final int SOREBONES_562 = 562; public static final int ZOMBIE_PIRATE = 563; public static final int ZOMBIE_PIRATE_564 = 564; public static final int ZOMBIE_PIRATE_565 = 565; public static final int ZOMBIE_PIRATE_566 = 566; public static final int ZOMBIE_PIRATE_567 = 567; public static final int ZOMBIE_PIRATE_568 = 568; public static final int ZOMBIE_PIRATE_569 = 569; public static final int ZOMBIE_PIRATE_570 = 570; public static final int ZOMBIE_PIRATE_571 = 571; public static final int ZOMBIE_PIRATE_572 = 572; public static final int ZOMBIE_PIRATE_573 = 573; public static final int ZOMBIE_PIRATE_574 = 574; public static final int ZOMBIE_PIRATE_575 = 575; public static final int ZOMBIE_PIRATE_576 = 576; public static final int ZOMBIE_PIRATE_577 = 577; public static final int ZOMBIE_PIRATE_578 = 578; public static final int ZOMBIE_PIRATE_579 = 579; public static final int ZOMBIE_PIRATE_580 = 580; public static final int ZOMBIE_PIRATE_581 = 581; public static final int ZOMBIE_PIRATE_582 = 582; public static final int ZOMBIE_PIRATE_583 = 583; public static final int ZOMBIE_PIRATE_584 = 584; public static final int ZOMBIE_PIRATE_585 = 585; public static final int ZOMBIE_PIRATE_586 = 586; public static final int ZOMBIE_PIRATE_587 = 587; public static final int ZOMBIE_PIRATE_588 = 588; public static final int ZOMBIE_PIRATE_589 = 589; public static final int ZOMBIE_PIRATE_590 = 590; public static final int ZOMBIE_PIRATE_591 = 591; public static final int ZOMBIE_PIRATE_592 = 592; public static final int ZOMBIE_PIRATE_593 = 593; public static final int ZOMBIE_PIRATE_594 = 594; public static final int ZOMBIE_PIRATE_595 = 595; public static final int ZOMBIE_PIRATE_596 = 596; public static final int ZOMBIE_PIRATE_597 = 597; public static final int ZOMBIE_PIRATE_598 = 598; public static final int ZOMBIE_PIRATE_599 = 599; public static final int BARRELCHEST = 600; public static final int PIRATE_PETE = 601; public static final int PIRATE_PETE_602 = 602; public static final int CAPTAIN_BRAINDEATH = 603; public static final int _50_LUKE = 604; public static final int DAVEY = 605; public static final int CAPTAIN_DONNIE = 606; public static final int ZOMBIE_PROTESTER = 607; public static final int ZOMBIE_PROTESTER_608 = 608; public static final int ZOMBIE_PROTESTER_609 = 609; public static final int ZOMBIE_PROTESTER_610 = 610; public static final int ZOMBIE_PROTESTER_611 = 611; public static final int ZOMBIE_PROTESTER_612 = 612; public static final int ZOMBIE_PIRATE_613 = 613; public static final int ZOMBIE_PIRATE_614 = 614; public static final int ZOMBIE_PIRATE_615 = 615; public static final int ZOMBIE_PIRATE_616 = 616; public static final int ZOMBIE_PIRATE_617 = 617; public static final int ZOMBIE_PIRATE_618 = 618; public static final int ZOMBIE_SWAB = 619; public static final int ZOMBIE_SWAB_620 = 620; public static final int ZOMBIE_SWAB_621 = 621; public static final int ZOMBIE_SWAB_622 = 622; public static final int ZOMBIE_SWAB_623 = 623; public static final int ZOMBIE_SWAB_624 = 624; public static final int EVIL_SPIRIT = 625; public static final int FEVER_SPIDER = 626; public static final int BREWER = 627; public static final int BREWER_628 = 628; public static final int BREWER_629 = 629; public static final int BREWER_630 = 630; public static final int BREWER_631 = 631; public static final int BREWER_632 = 632; public static final int BREWER_633 = 633; public static final int BREWER_634 = 634; public static final int FISHING_SPOT = 635; public static final int KARAMTHULHU = 636; public static final int FUNGI_637 = 637; public static final int TYRAS_GUARD = 639; public static final int UG = 640; public static final int AGA = 641; public static final int ARRG = 642; public static final int ARRG_643 = 643; public static final int UG_644 = 644; public static final int ICE_WOLF = 645; public static final int ICE_WOLF_646 = 646; public static final int ICE_WOLF_647 = 647; public static final int ICE_TROLL = 648; public static final int ICE_TROLL_649 = 649; public static final int ICE_TROLL_650 = 650; public static final int ICE_TROLL_651 = 651; public static final int ICE_TROLL_652 = 652; public static final int ICE_TROLL_653 = 653; public static final int ICE_TROLL_654 = 654; public static final int GOBLIN = 655; public static final int GOBLIN_656 = 656; public static final int GOBLIN_657 = 657; public static final int GOBLIN_658 = 658; public static final int GOBLIN_659 = 659; public static final int GOBLIN_660 = 660; public static final int GOBLIN_661 = 661; public static final int GOBLIN_662 = 662; public static final int GOBLIN_663 = 663; public static final int GOBLIN_664 = 664; public static final int GOBLIN_665 = 665; public static final int GOBLIN_666 = 666; public static final int GOBLIN_667 = 667; public static final int GOBLIN_668 = 668; public static final int GENERAL_BENTNOZE = 669; public static final int GENERAL_WARTFACE = 670; public static final int GRUBFOOT = 671; public static final int GRUBFOOT_672 = 672; public static final int GRUBFOOT_673 = 673; public static final int GOBLIN_674 = 674; public static final int GENERAL_BENTNOZE_675 = 675; public static final int GENERAL_WARTFACE_676 = 676; public static final int GOBLIN_677 = 677; public static final int GOBLIN_678 = 678; public static final int RASOLO = 679; public static final int GIANT_SKELETON = 680; public static final int GIANT_SKELETON_681 = 681; public static final int DAMIS = 682; public static final int DAMIS_683 = 683; public static final int ARCHAEOLOGIST = 684; public static final int STRANGER = 685; public static final int MALAK = 686; public static final int BARTENDER = 687; public static final int EBLIS = 688; public static final int EBLIS_689 = 689; public static final int BANDIT = 690; public static final int BANDIT_691 = 691; public static final int BANDIT_692 = 692; public static final int BANDIT_693 = 693; public static final int BANDIT_694 = 694; public static final int BANDIT_695 = 695; public static final int TROLL_CHILD = 696; public static final int TROLL_CHILD_697 = 697; public static final int ICE_TROLL_698 = 698; public static final int ICE_TROLL_699 = 699; public static final int ICE_TROLL_700 = 700; public static final int ICE_TROLL_701 = 701; public static final int ICE_TROLL_702 = 702; public static final int ICE_TROLL_703 = 703; public static final int ICE_TROLL_704 = 704; public static final int ICE_TROLL_705 = 705; public static final int ICE_BLOCK = 706; public static final int ICE_BLOCK_707 = 707; public static final int TROLL_FATHER = 708; public static final int TROLL_MOTHER = 709; public static final int ICE_WOLF_710 = 710; public static final int ICE_WOLF_711 = 711; public static final int ICE_WOLF_712 = 712; public static final int ICE_WOLF_713 = 713; public static final int ICE_WOLF_714 = 714; public static final int ICE_WOLF_715 = 715; public static final int MUMMY = 717; public static final int MUMMY_ASHES = 718; public static final int MUMMY_ASHES_719 = 719; public static final int MUMMY_720 = 720; public static final int MUMMY_721 = 721; public static final int MUMMY_722 = 722; public static final int MUMMY_723 = 723; public static final int MUMMY_724 = 724; public static final int MUMMY_725 = 725; public static final int MUMMY_726 = 726; public static final int MUMMY_727 = 727; public static final int MUMMY_728 = 728; public static final int SCARABS = 729; public static final int AZZANADRA = 730; public static final int SHEEP = 731; public static final int FRED_THE_FARMER = 732; public static final int BANDIT_LEADER = 733; public static final int BANDIT_734 = 734; public static final int BANDIT_735 = 735; public static final int BANDIT_736 = 736; public static final int BANDIT_737 = 737; public static final int BANDIT_CHAMPION = 738; public static final int COWARDLY_BANDIT = 739; public static final int MY_ARM = 741; public static final int MY_ARM_742 = 742; public static final int MY_ARM_750 = 750; public static final int MY_ARM_751 = 751; public static final int MY_ARM_752 = 752; public static final int ADVENTURER = 753; public static final int CAPTAIN_BARNABY = 754; public static final int MURCAILY = 755; public static final int JAGBAKOBA = 756; public static final int TOOL_LEPRECHAUN_757 = 757; public static final int FLIES = 758; public static final int UNNAMED_TROLL_CHILD = 759; public static final int DRUNKEN_DWARFS_LEG = 760; public static final int BABY_ROC = 762; public static final int GIANT_ROC = 763; public static final int SHADOW = 764; public static final int QUEEN_SIGRID = 765; public static final int BANKER = 766; public static final int ARNOR = 767; public static final int HAMING = 768; public static final int MOLDOF = 769; public static final int HELGA = 770; public static final int MATILDA = 771; public static final int ASHILD = 772; public static final int SKRAELING = 773; public static final int SKRAELING_774 = 774; public static final int FISHMONGER = 775; public static final int GREENGROCER = 776; public static final int ETHEREAL_MAN = 777; public static final int ETHEREAL_LADY = 778; public static final int ETHEREAL_NUMERATOR = 779; public static final int ETHEREAL_EXPERT = 780; public static final int ETHEREAL_PERCEPTIVE = 781; public static final int ETHEREAL_GUIDE = 782; public static final int ETHEREAL_FLUKE = 783; public static final int ETHEREAL_MIMIC = 784; public static final int ME = 785; public static final int ME_786 = 786; public static final int SUQAH = 787; public static final int SUQAH_788 = 788; public static final int SUQAH_789 = 789; public static final int SUQAH_790 = 790; public static final int SUQAH_791 = 791; public static final int SUQAH_792 = 792; public static final int SUQAH_793 = 793; public static final int SCARAB_MAGE = 794; public static final int LOCUST_RIDER = 795; public static final int LOCUST_RIDER_796 = 796; public static final int GIANT_SCARAB = 797; public static final int GIANT_SCARAB_798 = 798; public static final int SCARAB_MAGE_799 = 799; public static final int LOCUST_RIDER_800 = 800; public static final int LOCUST_RIDER_801 = 801; public static final int OLAF_THE_BARD = 802; public static final int LALLI = 803; public static final int GOLDEN_SHEEP = 804; public static final int GOLDEN_SHEEP_805 = 805; public static final int GOLDEN_SHEEP_806 = 806; public static final int GOLDEN_SHEEP_807 = 807; public static final int FOSSEGRIMEN = 808; public static final int OSPAK = 809; public static final int STYRMIR = 810; public static final int TORBRUND = 811; public static final int FRIDGEIR = 812; public static final int LONGHALL_BOUNCER = 813; public static final int GUILDMASTER = 814; public static final int DUKE_HORACIO = 815; public static final int ELVARG = 817; public static final int KLARENSE = 819; public static final int WORMBRAIN = 820; public static final int ORACLE = 821; public static final int OZIACH = 822; public static final int MELZAR_THE_MAD = 823; public static final int CAPTAIN_NED = 824; public static final int CABIN_BOY_JENKINS = 825; public static final int CABIN_BOY_JENKINS_826 = 826; public static final int LARRY = 827; public static final int LARRY_828 = 828; public static final int LARRY_829 = 829; public static final int PENGUIN = 830; public static final int PENGUIN_831 = 831; public static final int PENGUIN_832 = 832; public static final int KGP_GUARD = 833; public static final int PESCALING_PAX = 834; public static final int PING = 835; public static final int PING_836 = 836; public static final int PONG = 837; public static final int PONG_838 = 838; public static final int PING_839 = 839; public static final int PONG_840 = 840; public static final int KGP_AGENT = 841; public static final int KGP_AGENT_842 = 842; public static final int NOODLE = 844; public static final int PENGUIN_845 = 845; public static final int PENGUIN_SUIT = 846; public static final int AGILITY_INSTRUCTOR = 847; public static final int ARMY_COMMANDER = 848; public static final int PENGUIN_849 = 849; public static final int PENGUIN_850 = 850; public static final int PENGUIN_851 = 851; public static final int ICELORD = 852; public static final int ICELORD_853 = 853; public static final int ICELORD_854 = 854; public static final int ICELORD_855 = 855; public static final int CRUSHER = 856; public static final int CRUSHER_857 = 857; public static final int CRUSHER_858 = 858; public static final int CRUSHER_859 = 859; public static final int GRISH = 860; public static final int UGLUG_NAR = 861; public static final int PILG = 862; public static final int GRUG = 863; public static final int OGRE_GUARD = 864; public static final int OGRE_GUARD_865 = 865; public static final int ZOGRE = 866; public static final int ZOGRE_867 = 867; public static final int ZOGRE_868 = 868; public static final int ZOGRE_869 = 869; public static final int ZOGRE_870 = 870; public static final int ZOGRE_871 = 871; public static final int SKOGRE = 872; public static final int ZOGRE_873 = 873; public static final int ZOGRE_874 = 874; public static final int ZOGRE_875 = 875; public static final int ZOGRE_876 = 876; public static final int ZOGRE_877 = 877; public static final int SKOGRE_878 = 878; public static final int SKOGRE_879 = 879; public static final int ZOMBIE_880 = 880; public static final int ZAVISTIC_RARVE = 881; public static final int SLASH_BASH = 882; public static final int SITHIK_INTS = 883; public static final int SITHIK_INTS_884 = 884; public static final int GARGH = 885; public static final int SCARG = 886; public static final int GRUH = 887; public static final int IRWIN_FEASELBAUM = 888; public static final int MOSS_GUARDIAN = 891; public static final int GOLRIE = 892; public static final int FATHER_REEN = 893; public static final int FATHER_REEN_894 = 894; public static final int FATHER_BADDEN = 895; public static final int FATHER_BADDEN_896 = 896; public static final int DENATH = 897; public static final int DENATH_898 = 898; public static final int ERIC = 899; public static final int ERIC_900 = 900; public static final int EVIL_DAVE = 901; public static final int EVIL_DAVE_902 = 902; public static final int MATTHEW = 903; public static final int MATTHEW_904 = 904; public static final int JENNIFER_905 = 905; public static final int JENNIFER_906 = 906; public static final int TANYA = 907; public static final int TANYA_908 = 908; public static final int PATRICK = 909; public static final int PATRICK_910 = 910; public static final int AGRITH_NAAR = 911; public static final int SAND_STORM = 912; public static final int CLAY_GOLEM = 917; public static final int CLAY_GOLEM_918 = 918; public static final int GHOST_920 = 920; public static final int DONIE = 921; public static final int RESTLESS_GHOST = 922; public static final int FATHER_URHNEY = 923; public static final int SKELETON_924 = 924; public static final int ROCK = 925; public static final int STICK = 926; public static final int PEE_HAT = 927; public static final int KRAKA = 928; public static final int DUNG = 929; public static final int ASH = 930; public static final int THROWER_TROLL = 931; public static final int THROWER_TROLL_932 = 932; public static final int THROWER_TROLL_933 = 933; public static final int THROWER_TROLL_934 = 934; public static final int THROWER_TROLL_935 = 935; public static final int MOUNTAIN_TROLL = 936; public static final int MOUNTAIN_TROLL_937 = 937; public static final int MOUNTAIN_TROLL_938 = 938; public static final int MOUNTAIN_TROLL_939 = 939; public static final int MOUNTAIN_TROLL_940 = 940; public static final int MOUNTAIN_TROLL_941 = 941; public static final int MOUNTAIN_TROLL_942 = 942; public static final int FILLIMAN_TARLOCK = 943; public static final int NATURE_SPIRIT = 944; public static final int GHAST = 945; public static final int GHAST_946 = 946; public static final int ULIZIUS = 947; public static final int KLENTER = 948; public static final int MUMMY_949 = 949; public static final int MUMMY_950 = 950; public static final int MUMMY_951 = 951; public static final int MUMMY_952 = 952; public static final int MUMMY_953 = 953; public static final int WEIRD_OLD_MAN = 954; public static final int KALPHITE_WORKER = 955; public static final int KALPHITE_WORKER_956 = 956; public static final int KALPHITE_SOLDIER_957 = 957; public static final int KALPHITE_SOLDIER_958 = 958; public static final int KALPHITE_GUARDIAN = 959; public static final int KALPHITE_GUARDIAN_960 = 960; public static final int KALPHITE_WORKER_961 = 961; public static final int KALPHITE_GUARDIAN_962 = 962; public static final int KALPHITE_QUEEN_963 = 963; public static final int HELLPUPPY = 964; public static final int KALPHITE_QUEEN_965 = 965; public static final int KALPHITE_LARVA = 966; public static final int ANNA = 967; public static final int DAVID = 968; public static final int ANNA_969 = 969; public static final int DAGANNOTH_970 = 970; public static final int DAGANNOTH_971 = 971; public static final int DAGANNOTH_972 = 972; public static final int DAGANNOTH_973 = 973; public static final int DAGANNOTH_974 = 974; public static final int DAGANNOTH_975 = 975; public static final int DAGANNOTH_976 = 976; public static final int DAGANNOTH_977 = 977; public static final int DAGANNOTH_978 = 978; public static final int DAGANNOTH_979 = 979; public static final int DAGANNOTH_MOTHER = 980; public static final int DAGANNOTH_MOTHER_981 = 981; public static final int DAGANNOTH_MOTHER_982 = 982; public static final int DAGANNOTH_MOTHER_983 = 983; public static final int DAGANNOTH_MOTHER_984 = 984; public static final int DAGANNOTH_MOTHER_985 = 985; public static final int DAGANNOTH_MOTHER_986 = 986; public static final int DAGANNOTH_MOTHER_987 = 987; public static final int DAGANNOTH_MOTHER_988 = 988; public static final int VELIAF_HURTZ = 989; public static final int SIGMUND = 990; public static final int SIGMUND_991 = 991; public static final int SIGMUND_992 = 992; public static final int SIGMUND_993 = 993; public static final int SIGMUND_994 = 994; public static final int GUARD_995 = 995; public static final int NARDOK = 996; public static final int DARTOG = 997; public static final int GUARD_998 = 998; public static final int GUARD_999 = 999; public static final int GUARD_1000 = 1000; public static final int GUARD_1001 = 1001; public static final int GUARD_1002 = 1002; public static final int GUARD_1003 = 1003; public static final int GUARD_1004 = 1004; public static final int GUARD_1005 = 1005; public static final int GUARD_1006 = 1006; public static final int GUARD_1007 = 1007; public static final int GUARD_1008 = 1008; public static final int GUARD_1009 = 1009; public static final int GERTRUDES_CAT = 1010; public static final int GAMER = 1011; public static final int GAMER_1012 = 1012; public static final int BARMAN = 1013; public static final int GAMER_1014 = 1014; public static final int GAMER_1015 = 1015; public static final int GAMER_1016 = 1016; public static final int GAMER_1017 = 1017; public static final int GAMER_1018 = 1018; public static final int GAMER_1019 = 1019; public static final int RAT = 1020; public static final int RAT_1021 = 1021; public static final int RAT_1022 = 1022; public static final int ZYGOMITE_1024 = 1024; public static final int NECROMANCER = 1025; public static final int BANDIT_1026 = 1026; public static final int GUARD_BANDIT = 1027; public static final int BARBARIAN_GUARD = 1028; public static final int SLEEPWALKER = 1029; public static final int SLEEPWALKER_1030 = 1030; public static final int SLEEPWALKER_1031 = 1031; public static final int SLEEPWALKER_1032 = 1032; public static final int SNAKE = 1037; public static final int MONKEY_1038 = 1038; public static final int ALBINO_BAT = 1039; public static final int CRAB = 1040; public static final int GIANT_MOSQUITO = 1041; public static final int JUNGLE_HORROR = 1042; public static final int JUNGLE_HORROR_1043 = 1043; public static final int JUNGLE_HORROR_1044 = 1044; public static final int JUNGLE_HORROR_1045 = 1045; public static final int JUNGLE_HORROR_1046 = 1046; public static final int CAVE_HORROR = 1047; public static final int CAVE_HORROR_1048 = 1048; public static final int CAVE_HORROR_1049 = 1049; public static final int CAVE_HORROR_1050 = 1050; public static final int CAVE_HORROR_1051 = 1051; public static final int CAVEY_DAVEY = 1052; public static final int PATCHY = 1053; public static final int LAUNA = 1054; public static final int LAUNA_1055 = 1055; public static final int BRANA = 1056; public static final int TOLNA = 1057; public static final int TOLNA_1058 = 1058; public static final int TOLNA_1059 = 1059; public static final int ANGRY_BEAR = 1060; public static final int ANGRY_UNICORN = 1061; public static final int ANGRY_GIANT_RAT = 1062; public static final int ANGRY_GOBLIN = 1065; public static final int FEAR_REAPER = 1066; public static final int CONFUSION_BEAST = 1067; public static final int CONFUSION_BEAST_1068 = 1068; public static final int CONFUSION_BEAST_1069 = 1069; public static final int CONFUSION_BEAST_1070 = 1070; public static final int CONFUSION_BEAST_1071 = 1071; public static final int HOPELESS_CREATURE = 1072; public static final int HOPELESS_CREATURE_1073 = 1073; public static final int HOPELESS_CREATURE_1074 = 1074; public static final int TOLNA_1075 = 1075; public static final int TOLNA_1076 = 1076; public static final int TOLNA_1077 = 1077; public static final int RUNA = 1078; public static final int HALLA = 1079; public static final int FINN = 1080; public static final int OSVALD = 1081; public static final int RUNOLF = 1082; public static final int TJORVI = 1083; public static final int INGRID = 1084; public static final int THORA = 1085; public static final int SIGNY = 1086; public static final int HILD = 1087; public static final int ARMOD = 1088; public static final int BEIGARTH = 1089; public static final int REINN = 1090; public static final int ALVISS = 1091; public static final int FULLANGR = 1092; public static final int JARI = 1093; public static final int THORODIN = 1094; public static final int FERD = 1095; public static final int DONAL = 1096; public static final int SEA_SNAKE_YOUNG = 1097; public static final int SEA_SNAKE_HATCHLING = 1098; public static final int GUARD_1099 = 1099; public static final int GUARD_1100 = 1100; public static final int GIANT_SEA_SNAKE = 1101; public static final int ELENA = 1102; public static final int DA_VINCI = 1103; public static final int DA_VINCI_1104 = 1104; public static final int CHANCY = 1105; public static final int CHANCY_1106 = 1106; public static final int HOPS = 1107; public static final int HOPS_1108 = 1108; public static final int JULIE = 1109; public static final int GUIDOR = 1110; public static final int GUARD_1111 = 1111; public static final int GUARD_1112 = 1112; public static final int GUARD_1113 = 1113; public static final int MAN_1118 = 1118; public static final int WOMAN = 1119; public static final int DOMINIC_ONION = 1120; public static final int BARRELCHEST_HARD = 1126; public static final int GIANT_SCARAB_HARD = 1127; public static final int DESSOUS_HARD = 1128; public static final int KAMIL_HARD = 1129; public static final int WOMAN_1130 = 1130; public static final int WOMAN_1131 = 1131; public static final int CHILD = 1132; public static final int CHILD_1133 = 1133; public static final int DAMIS_HARD = 1134; public static final int DAMIS_HARD_1135 = 1135; public static final int PRIEST = 1137; public static final int MAN_1138 = 1138; public static final int WOMAN_1139 = 1139; public static final int WOMAN_1140 = 1140; public static final int WOMAN_1141 = 1141; public static final int WOMAN_1142 = 1142; public static final int PALADIN = 1144; public static final int JERICO = 1145; public static final int CHEMIST = 1146; public static final int GUARD_1147 = 1147; public static final int NURSE_SARAH = 1152; public static final int OGRE_1153 = 1153; public static final int SHARK = 1154; public static final int SHARK_1155 = 1155; public static final int SHARK_1156 = 1156; public static final int ARCHER = 1157; public static final int WARRIOR = 1158; public static final int MONK_1159 = 1159; public static final int WIZARD = 1160; public static final int FAIRY_QUEEN = 1161; public static final int SHAMUS = 1162; public static final int TREE_SPIRIT = 1163; public static final int CAVE_MONK = 1164; public static final int MONK_OF_ENTRANA = 1165; public static final int MONK_OF_ENTRANA_1166 = 1166; public static final int MONK_OF_ENTRANA_1167 = 1167; public static final int MONK_OF_ENTRANA_1168 = 1168; public static final int MONK_OF_ENTRANA_1169 = 1169; public static final int MONK_OF_ENTRANA_1170 = 1170; public static final int MONK_1171 = 1171; public static final int CHICKEN = 1173; public static final int CHICKEN_1174 = 1174; public static final int ROOSTER = 1175; public static final int LIL_LAMB = 1176; public static final int LAMB = 1177; public static final int SHEEP_1178 = 1178; public static final int LUMBRIDGE_GUIDE_1179 = 1179; public static final int LUMBRIDGE_GUIDE_1181 = 1181; public static final int ___ = 1182; public static final int ____1183 = 1183; public static final int ____1184 = 1184; public static final int ____1185 = 1185; public static final int ____1186 = 1186; public static final int ____1187 = 1187; public static final int ____1188 = 1188; public static final int ____1189 = 1189; public static final int ____1190 = 1190; public static final int ____1191 = 1191; public static final int GENERAL_WARTFACE_1192 = 1192; public static final int GENERAL_BENTNOZE_1193 = 1193; public static final int GENERAL_WARTFACE_1195 = 1195; public static final int GENERAL_BENTNOZE_1197 = 1197; public static final int CERIL_CARNILLEAN = 1198; public static final int CLAUS_THE_CHEF = 1199; public static final int GUARD_1200 = 1200; public static final int PHILIPE_CARNILLEAN = 1201; public static final int HENRYETA_CARNILLEAN = 1202; public static final int BUTLER_JONES = 1203; public static final int ALOMONE = 1204; public static final int HAZEEL = 1205; public static final int CLIVET = 1206; public static final int HAZEEL_CULTIST = 1207; public static final int KHAZARD_GUARD = 1208; public static final int KHAZARD_GUARD_1209 = 1209; public static final int KHAZARD_GUARD_1210 = 1210; public static final int KHAZARD_GUARD_1211 = 1211; public static final int KHAZARD_GUARD_1212 = 1212; public static final int GENERAL_KHAZARD = 1213; public static final int KHAZARD_BARMAN = 1214; public static final int KELVIN = 1215; public static final int JOE = 1216; public static final int FIGHTSLAVE = 1217; public static final int HENGRAD = 1218; public static final int LADY_SERVIL = 1219; public static final int SAMMY_SERVIL = 1220; public static final int SAMMY_SERVIL_1221 = 1221; public static final int JUSTIN_SERVIL = 1222; public static final int LOCAL = 1223; public static final int BOUNCER = 1224; public static final int KHAZARD_OGRE = 1225; public static final int KHAZARD_SCORPION = 1226; public static final int ARZINIAN_AVATAR_OF_STRENGTH = 1227; public static final int ARZINIAN_AVATAR_OF_STRENGTH_1228 = 1228; public static final int ARZINIAN_AVATAR_OF_STRENGTH_1229 = 1229; public static final int ARZINIAN_AVATAR_OF_RANGING = 1230; public static final int ARZINIAN_AVATAR_OF_RANGING_1231 = 1231; public static final int ARZINIAN_AVATAR_OF_RANGING_1232 = 1232; public static final int ARZINIAN_AVATAR_OF_MAGIC = 1233; public static final int ARZINIAN_AVATAR_OF_MAGIC_1234 = 1234; public static final int ARZINIAN_AVATAR_OF_MAGIC_1235 = 1235; public static final int ARZINIAN_BEING_OF_BORDANZAN = 1236; public static final int SABOTEUR = 1237; public static final int GNOME_SHOP_KEEPER = 1238; public static final int CUTE_CREATURE = 1240; public static final int EVIL_CREATURE = 1241; public static final int CUTE_CREATURE_1243 = 1243; public static final int EVIL_CREATURE_1244 = 1244; public static final int CUTE_CREATURE_1246 = 1246; public static final int EVIL_CREATURE_1247 = 1247; public static final int CUTE_CREATURE_1249 = 1249; public static final int EVIL_CREATURE_1250 = 1250; public static final int CUTE_CREATURE_1252 = 1252; public static final int EVIL_CREATURE_1253 = 1253; public static final int CUTE_CREATURE_1255 = 1255; public static final int EVIL_CREATURE_1256 = 1256; public static final int FLUFFIE = 1257; public static final int FLUFFIE_1258 = 1258; public static final int ODD_OLD_MAN = 1259; public static final int FORTUNATO = 1260; public static final int RAM = 1261; public static final int RAM_1262 = 1262; public static final int RAM_1263 = 1263; public static final int RAM_1264 = 1264; public static final int RAM_1265 = 1265; public static final int BONES = 1266; public static final int VULTURE = 1267; public static final int VULTURE_1268 = 1268; public static final int DR_FENKENSTRAIN = 1269; public static final int FENKENSTRAINS_MONSTER = 1270; public static final int LORD_ROLOGARTH = 1271; public static final int GARDENER_GHOST = 1272; public static final int EXPERIMENT = 1273; public static final int EXPERIMENT_1274 = 1274; public static final int EXPERIMENT_1275 = 1275; public static final int LOAR_SHADOW = 1276; public static final int LOAR_SHADE = 1277; public static final int SHADE_SPIRIT = 1278; public static final int PHRIN_SHADOW = 1279; public static final int PHRIN_SHADE = 1280; public static final int RIYL_SHADOW = 1281; public static final int RIYL_SHADE = 1282; public static final int ASYN_SHADOW = 1283; public static final int ASYN_SHADE = 1284; public static final int FIYR_SHADOW = 1285; public static final int FIYR_SHADE = 1286; public static final int AFFLICTEDULSQUIRE = 1287; public static final int ULSQUIRE_SHAUNCY = 1288; public static final int AFFLICTEDRAZMIRE = 1289; public static final int RAZMIRE_KEELGAN = 1290; public static final int MORTTON_LOCAL = 1291; public static final int MORTTON_LOCAL_1292 = 1292; public static final int AFFLICTED = 1293; public static final int AFFLICTED_1294 = 1294; public static final int MORTTON_LOCAL_1295 = 1295; public static final int MORTTON_LOCAL_1296 = 1296; public static final int AFFLICTED_1297 = 1297; public static final int AFFLICTED_1298 = 1298; public static final int SHEEP_1299 = 1299; public static final int SHEEP_1300 = 1300; public static final int SHEEP_1301 = 1301; public static final int SHEEP_1302 = 1302; public static final int SHEEP_1303 = 1303; public static final int SHEEP_1304 = 1304; public static final int HAIRDRESSER = 1305; public static final int MAKEOVER_MAGE = 1306; public static final int MAKEOVER_MAGE_1307 = 1307; public static final int SHEEP_1308 = 1308; public static final int SHEEP_1309 = 1309; public static final int BARTENDER_1310 = 1310; public static final int BARTENDER_1311 = 1311; public static final int BARTENDER_1312 = 1312; public static final int BARTENDER_1313 = 1313; public static final int BARTENDER_1314 = 1314; public static final int EMILY = 1315; public static final int KAYLEE = 1316; public static final int TINA = 1317; public static final int BARTENDER_1318 = 1318; public static final int BARTENDER_1319 = 1319; public static final int BARTENDER_1320 = 1320; public static final int TARQUIN = 1323; public static final int SIGURD = 1324; public static final int HARI = 1325; public static final int BARFY_BILL = 1326; public static final int TYRAS_GUARD_1327 = 1327; public static final int JACK_SEAGULL = 1335; public static final int LONGBOW_BEN = 1336; public static final int AHAB = 1337; public static final int SEAGULL = 1338; public static final int SEAGULL_1339 = 1339; public static final int MATTHIAS = 1340; public static final int MATTHIAS_1341 = 1341; public static final int GYR_FALCON = 1342; public static final int GYR_FALCON_1343 = 1343; public static final int GYR_FALCON_1344 = 1344; public static final int GYR_FALCON_1345 = 1345; public static final int PRICKLY_KEBBIT = 1346; public static final int SABRETOOTHED_KEBBIT = 1347; public static final int BARBTAILED_KEBBIT = 1348; public static final int WILD_KEBBIT = 1349; public static final int ARTIMEUS = 1350; public static final int SETH_GROATS = 1351; public static final int TASSIE_SLIPCAST = 1352; public static final int HAMMERSPIKE_STOUTBEARD = 1353; public static final int DWARF_GANG_MEMBER = 1354; public static final int DWARF_GANG_MEMBER_1355 = 1355; public static final int DWARF_GANG_MEMBER_1356 = 1356; public static final int PHANTUWTI_FANSTUWI_FARSIGHT = 1357; public static final int TINDEL_MARCHANT = 1358; public static final int PETRA_FIYED = 1360; public static final int JIMMY_THE_CHISEL = 1361; public static final int SLAGILITH = 1362; public static final int ROCK_PILE = 1363; public static final int SLAGILITH_1364 = 1364; public static final int FIRE_ELEMENTAL = 1365; public static final int EARTH_ELEMENTAL = 1366; public static final int EARTH_ELEMENTAL_1367 = 1367; public static final int ELEMENTAL_ROCK = 1368; public static final int AIR_ELEMENTAL = 1369; public static final int WATER_ELEMENTAL = 1370; public static final int GUARD_1371 = 1371; public static final int GUARD_1372 = 1372; public static final int HAMAL_THE_CHIEFTAIN = 1373; public static final int RAGNAR = 1374; public static final int SVIDI = 1375; public static final int JOKUL = 1376; public static final int THE_KENDAL = 1377; public static final int THE_KENDAL_1378 = 1378; public static final int CAMP_DWELLER = 1379; public static final int CAMP_DWELLER_1380 = 1380; public static final int CAMP_DWELLER_1381 = 1381; public static final int CAMP_DWELLER_1382 = 1382; public static final int CAMP_DWELLER_1383 = 1383; public static final int MOUNTAIN_GOAT = 1384; public static final int MOUNTAIN_GOAT_1385 = 1385; public static final int MOUNTAIN_GOAT_1386 = 1386; public static final int MOUNTAIN_GOAT_1387 = 1387; public static final int BALD_HEADED_EAGLE = 1388; public static final int BERNALD = 1389; public static final int QUEEN_ELLAMARIA = 1390; public static final int TROLLEY = 1391; public static final int TROLLEY_1392 = 1392; public static final int TROLLEY_1393 = 1393; public static final int BILLY_A_GUARD_OF_FALADOR = 1395; public static final int BOB_ANOTHER_GUARD_OF_FALADOR = 1396; public static final int BROTHER_ALTHRIC = 1397; public static final int PKMASTER0036 = 1398; public static final int KING_ROALD = 1399; public static final int NULODION = 1400; public static final int DWARF_1401 = 1401; public static final int DWARF_1402 = 1402; public static final int DWARF_1403 = 1403; public static final int DWARF_1404 = 1404; public static final int DWARF_1405 = 1405; public static final int DWARF_1406 = 1406; public static final int DWARF_1407 = 1407; public static final int DWARF_1408 = 1408; public static final int BLACK_GUARD = 1409; public static final int BLACK_GUARD_1410 = 1410; public static final int BLACK_GUARD_1411 = 1411; public static final int BLACK_GUARD_1412 = 1412; public static final int ENGINEERING_ASSISTANT = 1413; public static final int ENGINEERING_ASSISTANT_1414 = 1414; public static final int ENGINEER = 1415; public static final int SQUIRREL = 1416; public static final int SQUIRREL_1417 = 1417; public static final int SQUIRREL_1418 = 1418; public static final int RACCOON = 1419; public static final int RACCOON_1420 = 1420; public static final int RACCOON_1421 = 1421; public static final int HAZELMERE = 1422; public static final int GLOUGH = 1425; public static final int CHARLIE = 1428; public static final int FOREMAN = 1429; public static final int SHIPYARD_WORKER = 1430; public static final int FEMI = 1431; public static final int BLACK_DEMON_1432 = 1432; public static final int GNOME_GUARD = 1433; public static final int GARKOR = 1434; public static final int LUMO = 1435; public static final int BUNKDO = 1436; public static final int CARADO = 1437; public static final int LUMDO = 1438; public static final int KARAM = 1439; public static final int BUNKWICKET = 1440; public static final int WAYMOTTIN = 1441; public static final int ZOOKNOCK = 1442; public static final int JUNGLE_DEMON = 1443; public static final int DAERO = 1444; public static final int DAERO_1445 = 1445; public static final int WAYDAR = 1446; public static final int PIRATE_1447 = 1447; public static final int THIEF = 1448; public static final int LUMDO_1453 = 1453; public static final int LUMDO_1454 = 1454; public static final int GLO_CARANOCK = 1460; public static final int MUGGER_1461 = 1461; public static final int SMALL_NINJA_MONKEY = 1462; public static final int MEDIUM_NINJA_MONKEY = 1463; public static final int GORILLA = 1464; public static final int BEARDED_GORILLA = 1465; public static final int ANCIENT_MONKEY = 1466; public static final int SMALL_ZOMBIE_MONKEY = 1467; public static final int LARGE_ZOMBIE_MONKEY = 1468; public static final int MONKEY_1469 = 1469; public static final int RANTZ = 1470; public static final int FYCIE = 1471; public static final int BUGS = 1472; public static final int SWAMP_TOAD = 1473; public static final int BLOATED_TOAD = 1474; public static final int CHOMPY_BIRD = 1475; public static final int CHOMPY_BIRD_1476 = 1476; public static final int EUDAV = 1477; public static final int ORONWEN = 1478; public static final int BANKER_1479 = 1479; public static final int BANKER_1480 = 1480; public static final int DALLDAV = 1481; public static final int GETHIN = 1482; public static final int NICKOLAUS = 1483; public static final int NICKOLAUS_1484 = 1484; public static final int NICKOLAUS_1485 = 1485; public static final int NICKOLAUS_1486 = 1486; public static final int DESERT_EAGLE = 1487; public static final int JUNGLE_EAGLE = 1488; public static final int POLAR_EAGLE = 1489; public static final int EAGLE = 1490; public static final int KEBBIT = 1494; public static final int CHARLIE_1495 = 1495; public static final int BOULDER = 1496; public static final int FISHING_SPOT_1497 = 1497; public static final int FISHING_SPOT_1498 = 1498; public static final int FISHING_SPOT_1499 = 1499; public static final int FISHING_SPOT_1500 = 1500; public static final int ALECK = 1501; public static final int LEON = 1502; public static final int HUNTING_EXPERT = 1503; public static final int HUNTING_EXPERT_1504 = 1504; public static final int FERRET = 1505; public static final int ROD_FISHING_SPOT_1506 = 1506; public static final int ROD_FISHING_SPOT_1507 = 1507; public static final int ROD_FISHING_SPOT_1508 = 1508; public static final int ROD_FISHING_SPOT_1509 = 1509; public static final int FISHING_SPOT_1510 = 1510; public static final int FISHING_SPOT_1511 = 1511; public static final int ROD_FISHING_SPOT_1512 = 1512; public static final int ROD_FISHING_SPOT_1513 = 1513; public static final int FISHING_SPOT_1514 = 1514; public static final int ROD_FISHING_SPOT_1515 = 1515; public static final int ROD_FISHING_SPOT_1516 = 1516; public static final int FISHING_SPOT_1517 = 1517; public static final int FISHING_SPOT_1518 = 1518; public static final int FISHING_SPOT_1519 = 1519; public static final int FISHING_SPOT_1520 = 1520; public static final int FISHING_SPOT_1521 = 1521; public static final int FISHING_SPOT_1522 = 1522; public static final int FISHING_SPOT_1523 = 1523; public static final int FISHING_SPOT_1524 = 1524; public static final int FISHING_SPOT_1525 = 1525; public static final int ROD_FISHING_SPOT_1526 = 1526; public static final int ROD_FISHING_SPOT_1527 = 1527; public static final int FISHING_SPOT_1528 = 1528; public static final int ROD_FISHING_SPOT_1529 = 1529; public static final int FISHING_SPOT_1530 = 1530; public static final int ROD_FISHING_SPOT_1531 = 1531; public static final int FISHING_SPOT_1532 = 1532; public static final int FISHING_SPOT_1533 = 1533; public static final int FISHING_SPOT_1534 = 1534; public static final int FISHING_SPOT_1535 = 1535; public static final int FISHING_SPOT_1536 = 1536; public static final int SKELETON_HERO = 1537; public static final int SKELETON_BRUTE = 1538; public static final int SKELETON_WARLORD = 1539; public static final int SKELETON_HEAVY = 1540; public static final int SKELETON_THUG = 1541; public static final int FISHING_SPOT_1542 = 1542; public static final int GARGOYLE_1543 = 1543; public static final int FISHING_SPOT_1544 = 1544; public static final int BLACK_KNIGHT_1545 = 1545; public static final int GUARD_1546 = 1546; public static final int GUARD_1547 = 1547; public static final int GUARD_1548 = 1548; public static final int GUARD_1549 = 1549; public static final int GUARD_1550 = 1550; public static final int GUARD_1551 = 1551; public static final int GUARD_1552 = 1552; public static final int CRAB_1553 = 1553; public static final int SEAGULL_1554 = 1554; public static final int SEAGULL_1555 = 1555; public static final int FIRE_WIZARD = 1556; public static final int WATER_WIZARD = 1557; public static final int EARTH_WIZARD = 1558; public static final int AIR_WIZARD = 1559; public static final int ORDAN = 1560; public static final int JORZIK = 1561; public static final int SMIDDI_RYAK_HARD = 1562; public static final int ROLAYNE_TWICKIT_HARD = 1563; public static final int JAYENE_KLIYN_MEDIUM = 1564; public static final int VALANTAY_EPPEL_MEDIUM = 1565; public static final int DALCIAN_FANG_EASY = 1566; public static final int FYIONA_FRAY_EASY = 1567; public static final int ABIDOR_CRANK = 1568; public static final int BENJAMIN = 1569; public static final int LIAM = 1570; public static final int MIALA = 1571; public static final int VERAK = 1572; public static final int FORESTER_HARD = 1573; public static final int WOMANATARMS_HARD = 1574; public static final int APPRENTICE_MEDIUM = 1575; public static final int RANGER_MEDIUM = 1576; public static final int ADVENTURER_EASY = 1577; public static final int MAGE_EASY = 1578; public static final int HIYLIK_MYNA = 1579; public static final int DUMMY = 1580; public static final int DUMMY_1581 = 1581; public static final int DUMMY_1582 = 1582; public static final int DUMMY_1583 = 1583; public static final int DUMMY_1584 = 1584; public static final int DUMMY_1585 = 1585; public static final int DUMMY_1586 = 1586; public static final int DUMMY_1587 = 1587; public static final int DUMMY_1588 = 1588; public static final int DUMMY_1589 = 1589; public static final int DUMMY_1590 = 1590; public static final int DUMMY_1591 = 1591; public static final int DUMMY_1592 = 1592; public static final int DUMMY_1593 = 1593; public static final int DUMMY_1594 = 1594; public static final int DUMMY_1595 = 1595; public static final int DUMMY_1596 = 1596; public static final int DUMMY_1597 = 1597; public static final int DUMMY_1598 = 1598; public static final int DUMMY_1599 = 1599; public static final int GUNDAI = 1600; public static final int LUNDAIL = 1601; public static final int CHAMBER_GUARDIAN = 1602; public static final int KOLODION = 1603; public static final int KOLODION_1604 = 1604; public static final int KOLODION_1605 = 1605; public static final int KOLODION_1606 = 1606; public static final int KOLODION_1607 = 1607; public static final int KOLODION_1608 = 1608; public static final int KOLODION_1609 = 1609; public static final int BATTLE_MAGE = 1610; public static final int BATTLE_MAGE_1611 = 1611; public static final int BATTLE_MAGE_1612 = 1612; public static final int BANKER_1613 = 1613; public static final int PHIALS = 1614; public static final int BANKNOTE_EXCHANGE_MERCHANT = 1615; public static final int HIGH_PRIESTESS_ZULHARCINQA = 1616; public static final int PRIESTESS_ZULGWENWYNIG = 1617; public static final int BANKER_1618 = 1618; public static final int CAT_1619 = 1619; public static final int CAT_1620 = 1620; public static final int CAT_1621 = 1621; public static final int CAT_1622 = 1622; public static final int CAT_1623 = 1623; public static final int CAT_1624 = 1624; public static final int HELLCAT = 1625; public static final int LAZY_CAT = 1626; public static final int LAZY_CAT_1627 = 1627; public static final int LAZY_CAT_1628 = 1628; public static final int LAZY_CAT_1629 = 1629; public static final int LAZY_CAT_1630 = 1630; public static final int LAZY_CAT_1631 = 1631; public static final int LAZY_HELLCAT = 1632; public static final int BANKER_1633 = 1633; public static final int BANKER_1634 = 1634; public static final int BABY_IMPLING = 1635; public static final int YOUNG_IMPLING = 1636; public static final int GOURMET_IMPLING = 1637; public static final int EARTH_IMPLING = 1638; public static final int ESSENCE_IMPLING = 1639; public static final int ECLECTIC_IMPLING = 1640; public static final int NATURE_IMPLING = 1641; public static final int MAGPIE_IMPLING = 1642; public static final int NINJA_IMPLING = 1643; public static final int DRAGON_IMPLING = 1644; public static final int BABY_IMPLING_1645 = 1645; public static final int YOUNG_IMPLING_1646 = 1646; public static final int GOURMET_IMPLING_1647 = 1647; public static final int EARTH_IMPLING_1648 = 1648; public static final int ESSENCE_IMPLING_1649 = 1649; public static final int ECLECTIC_IMPLING_1650 = 1650; public static final int NATURE_IMPLING_1651 = 1651; public static final int MAGPIE_IMPLING_1652 = 1652; public static final int NINJA_IMPLING_1653 = 1653; public static final int DRAGON_IMPLING_1654 = 1654; public static final int EGG_LAUNCHER = 1655; public static final int COMMANDER_CONNAD = 1656; public static final int CAPTAIN_CAIN = 1657; public static final int PRIVATE_PALDO = 1658; public static final int PRIVATE_PENDRON = 1659; public static final int PRIVATE_PIERREB = 1660; public static final int PRIVATE_PALDON = 1661; public static final int MAJOR_ATTACK = 1662; public static final int MAJOR_COLLECT = 1663; public static final int MAJOR_DEFEND = 1664; public static final int MAJOR_HEAL = 1665; public static final int SERGEANT_SAMBUR = 1666; public static final int PENANCE_FIGHTER = 1667; public static final int PENANCE_RANGER = 1668; public static final int PENANCE_RUNNER = 1669; public static final int PENANCE_HEALER = 1670; public static final int STRANGE_OLD_MAN = 1671; public static final int AHRIM_THE_BLIGHTED = 1672; public static final int DHAROK_THE_WRETCHED = 1673; public static final int GUTHAN_THE_INFESTED = 1674; public static final int KARIL_THE_TAINTED = 1675; public static final int TORAG_THE_CORRUPTED = 1676; public static final int VERAC_THE_DEFILED = 1677; public static final int BLOODWORM = 1678; public static final int CRYPT_RAT = 1679; public static final int GIANT_CRYPT_RAT = 1680; public static final int GIANT_CRYPT_RAT_1681 = 1681; public static final int GIANT_CRYPT_RAT_1682 = 1682; public static final int CRYPT_SPIDER = 1683; public static final int GIANT_CRYPT_SPIDER = 1684; public static final int SKELETON_1685 = 1685; public static final int SKELETON_1686 = 1686; public static final int SKELETON_1687 = 1687; public static final int SKELETON_1688 = 1688; public static final int SPLATTER = 1689; public static final int SPLATTER_1690 = 1690; public static final int SPLATTER_1691 = 1691; public static final int SPLATTER_1692 = 1692; public static final int SPLATTER_1693 = 1693; public static final int SHIFTER = 1694; public static final int SHIFTER_1695 = 1695; public static final int SHIFTER_1696 = 1696; public static final int SHIFTER_1697 = 1697; public static final int SHIFTER_1698 = 1698; public static final int SHIFTER_1699 = 1699; public static final int SHIFTER_1700 = 1700; public static final int SHIFTER_1701 = 1701; public static final int SHIFTER_1702 = 1702; public static final int SHIFTER_1703 = 1703; public static final int RAVAGER = 1704; public static final int RAVAGER_1705 = 1705; public static final int RAVAGER_1706 = 1706; public static final int RAVAGER_1707 = 1707; public static final int RAVAGER_1708 = 1708; public static final int SPINNER = 1709; public static final int SPINNER_1710 = 1710; public static final int SPINNER_1711 = 1711; public static final int SPINNER_1712 = 1712; public static final int SPINNER_1713 = 1713; public static final int TORCHER = 1714; public static final int TORCHER_1715 = 1715; public static final int TORCHER_1716 = 1716; public static final int TORCHER_1717 = 1717; public static final int TORCHER_1718 = 1718; public static final int TORCHER_1719 = 1719; public static final int TORCHER_1720 = 1720; public static final int TORCHER_1721 = 1721; public static final int TORCHER_1722 = 1722; public static final int TORCHER_1723 = 1723; public static final int DEFILER = 1724; public static final int DEFILER_1725 = 1725; public static final int DEFILER_1726 = 1726; public static final int DEFILER_1727 = 1727; public static final int DEFILER_1728 = 1728; public static final int DEFILER_1729 = 1729; public static final int DEFILER_1730 = 1730; public static final int DEFILER_1731 = 1731; public static final int DEFILER_1732 = 1732; public static final int DEFILER_1733 = 1733; public static final int BRAWLER = 1734; public static final int BRAWLER_1735 = 1735; public static final int BRAWLER_1736 = 1736; public static final int BRAWLER_1737 = 1737; public static final int BRAWLER_1738 = 1738; public static final int PORTAL = 1739; public static final int PORTAL_1740 = 1740; public static final int PORTAL_1741 = 1741; public static final int PORTAL_1742 = 1742; public static final int PORTAL_1743 = 1743; public static final int PORTAL_1744 = 1744; public static final int PORTAL_1745 = 1745; public static final int PORTAL_1746 = 1746; public static final int PORTAL_1747 = 1747; public static final int PORTAL_1748 = 1748; public static final int PORTAL_1749 = 1749; public static final int PORTAL_1750 = 1750; public static final int PORTAL_1751 = 1751; public static final int PORTAL_1752 = 1752; public static final int PORTAL_1753 = 1753; public static final int PORTAL_1754 = 1754; public static final int VOID_KNIGHT = 1755; public static final int VOID_KNIGHT_1756 = 1756; public static final int VOID_KNIGHT_1757 = 1757; public static final int VOID_KNIGHT_1758 = 1758; public static final int SQUIRE = 1759; public static final int SQUIRE_1760 = 1760; public static final int SQUIRE_1761 = 1761; public static final int SQUIRE_1762 = 1762; public static final int SQUIRE_1764 = 1764; public static final int SQUIRE_1765 = 1765; public static final int SQUIRE_1766 = 1766; public static final int SQUIRE_1767 = 1767; public static final int SQUIRE_1768 = 1768; public static final int SQUIRE_1769 = 1769; public static final int SQUIRE_1770 = 1770; public static final int SQUIRE_NOVICE = 1771; public static final int SQUIRE_INTERMEDIATE = 1772; public static final int SQUIRE_VETERAN = 1773; public static final int URI = 1774; public static final int URI_1775 = 1775; public static final int URI_1776 = 1776; public static final int DOUBLE_AGENT = 1777; public static final int DOUBLE_AGENT_1778 = 1778; public static final int GUARDIAN_MUMMY = 1779; public static final int ANNOYED_GUARDIAN_MUMMY = 1780; public static final int TARIK = 1781; public static final int SCARAB_SWARM = 1782; public static final int MALIGNIUS_MORTIFER = 1783; public static final int ZOMBIE_1784 = 1784; public static final int SKELETON_1785 = 1785; public static final int GHOST_1786 = 1786; public static final int SKELETON_MAGE_1787 = 1787; public static final int BETTY = 1788; public static final int GRUM = 1789; public static final int GERRANT = 1790; public static final int WYDIN = 1791; public static final int GOAT = 1792; public static final int GOAT_1793 = 1793; public static final int BILLY_GOAT = 1794; public static final int GOAT_1795 = 1795; public static final int GOAT_1796 = 1796; public static final int BILLY_GOAT_1797 = 1797; public static final int WHITE_KNIGHT = 1798; public static final int WHITE_KNIGHT_1799 = 1799; public static final int WHITE_KNIGHT_1800 = 1800; public static final int SUMMER_ELEMENTAL = 1801; public static final int SUMMER_ELEMENTAL_1802 = 1802; public static final int SUMMER_ELEMENTAL_1803 = 1803; public static final int SUMMER_ELEMENTAL_1804 = 1804; public static final int SUMMER_ELEMENTAL_1805 = 1805; public static final int SUMMER_ELEMENTAL_1806 = 1806; public static final int SORCERESS = 1807; public static final int APPRENTICE = 1808; public static final int OSMAN = 1809; public static final int OSMAN_1810 = 1810; public static final int OSMAN_1811 = 1811; public static final int DELMONTY = 1813; public static final int SAN_FAN = 1814; public static final int FANCY_DAN = 1815; public static final int HONEST_JIMMY = 1816; public static final int MONKEY_1817 = 1817; public static final int SWARM_1818 = 1818; public static final int BLUE_MONKEY = 1825; public static final int RED_MONKEY = 1826; public static final int PARROT = 1827; public static final int PARROT_1828 = 1828; public static final int WHITE_KNIGHT_1829 = 1829; public static final int SHARK_1830 = 1830; public static final int SWAN = 1831; public static final int BLACK_SWAN = 1832; public static final int BANDIT_SHOPKEEPER = 1833; public static final int GORAK = 1834; public static final int COSMIC_BEING = 1835; public static final int DUCK = 1838; public static final int DUCK_1839 = 1839; public static final int FAIRY_GODFATHER = 1840; public static final int FAIRY_NUFF = 1841; public static final int FAIRY_QUEEN_1842 = 1842; public static final int CENTAUR = 1843; public static final int CENTAUR_1844 = 1844; public static final int STAG = 1845; public static final int WOOD_DRYAD = 1846; public static final int FAIRY_VERY_WISE = 1847; public static final int FAIRY = 1848; public static final int FAIRY_1849 = 1849; public static final int FAIRY_1850 = 1850; public static final int FAIRY_1851 = 1851; public static final int RABBIT = 1852; public static final int RABBIT_1853 = 1853; public static final int BUTTERFLY_1854 = 1854; public static final int BUTTERFLY_1855 = 1855; public static final int STARFLOWER = 1856; public static final int STARFLOWER_1857 = 1857; public static final int TREE_SPIRIT_1861 = 1861; public static final int TREE_SPIRIT_1862 = 1862; public static final int TREE_SPIRIT_1863 = 1863; public static final int TREE_SPIRIT_1864 = 1864; public static final int TREE_SPIRIT_1865 = 1865; public static final int TREE_SPIRIT_1866 = 1866; public static final int SIR_AMIK_VARZE = 1867; public static final int SIR_AMIK_VARZE_1869 = 1869; public static final int EVIL_CHICKEN = 1870; public static final int BABY_BLACK_DRAGON = 1871; public static final int BABY_BLACK_DRAGON_1872 = 1872; public static final int KKLIK = 1873; public static final int ICE_TROLL_RUNT = 1874; public static final int ICE_TROLL_MALE = 1875; public static final int ICE_TROLL_FEMALE = 1876; public static final int ICE_TROLL_GRUNT = 1877; public static final int MAWNIS_BUROWGAR = 1878; public static final int MAWNIS_BUROWGAR_1879 = 1879; public static final int FRIDLEIF_SHIELDSON = 1880; public static final int THAKKRAD_SIGMUNDSON = 1881; public static final int MARIA_GUNNARS = 1882; public static final int MARIA_GUNNARS_1883 = 1883; public static final int JOFRIDR_MORDSTATTER = 1884; public static final int MORTEN_HOLDSTROM = 1885; public static final int GUNNAR_HOLDSTROM = 1886; public static final int ANNE_ISAAKSON = 1887; public static final int LISSE_ISAAKSON = 1888; public static final int HONOUR_GUARD = 1889; public static final int HONOUR_GUARD_1890 = 1890; public static final int HONOUR_GUARD_1891 = 1891; public static final int HONOUR_GUARD_1892 = 1892; public static final int KJEDELIG_UPPSEN = 1893; public static final int TROGEN_KONUNGARDE = 1894; public static final int SLUG_HEMLIGSSEN = 1895; public static final int CANDLE_SELLER = 1896; public static final int KING_GJUKI_SORVOTT_IV = 1897; public static final int HRH_HRAFN = 1898; public static final int THORKEL_SILKBEARD = 1899; public static final int MORD_GUNNARS = 1900; public static final int ART_CRITIC_JACQUES = 1901; public static final int HISTORIAN_MINAS = 1902; public static final int BARNABUS_HURMA = 1903; public static final int MARIUS_GISTE = 1904; public static final int CADEN_AZRO = 1905; public static final int THIAS_LEACKE = 1906; public static final int SINCO_DOAR = 1907; public static final int TINSE_TORPE = 1908; public static final int INFORMATION_CLERK = 1909; public static final int MUSEUM_GUARD = 1910; public static final int MUSEUM_GUARD_1911 = 1911; public static final int MUSEUM_GUARD_1912 = 1912; public static final int TEACHER_AND_PUPIL = 1913; public static final int SCHOOLGIRL = 1914; public static final int SCHOOLGIRL_1915 = 1915; public static final int SCHOOLGIRL_1916 = 1916; public static final int SCHOOLGIRL_1917 = 1917; public static final int SCHOOLGIRL_1918 = 1918; public static final int SCHOOLBOY = 1919; public static final int SCHOOLBOY_1920 = 1920; public static final int SCHOOLGIRL_1921 = 1921; public static final int TEACHER_AND_PUPIL_1922 = 1922; public static final int TEACHER_AND_PUPIL_1923 = 1923; public static final int SCHOOLBOY_1924 = 1924; public static final int TEACHER = 1925; public static final int SCHOOLGIRL_1926 = 1926; public static final int WORKMAN = 1927; public static final int WORKMAN_1928 = 1928; public static final int WORKMAN_1929 = 1929; public static final int WORKMAN_1930 = 1930; public static final int WORKMAN_1931 = 1931; public static final int WORKMAN_1932 = 1932; public static final int DIG_SITE_WORKMAN = 1933; public static final int BARGE_WORKMAN = 1934; public static final int BARGE_WORKMAN_1935 = 1935; public static final int BARGE_WORKMAN_1936 = 1936; public static final int BARGE_WORKMAN_1937 = 1937; public static final int BARGE_FOREMAN = 1938; public static final int ED_WOOD = 1939; public static final int MORD_GUNNARS_1940 = 1940; public static final int HRING_HRING = 1941; public static final int FLOSI_DALKSSON = 1942; public static final int RAUM_URDASTEIN = 1943; public static final int SKULI_MYRKA = 1944; public static final int KEEPA_KETTILON = 1945; public static final int GUARD_1947 = 1947; public static final int GUARD_1948 = 1948; public static final int GUARD_1949 = 1949; public static final int GUARD_1950 = 1950; public static final int FREYGERD = 1951; public static final int LENSA = 1952; public static final int VANLIGGA_GASTFRIHET = 1990; public static final int SASSILIK = 1991; public static final int MINER = 1992; public static final int MINER_1993 = 1993; public static final int ERIC_1997 = 1997; public static final int GRUVA_PATRULL = 1998; public static final int BRENDT = 1999; public static final int GRUNDT = 2000; public static final int DUCKLING = 2001; public static final int DUCKLINGS = 2002; public static final int DUCK_2003 = 2003; public static final int DRAKE = 2004; public static final int LESSER_DEMON = 2005; public static final int LESSER_DEMON_2006 = 2006; public static final int LESSER_DEMON_2007 = 2007; public static final int LESSER_DEMON_2008 = 2008; public static final int LESSER_DEMON_2018 = 2018; public static final int GREATER_DEMON = 2025; public static final int GREATER_DEMON_2026 = 2026; public static final int GREATER_DEMON_2027 = 2027; public static final int GREATER_DEMON_2028 = 2028; public static final int GREATER_DEMON_2029 = 2029; public static final int GREATER_DEMON_2030 = 2030; public static final int GREATER_DEMON_2031 = 2031; public static final int GREATER_DEMON_2032 = 2032; public static final int PRIESTESS_ZULGWENWYNIG_2033 = 2033; public static final int ZULURGISH = 2034; public static final int ZULCHERAY = 2035; public static final int ZULGUTUSOLLY = 2036; public static final int SACRIFICE = 2037; public static final int ZULONAN = 2038; public static final int ZULANIEL = 2039; public static final int ZULARETH = 2040; public static final int BROKEN_HANDZ = 2041; public static final int ZULRAH = 2042; public static final int ZULRAH_2043 = 2043; public static final int ZULRAH_2044 = 2044; public static final int SNAKELING = 2045; public static final int SNAKELING_2046 = 2046; public static final int SNAKELING_2047 = 2047; public static final int BLACK_DEMON_2048 = 2048; public static final int BLACK_DEMON_2049 = 2049; public static final int BLACK_DEMON_2050 = 2050; public static final int BLACK_DEMON_2051 = 2051; public static final int BLACK_DEMON_2052 = 2052; public static final int FRITZ_THE_GLASSBLOWER = 2053; public static final int CHAOS_ELEMENTAL = 2054; public static final int CHAOS_ELEMENTAL_JR = 2055; public static final int DARK_WIZARD_2056 = 2056; public static final int DARK_WIZARD_2057 = 2057; public static final int DARK_WIZARD_2058 = 2058; public static final int DARK_WIZARD_2059 = 2059; public static final int DODGY_SQUIRE = 2060; public static final int GLOUGH_2061 = 2061; public static final int OOMLIE_BIRD = 2062; public static final int PENGUIN_2063 = 2063; public static final int TERRORBIRD = 2064; public static final int TERRORBIRD_2065 = 2065; public static final int TERRORBIRD_2066 = 2066; public static final int MOUNTED_TERRORBIRD_GNOME = 2067; public static final int MOUNTED_TERRORBIRD_GNOME_2068 = 2068; public static final int CROW = 2069; public static final int CROW_2070 = 2070; public static final int CROW_2071 = 2071; public static final int CROW_2072 = 2072; public static final int CROW_2073 = 2073; public static final int CROW_2074 = 2074; public static final int FIRE_GIANT = 2075; public static final int FIRE_GIANT_2076 = 2076; public static final int FIRE_GIANT_2077 = 2077; public static final int FIRE_GIANT_2078 = 2078; public static final int FIRE_GIANT_2079 = 2079; public static final int FIRE_GIANT_2080 = 2080; public static final int FIRE_GIANT_2081 = 2081; public static final int FIRE_GIANT_2082 = 2082; public static final int FIRE_GIANT_2083 = 2083; public static final int FIRE_GIANT_2084 = 2084; public static final int ICE_GIANT = 2085; public static final int ICE_GIANT_2086 = 2086; public static final int ICE_GIANT_2087 = 2087; public static final int ICE_GIANT_2088 = 2088; public static final int ICE_GIANT_2089 = 2089; public static final int MOSS_GIANT = 2090; public static final int MOSS_GIANT_2091 = 2091; public static final int MOSS_GIANT_2092 = 2092; public static final int MOSS_GIANT_2093 = 2093; public static final int JOGRE = 2094; public static final int OGRE_2095 = 2095; public static final int OGRE_2096 = 2096; public static final int CYCLOPS = 2097; public static final int HILL_GIANT = 2098; public static final int HILL_GIANT_2099 = 2099; public static final int HILL_GIANT_2100 = 2100; public static final int HILL_GIANT_2101 = 2101; public static final int HILL_GIANT_2102 = 2102; public static final int HILL_GIANT_2103 = 2103; public static final int ORK = 2104; public static final int ORK_2105 = 2105; public static final int ORK_2106 = 2106; public static final int ORK_2107 = 2107; public static final int WISE_OLD_MAN = 2108; public static final int WISE_OLD_MAN_2110 = 2110; public static final int WISE_OLD_MAN_2111 = 2111; public static final int WISE_OLD_MAN_2112 = 2112; public static final int WISE_OLD_MAN_2113 = 2113; public static final int BED = 2114; public static final int THING_UNDER_THE_BED = 2115; public static final int MISS_SCHISM = 2116; public static final int BANKER_2117 = 2117; public static final int BANKER_2118 = 2118; public static final int BANKER_2119 = 2119; public static final int MARKET_GUARD = 2120; public static final int OLIVIA_2121 = 2121; public static final int PILLORY_GUARD_2122 = 2122; public static final int BANK_GUARD = 2123; public static final int BADGER = 2125; public static final int BADGER_2126 = 2126; public static final int SNAKELING_2127 = 2127; public static final int SNAKELING_2128 = 2128; public static final int SNAKELING_2129 = 2129; public static final int SNAKELING_2130 = 2130; public static final int SNAKELING_2131 = 2131; public static final int SNAKELING_2132 = 2132; public static final int TILES = 2133; public static final int AISLES = 2134; public static final int LORELAI = 2135; public static final int RORY = 2136; public static final int CYCLOPS_2137 = 2137; public static final int CYCLOPS_2138 = 2138; public static final int CYCLOPS_2139 = 2139; public static final int CYCLOPS_2140 = 2140; public static final int CYCLOPS_2141 = 2141; public static final int CYCLOPS_2142 = 2142; public static final int SRARACHA = 2143; public static final int SRARACHA_2144 = 2144; public static final int UNDEAD_DRUID = 2145; public static final int FISHING_SPOT_2146 = 2146; public static final int GRAND_EXCHANGE_CLERK = 2148; public static final int GRAND_EXCHANGE_CLERK_2149 = 2149; public static final int GRAND_EXCHANGE_CLERK_2150 = 2150; public static final int GRAND_EXCHANGE_CLERK_2151 = 2151; public static final int BRUGSEN_BURSEN = 2152; public static final int GUNNJORN = 2153; public static final int TZHAARMEJ = 2154; public static final int TZHAARMEJ_2155 = 2155; public static final int TZHAARMEJ_2156 = 2156; public static final int TZHAARMEJ_2157 = 2157; public static final int TZHAARMEJ_2158 = 2158; public static final int TZHAARMEJ_2159 = 2159; public static final int TZHAARMEJ_2160 = 2160; public static final int TZHAARHUR = 2161; public static final int TZHAARHUR_2162 = 2162; public static final int TZHAARHUR_2163 = 2163; public static final int TZHAARHUR_2164 = 2164; public static final int TZHAARHUR_2165 = 2165; public static final int TZHAARHUR_2166 = 2166; public static final int TZHAARXIL = 2167; public static final int TZHAARXIL_2168 = 2168; public static final int TZHAARXIL_2169 = 2169; public static final int TZHAARXIL_2170 = 2170; public static final int TZHAARXIL_2171 = 2171; public static final int TZHAARXIL_2172 = 2172; public static final int TZHAARKET = 2173; public static final int TZHAARKET_2174 = 2174; public static final int TZHAARKET_2175 = 2175; public static final int TZHAARKET_2176 = 2176; public static final int TZHAARKET_2177 = 2177; public static final int TZHAARKET_2178 = 2178; public static final int TZHAARKET_2179 = 2179; public static final int TZHAARMEJJAL = 2180; public static final int TZHAARMEJKAH = 2181; public static final int ROCK_GOLEM = 2182; public static final int TZHAARHURTEL = 2183; public static final int TZHAARHURLEK = 2184; public static final int TZHAARMEJROH = 2185; public static final int TZHAARKET_2186 = 2186; public static final int TZHAARKET_2187 = 2187; public static final int ROCKS_2188 = 2188; public static final int TZKIH = 2189; public static final int TZKIH_2190 = 2190; public static final int TZKEK = 2191; public static final int TZKEK_2192 = 2192; public static final int TOKXIL_2193 = 2193; public static final int TOKXIL_2194 = 2194; public static final int WILLIAM = 2195; public static final int IAN = 2196; public static final int LARRY_2197 = 2197; public static final int DARREN = 2198; public static final int EDWARD = 2199; public static final int RICHARD_2200 = 2200; public static final int NEIL = 2201; public static final int EDMOND = 2202; public static final int SIMON = 2203; public static final int SAM = 2204; public static final int COMMANDER_ZILYANA = 2205; public static final int STARLIGHT = 2206; public static final int GROWLER = 2207; public static final int BREE = 2208; public static final int SARADOMIN_PRIEST = 2209; public static final int SPIRITUAL_WARRIOR = 2210; public static final int SPIRITUAL_RANGER = 2211; public static final int SPIRITUAL_MAGE = 2212; public static final int KNIGHT_OF_SARADOMIN = 2213; public static final int KNIGHT_OF_SARADOMIN_2214 = 2214; public static final int GENERAL_GRAARDOR = 2215; public static final int SERGEANT_STRONGSTACK = 2216; public static final int SERGEANT_STEELWILL = 2217; public static final int SERGEANT_GRIMSPIKE = 2218; public static final int PURPLE_PEWTER_DIRECTOR = 2219; public static final int PURPLE_PEWTER_DIRECTOR_2220 = 2220; public static final int BLUE_OPAL_DIRECTOR = 2221; public static final int YELLOW_FORTUNE_DIRECTOR = 2222; public static final int GREEN_GEMSTONE_DIRECTOR = 2223; public static final int WHITE_CHISEL_DIRECTOR = 2224; public static final int SILVER_COG_DIRECTOR = 2225; public static final int BROWN_ENGINE_DIRECTOR = 2226; public static final int RED_AXE_DIRECTOR = 2227; public static final int COMMANDER_VELDABAN = 2228; public static final int RED_AXE_CAT = 2229; public static final int RED_AXE_CAT_2230 = 2230; public static final int BLACK_GUARD_BERSERKER = 2232; public static final int OGRE_2233 = 2233; public static final int JOGRE_2234 = 2234; public static final int CYCLOPS_2235 = 2235; public static final int CYCLOPS_2236 = 2236; public static final int ORK_2237 = 2237; public static final int ORK_2238 = 2238; public static final int ORK_2239 = 2239; public static final int ORK_2240 = 2240; public static final int HOBGOBLIN_2241 = 2241; public static final int SPIRITUAL_RANGER_2242 = 2242; public static final int SPIRITUAL_WARRIOR_2243 = 2243; public static final int SPIRITUAL_MAGE_2244 = 2244; public static final int GOBLIN_2245 = 2245; public static final int GOBLIN_2246 = 2246; public static final int GOBLIN_2247 = 2247; public static final int GOBLIN_2248 = 2248; public static final int GOBLIN_2249 = 2249; public static final int DOORSUPPORT = 2250; public static final int DOOR = 2251; public static final int DOOR_2252 = 2252; public static final int DOORSUPPORT_2253 = 2253; public static final int DOOR_2254 = 2254; public static final int DOOR_2255 = 2255; public static final int DOORSUPPORT_2256 = 2256; public static final int DOOR_2257 = 2257; public static final int DOOR_2258 = 2258; public static final int DAGANNOTH_2259 = 2259; public static final int GIANT_ROCK_CRAB = 2261; public static final int BOULDER_2262 = 2262; public static final int BARDUR = 2263; public static final int DAGANNOTH_FLEDGELING = 2264; public static final int DAGANNOTH_SUPREME = 2265; public static final int DAGANNOTH_PRIME = 2266; public static final int DAGANNOTH_REX = 2267; public static final int CAVE_GOBLIN = 2268; public static final int CAVE_GOBLIN_2269 = 2269; public static final int CAVE_GOBLIN_2270 = 2270; public static final int CAVE_GOBLIN_2271 = 2271; public static final int CAVE_GOBLIN_2272 = 2272; public static final int CAVE_GOBLIN_2273 = 2273; public static final int CAVE_GOBLIN_2274 = 2274; public static final int CAVE_GOBLIN_2275 = 2275; public static final int CAVE_GOBLIN_2276 = 2276; public static final int CAVE_GOBLIN_2277 = 2277; public static final int CAVE_GOBLIN_2278 = 2278; public static final int CAVE_GOBLIN_2279 = 2279; public static final int CAVE_GOBLIN_2280 = 2280; public static final int CAVE_GOBLIN_2281 = 2281; public static final int CAVE_GOBLIN_2282 = 2282; public static final int CAVE_GOBLIN_2283 = 2283; public static final int CAVE_GOBLIN_2284 = 2284; public static final int CAVE_GOBLIN_2285 = 2285; public static final int URZEK = 2286; public static final int URVASS = 2287; public static final int URTAAL = 2288; public static final int URMEG = 2289; public static final int URLUN = 2290; public static final int URPEL = 2291; public static final int BANKER_2292 = 2292; public static final int BANKER_2293 = 2293; public static final int BARTAK = 2294; public static final int TURGALL = 2295; public static final int RELDAK = 2296; public static final int MILTOG = 2297; public static final int MERNIK = 2298; public static final int CAVE_GOBLIN_2299 = 2299; public static final int CRATE_GOBLIN = 2300; public static final int CAVE_GOBLIN_2301 = 2301; public static final int GOBLIN_SCRIBE = 2302; public static final int GOURMET = 2304; public static final int GOURMET_2305 = 2305; public static final int GOURMET_2306 = 2306; public static final int GOURMET_2307 = 2307; public static final int TURGOK = 2308; public static final int MARKOG = 2309; public static final int DURGOK = 2310; public static final int TINDAR = 2311; public static final int GUNDIK = 2312; public static final int ZENKOG = 2313; public static final int LURGON = 2314; public static final int URTAG = 2315; public static final int GUARD_2316 = 2316; public static final int GUARD_2317 = 2317; public static final int ZANIK = 2318; public static final int YOUNG_UN = 2319; public static final int TYKE = 2320; public static final int NIPPER = 2321; public static final int NIPPER_2322 = 2322; public static final int CAVE_GOBLIN_CHILD = 2323; public static final int CAVE_GOBLIN_CHILD_2324 = 2324; public static final int CAVE_GOBLIN_CHILD_2325 = 2325; public static final int CAVE_GOBLIN_CHILD_2326 = 2326; public static final int CAVE_GOBLIN_CHILD_2327 = 2327; public static final int CAVE_GOBLIN_CHILD_2328 = 2328; public static final int CAVE_GOBLIN_CHILD_2329 = 2329; public static final int CAVE_GOBLIN_CHILD_2330 = 2330; public static final int CAVE_GOBLIN_CHILD_2331 = 2331; public static final int CAVE_GOBLIN_CHILD_2332 = 2332; public static final int CAVE_GOBLIN_CHILD_2333 = 2333; public static final int CAVE_GOBLIN_CHILD_2334 = 2334; public static final int CAVE_GOBLIN_CHILD_2335 = 2335; public static final int CAVE_GOBLIN_CHILD_2336 = 2336; public static final int CAVE_GOBLIN_CHILD_2337 = 2337; public static final int CAVE_GOBLIN_CHILD_2338 = 2338; public static final int SPIT_GOBLIN = 2339; public static final int GOBLIN_FISH = 2340; public static final int MOVARIO = 2341; public static final int DARVE = 2342; public static final int MOTHS = 2343; public static final int BARLAK = 2344; public static final int SANIBOCH = 2345; public static final int DROMUNDS_CAT = 2346; public static final int BLASIDAR_THE_SCULPTOR = 2347; public static final int RIKI_THE_SCULPTORS_MODEL = 2348; public static final int RIKI_THE_SCULPTORS_MODEL_2349 = 2349; public static final int RIKI_THE_SCULPTORS_MODEL_2350 = 2350; public static final int RIKI_THE_SCULPTORS_MODEL_2351 = 2351; public static final int RIKI_THE_SCULPTORS_MODEL_2352 = 2352; public static final int RIKI_THE_SCULPTORS_MODEL_2353 = 2353; public static final int RIKI_THE_SCULPTORS_MODEL_2354 = 2354; public static final int RIKI_THE_SCULPTORS_MODEL_2355 = 2355; public static final int VIGR = 2356; public static final int SANTIRI = 2357; public static final int SARO = 2358; public static final int GUNSLIK = 2359; public static final int WEMUND = 2360; public static final int RANDIVOR = 2361; public static final int HERVI = 2362; public static final int NOLAR = 2363; public static final int GULLDAMAR = 2364; public static final int TATI = 2365; public static final int AGMUNDI = 2366; public static final int VERMUNDI = 2367; public static final int BANKER_2368 = 2368; public static final int BANKER_2369 = 2369; public static final int LIBRARIAN = 2370; public static final int ASSISTANT = 2371; public static final int CUSTOMER = 2372; public static final int CUSTOMER_2373 = 2373; public static final int DROMUND = 2374; public static final int RIND_THE_GARDENER = 2375; public static final int FACTORY_MANAGER = 2376; public static final int FACTORY_WORKER = 2377; public static final int FACTORY_WORKER_2378 = 2378; public static final int FACTORY_WORKER_2379 = 2379; public static final int FACTORY_WORKER_2380 = 2380; public static final int INN_KEEPER = 2381; public static final int INN_KEEPER_2382 = 2382; public static final int BARMAID = 2383; public static final int BARMAN_2384 = 2384; public static final int CART_CONDUCTOR = 2385; public static final int CART_CONDUCTOR_2386 = 2386; public static final int CART_CONDUCTOR_2387 = 2387; public static final int CART_CONDUCTOR_2388 = 2388; public static final int CART_CONDUCTOR_2389 = 2389; public static final int CART_CONDUCTOR_2390 = 2390; public static final int CART_CONDUCTOR_2391 = 2391; public static final int CART_CONDUCTOR_2392 = 2392; public static final int ROWDY_DWARF = 2393; public static final int HEGIR = 2394; public static final int HAERA = 2395; public static final int RUNVASTR = 2396; public static final int SUNE = 2397; public static final int BENTAMIR = 2398; public static final int ULIFED = 2399; public static final int REINALD = 2400; public static final int KARL = 2401; public static final int GAUSS = 2402; public static final int MYNDILL = 2403; public static final int KJUT = 2404; public static final int TOMBAR = 2405; public static final int ODMAR = 2406; public static final int AUDMANN = 2407; public static final int DRUNKEN_DWARF_2408 = 2408; public static final int DRUNKEN_DWARF_2409 = 2409; public static final int RED_AXE_DIRECTOR_2410 = 2410; public static final int RED_AXE_DIRECTOR_2411 = 2411; public static final int RED_AXE_HENCHMAN = 2412; public static final int RED_AXE_HENCHMAN_2413 = 2413; public static final int RED_AXE_HENCHMAN_2414 = 2414; public static final int COLONEL_GRIMSSON = 2415; public static final int COLONEL_GRIMSSON_2416 = 2416; public static final int OGRE_SHAMAN = 2417; public static final int OGRE_SHAMAN_2418 = 2418; public static final int GRUNSH = 2419; public static final int GNOME_EMISSARY = 2420; public static final int GNOME_COMPANION = 2421; public static final int GNOME_COMPANION_2422 = 2422; public static final int CHAOS_DWARF_2423 = 2423; public static final int GUNSLIK_2424 = 2424; public static final int NOLAR_2425 = 2425; public static final int FACTORY_WORKER_2426 = 2426; public static final int CART_CONDUCTOR_2427 = 2427; public static final int GAUSS_2428 = 2428; public static final int DRUNKEN_DWARF_2429 = 2429; public static final int ROWDY_DWARF_2430 = 2430; public static final int ULIFED_2431 = 2431; public static final int DWARVEN_BOATMAN = 2433; public static final int DWARVEN_MINER = 2434; public static final int DWARVEN_MINER_2435 = 2435; public static final int DWARVEN_MINER_2436 = 2436; public static final int DWARVEN_MINER_2437 = 2437; public static final int DWARVEN_MINER_2438 = 2438; public static final int DWARVEN_MINER_2439 = 2439; public static final int DWARVEN_MINER_2440 = 2440; public static final int DWARVEN_MINER_2441 = 2441; public static final int DWARVEN_MINER_2442 = 2442; public static final int DWARVEN_MINER_2443 = 2443; public static final int DWARVEN_MINER_2444 = 2444; public static final int DWARVEN_MINER_2445 = 2445; public static final int DWARVEN_MINER_2446 = 2446; public static final int DWARVEN_MINER_2447 = 2447; public static final int DWARVEN_MINER_2448 = 2448; public static final int BUINN = 2449; public static final int ANIMATED_BRONZE_ARMOUR = 2450; public static final int ANIMATED_IRON_ARMOUR = 2451; public static final int ANIMATED_STEEL_ARMOUR = 2452; public static final int ANIMATED_BLACK_ARMOUR = 2453; public static final int ANIMATED_MITHRIL_ARMOUR = 2454; public static final int ANIMATED_ADAMANT_ARMOUR = 2455; public static final int ANIMATED_RUNE_ARMOUR = 2456; public static final int GHOMMAL = 2457; public static final int HARRALLAK_MENAROUS = 2458; public static final int GAMFRED = 2459; public static final int AJJAT = 2460; public static final int KAMFREENA = 2461; public static final int SHANOMI = 2462; public static final int CYCLOPS_2463 = 2463; public static final int CYCLOPS_2464 = 2464; public static final int CYCLOPS_2465 = 2465; public static final int CYCLOPS_2466 = 2466; public static final int CYCLOPS_2467 = 2467; public static final int CYCLOPS_2468 = 2468; public static final int LIDIO = 2469; public static final int LILLY = 2470; public static final int ANTON = 2471; public static final int JADE = 2472; public static final int SLOANE = 2473; public static final int CATABLEPON = 2474; public static final int CATABLEPON_2475 = 2475; public static final int CATABLEPON_2476 = 2476; public static final int GIANT_SPIDER = 2477; public static final int SPIDER = 2478; public static final int SCORPION = 2479; public static final int SCORPION_2480 = 2480; public static final int MINOTAUR = 2481; public static final int MINOTAUR_2482 = 2482; public static final int MINOTAUR_2483 = 2483; public static final int GOBLIN_2484 = 2484; public static final int GOBLIN_2485 = 2485; public static final int GOBLIN_2486 = 2486; public static final int GOBLIN_2487 = 2487; public static final int GOBLIN_2488 = 2488; public static final int GOBLIN_2489 = 2489; public static final int WOLF_2490 = 2490; public static final int WOLF_2491 = 2491; public static final int RAT_2492 = 2492; public static final int GATE_OF_WAR = 2494; public static final int RICKETTY_DOOR = 2495; public static final int OOZING_BARRIER = 2496; public static final int PORTAL_OF_DEATH = 2497; public static final int FLESH_CRAWLER = 2498; public static final int FLESH_CRAWLER_2499 = 2499; public static final int FLESH_CRAWLER_2500 = 2500; public static final int ZOMBIE_2501 = 2501; public static final int ZOMBIE_2502 = 2502; public static final int ZOMBIE_2503 = 2503; public static final int ZOMBIE_2504 = 2504; public static final int ZOMBIE_2505 = 2505; public static final int ZOMBIE_2506 = 2506; public static final int ZOMBIE_2507 = 2507; public static final int ZOMBIE_2508 = 2508; public static final int ZOMBIE_2509 = 2509; public static final int GIANT_RAT = 2510; public static final int GIANT_RAT_2511 = 2511; public static final int GIANT_RAT_2512 = 2512; public static final int RAT_2513 = 2513; public static final int ANKOU = 2514; public static final int ANKOU_2515 = 2515; public static final int ANKOU_2516 = 2516; public static final int ANKOU_2517 = 2517; public static final int ANKOU_2518 = 2518; public static final int ANKOU_2519 = 2519; public static final int SKELETON_2520 = 2520; public static final int SKELETON_2521 = 2521; public static final int SKELETON_2522 = 2522; public static final int SKELETON_2523 = 2523; public static final int SKELETON_2524 = 2524; public static final int SKELETON_2525 = 2525; public static final int SKELETON_2526 = 2526; public static final int GHOST_2527 = 2527; public static final int GHOST_2528 = 2528; public static final int GHOST_2529 = 2529; public static final int GHOST_2530 = 2530; public static final int GHOST_2531 = 2531; public static final int GHOST_2532 = 2532; public static final int GHOST_2533 = 2533; public static final int GHOST_2534 = 2534; public static final int JOHANHUS_ULSBRECHT = 2535; public static final int HAM_GUARD = 2536; public static final int HAM_GUARD_2537 = 2537; public static final int HAM_GUARD_2538 = 2538; public static final int HAM_DEACON = 2539; public static final int HAM_MEMBER = 2540; public static final int HAM_MEMBER_2541 = 2541; public static final int HAM_MEMBER_2542 = 2542; public static final int HAM_MEMBER_2543 = 2543; public static final int MOUNTED_TERRORCHICK_GNOME = 2544; public static final int CAPTAIN_LAMDOO = 2545; public static final int TERRORCHICK_GNOME = 2546; public static final int GIANNE_JNR = 2547; public static final int TIMBLE = 2548; public static final int TAMBLE = 2549; public static final int SPANG = 2550; public static final int BRAMBICKLE = 2551; public static final int WINGSTONE = 2552; public static final int PENWIE = 2553; public static final int GENERIC_DIPLOMAT = 2554; public static final int AMBASSADOR_GIMBLEWAP = 2555; public static final int AMBASSADOR_SPANFIPPLE = 2556; public static final int AMBASSADOR_FERRNOOK = 2557; public static final int PROFESSOR_MANGLETHORP = 2558; public static final int DAMWIN = 2559; public static final int PROFESSOR_ONGLEWIP = 2560; public static final int PROFESSOR_IMBLEWYN = 2561; public static final int PERRDUR = 2562; public static final int DALILA = 2563; public static final int SORRN = 2564; public static final int MIMM = 2565; public static final int EEBEL = 2566; public static final int ERMIN = 2567; public static final int PORTOBELLO = 2568; public static final int CAPTAIN_NINTO = 2569; public static final int CAPTAIN_DAERKIN = 2570; public static final int MEEGLE = 2571; public static final int WURBEL = 2572; public static final int SARBLE = 2573; public static final int GUARD_VEMMELDO = 2574; public static final int BURKOR = 2575; public static final int FROONO = 2576; public static final int ABBOT_LANGLEY = 2577; public static final int BROTHER_JERED = 2578; public static final int MONK_2579 = 2579; public static final int MAGE_OF_ZAMORAK = 2580; public static final int MAGE_OF_ZAMORAK_2581 = 2581; public static final int MAGE_OF_ZAMORAK_2582 = 2582; public static final int DARK_MAGE = 2583; public static final int ABYSSAL_LEECH = 2584; public static final int ABYSSAL_GUARDIAN = 2585; public static final int ABYSSAL_WALKER = 2586; public static final int SKIPPY = 2587; public static final int SKIPPY_2588 = 2588; public static final int SKIPPY_2589 = 2589; public static final int SKIPPY_2590 = 2590; public static final int A_PILE_OF_BROKEN_GLASS = 2591; public static final int MOGRE = 2592; public static final int WEREWOLF = 2593; public static final int WEREWOLF_2594 = 2594; public static final int WEREWOLF_2595 = 2595; public static final int WEREWOLF_2596 = 2596; public static final int WEREWOLF_2597 = 2597; public static final int WEREWOLF_2598 = 2598; public static final int WEREWOLF_2599 = 2599; public static final int WEREWOLF_2600 = 2600; public static final int WEREWOLF_2601 = 2601; public static final int WEREWOLF_2602 = 2602; public static final int WEREWOLF_2603 = 2603; public static final int WEREWOLF_2604 = 2604; public static final int WEREWOLF_2605 = 2605; public static final int WEREWOLF_2606 = 2606; public static final int WEREWOLF_2607 = 2607; public static final int WEREWOLF_2608 = 2608; public static final int WEREWOLF_2609 = 2609; public static final int WEREWOLF_2610 = 2610; public static final int WEREWOLF_2611 = 2611; public static final int WEREWOLF_2612 = 2612; public static final int BORIS = 2613; public static final int IMRE = 2614; public static final int YURI = 2615; public static final int JOSEPH = 2616; public static final int NIKOLAI = 2617; public static final int EDUARD = 2618; public static final int LEV = 2619; public static final int GEORGY = 2620; public static final int SVETLANA = 2621; public static final int IRINA = 2622; public static final int ALEXIS = 2623; public static final int MILLA = 2624; public static final int GALINA = 2625; public static final int SOFIYA = 2626; public static final int KSENIA = 2627; public static final int YADVIGA = 2628; public static final int NIKITA = 2629; public static final int VERA = 2630; public static final int ZOJA = 2631; public static final int LILIYA = 2632; public static final int BANKER_2633 = 2633; public static final int MYRE_BLAMISH_SNAIL = 2634; public static final int BOB = 2635; public static final int BOB_2636 = 2636; public static final int SPHINX = 2637; public static final int NEITE = 2638; public static final int ROBERT_THE_STRONG = 2639; public static final int ODYSSEUS = 2640; public static final int DRAGONKIN = 2641; public static final int KING_BLACK_DRAGON_2642 = 2642; public static final int R4NG3RNO0B889 = 2643; public static final int LOVE_CATS = 2644; public static final int BLOOD_BLAMISH_SNAIL = 2645; public static final int OCHRE_BLAMISH_SNAIL = 2646; public static final int BRUISE_BLAMISH_SNAIL = 2647; public static final int BARK_BLAMISH_SNAIL = 2648; public static final int MYRE_BLAMISH_SNAIL_2649 = 2649; public static final int BLOOD_BLAMISH_SNAIL_2650 = 2650; public static final int OCHRE_BLAMISH_SNAIL_2651 = 2651; public static final int BRUISE_BLAMISH_SNAIL_2652 = 2652; public static final int FISHING_SPOT_2653 = 2653; public static final int FISHING_SPOT_2654 = 2654; public static final int FISHING_SPOT_2655 = 2655; public static final int ALUFT_GIANNE_SNR = 2656; public static final int GNOME_WAITER = 2657; public static final int HEAD_CHEF = 2658; public static final int PUREPKER895 = 2659; public static final int QUTIEDOLL = 2660; public static final int _1337SP34KR = 2661; public static final int ELFINLOCKS_2662 = 2662; public static final int ELSTAN = 2663; public static final int DANTAERA = 2664; public static final int KRAGEN = 2665; public static final int LYRA = 2666; public static final int FRANCIS = 2667; public static final int COMBAT_DUMMY = 2668; public static final int GARTH = 2669; public static final int ELLENA = 2670; public static final int SELENA = 2671; public static final int VASQUEN = 2672; public static final int RHONEN = 2673; public static final int DREVEN = 2674; public static final int TARIA = 2675; public static final int RHAZIEN = 2676; public static final int TORRELL = 2677; public static final int ALAIN = 2678; public static final int HESKEL = 2679; public static final int TREZNOR = 2680; public static final int FAYETH = 2681; public static final int BOLONGO = 2682; public static final int GILETH = 2683; public static final int FRIZZY_SKERNIP = 2684; public static final int YULF_SQUECKS = 2685; public static final int PRAISTAN_EBOLA = 2686; public static final int PRISSY_SCILLA = 2687; public static final int IMIAGO = 2688; public static final int LILIWEN = 2689; public static final int COOL_MOM227 = 2690; public static final int SHEEP_2691 = 2691; public static final int SHEEP_2692 = 2692; public static final int SHEEP_2693 = 2693; public static final int SHEEP_2694 = 2694; public static final int SHEEP_2695 = 2695; public static final int SHEEP_2696 = 2696; public static final int SHEEP_2697 = 2697; public static final int SHEEP_2698 = 2698; public static final int SHEEP_2699 = 2699; public static final int REACHER_2700 = 2700; public static final int REACHER_2701 = 2701; public static final int REACHER_2702 = 2702; public static final int REACH = 2703; public static final int REACH_2704 = 2704; public static final int REACH_2705 = 2705; public static final int REACH_2706 = 2706; public static final int REACH_2707 = 2707; public static final int REACH_2708 = 2708; public static final int REACHER_2709 = 2709; public static final int REACHER_2710 = 2710; public static final int REACHER_2711 = 2711; public static final int REACHER_2712 = 2712; public static final int WISE_OLD_MAN_2713 = 2713; public static final int COMBAT_STONE_2714 = 2714; public static final int COMBAT_STONE_2715 = 2715; public static final int COMBAT_STONE_2716 = 2716; public static final int COMBAT_STONE_2717 = 2717; public static final int COMBAT_STONE_2718 = 2718; public static final int COMBAT_STONE_2719 = 2719; public static final int COMBAT_STONE_2720 = 2720; public static final int COMBAT_STONE_2721 = 2721; public static final int COMBAT_STONE_2722 = 2722; public static final int COMBAT_STONE_2723 = 2723; public static final int COMBAT_STONE_2724 = 2724; public static final int COMBAT_STONE_2725 = 2725; public static final int COMBAT_STONE_2726 = 2726; public static final int COMBAT_STONE_2727 = 2727; public static final int COMBAT_STONE_2728 = 2728; public static final int COMBAT_STONE_2729 = 2729; public static final int COMBAT_STONE_2730 = 2730; public static final int COMBAT_STONE_2731 = 2731; public static final int COMBAT_STONE_2732 = 2732; public static final int COMBAT_STONE_2733 = 2733; public static final int COMBAT_STONE_2734 = 2734; public static final int COMBAT_STONE_2735 = 2735; public static final int COMBAT_STONE_2736 = 2736; public static final int COMBAT_STONE_2737 = 2737; public static final int COMBAT_STONE_2738 = 2738; public static final int COMBAT_STONE_2739 = 2739; public static final int COMBAT_STONE_2740 = 2740; public static final int COMBAT_STONE_2741 = 2741; public static final int COMBAT_STONE_2742 = 2742; public static final int COMBAT_STONE_2743 = 2743; public static final int COMBAT_STONE_2744 = 2744; public static final int COMBAT_STONE_2745 = 2745; public static final int COMBAT_STONE_2746 = 2746; public static final int COMBAT_STONE_2747 = 2747; public static final int COMBAT_STONE_2748 = 2748; public static final int COMBAT_STONE_2749 = 2749; public static final int COMBAT_STONE_2750 = 2750; public static final int COMBAT_STONE_2751 = 2751; public static final int COMBAT_STONE_2752 = 2752; public static final int COMBAT_STONE_2753 = 2753; public static final int COMBAT_STONE_2754 = 2754; public static final int COMBAT_STONE_2755 = 2755; public static final int COMBAT_STONE_2756 = 2756; public static final int COMBAT_STONE_2757 = 2757; public static final int COMBAT_STONE_2758 = 2758; public static final int COMBAT_STONE_2759 = 2759; public static final int COMBAT_STONE_2760 = 2760; public static final int COMBAT_STONE_2761 = 2761; public static final int COMBAT_STONE_2762 = 2762; public static final int COMBAT_STONE_2763 = 2763; public static final int COMBAT_STONE_2764 = 2764; public static final int COMBAT_STONE_2765 = 2765; public static final int COMBAT_STONE_2766 = 2766; public static final int COMBAT_STONE_2767 = 2767; public static final int COMBAT_STONE_2768 = 2768; public static final int COMBAT_STONE_2769 = 2769; public static final int COMBAT_STONE_2770 = 2770; public static final int COMBAT_STONE_2771 = 2771; public static final int COMBAT_STONE_2772 = 2772; public static final int COMBAT_STONE_2773 = 2773; public static final int COMBAT_STONE_2774 = 2774; public static final int COMBAT_STONE_2775 = 2775; public static final int COMBAT_STONE_2776 = 2776; public static final int COMBAT_STONE_2777 = 2777; public static final int COMBAT_STONE_2778 = 2778; public static final int CLOCKWORK_CAT_2782 = 2782; public static final int HIRKO = 2783; public static final int HOLOY = 2784; public static final int HURA = 2785; public static final int SHEEP_2786 = 2786; public static final int SHEEP_2787 = 2787; public static final int SHEEP_2788 = 2788; public static final int SHEEP_2789 = 2789; public static final int COW = 2790; public static final int COW_2791 = 2791; public static final int COW_CALF = 2792; public static final int COW_2793 = 2793; public static final int COW_CALF_2794 = 2794; public static final int COW_2795 = 2795; public static final int PIG = 2796; public static final int PIG_2797 = 2797; public static final int PIGLET = 2798; public static final int PIGLET_2799 = 2799; public static final int PIGLET_2800 = 2800; public static final int COW_CALF_2801 = 2801; public static final int SHEEPDOG = 2802; public static final int ROOSTER_2803 = 2803; public static final int CHICKEN_2804 = 2804; public static final int CHICKEN_2805 = 2805; public static final int CHICKEN_2806 = 2806; public static final int PIG_2807 = 2807; public static final int PIG_2808 = 2808; public static final int PIGLET_2809 = 2809; public static final int PIGLET_2810 = 2810; public static final int PIGLET_2811 = 2811; public static final int FATHER_AERECK = 2812; public static final int SHOP_KEEPER = 2813; public static final int SHOP_ASSISTANT = 2814; public static final int SHOP_KEEPER_2815 = 2815; public static final int SHOP_ASSISTANT_2816 = 2816; public static final int SHOP_KEEPER_2817 = 2817; public static final int SHOP_ASSISTANT_2818 = 2818; public static final int SHOP_KEEPER_2819 = 2819; public static final int SHOP_ASSISTANT_2820 = 2820; public static final int SHOP_KEEPER_2821 = 2821; public static final int SHOP_ASSISTANT_2822 = 2822; public static final int SHOP_KEEPER_2823 = 2823; public static final int SHOP_ASSISTANT_2824 = 2824; public static final int SHOP_KEEPER_2825 = 2825; public static final int SHOP_ASSISTANT_2826 = 2826; public static final int BAT = 2827; public static final int DRYAD = 2828; public static final int FAIRY_2829 = 2829; public static final int MYSTERIOUS_OLD_MAN = 2830; public static final int CHAIR = 2832; public static final int LIL_CREATOR = 2833; public static final int GIANT_BAT = 2834; public static final int CAMEL = 2835; public static final int GOLEM = 2836; public static final int UNICORN = 2837; public static final int GRIZZLY_BEAR = 2838; public static final int BLACK_BEAR = 2839; public static final int EARTH_WARRIOR = 2840; public static final int ICE_WARRIOR = 2841; public static final int ICE_WARRIOR_2842 = 2842; public static final int OTHERWORLDLY_BEING = 2843; public static final int MAGIC_AXE = 2844; public static final int SNAKE_2845 = 2845; public static final int SKAVID = 2846; public static final int YETI = 2847; public static final int MONKEY_2848 = 2848; public static final int BLACK_UNICORN = 2849; public static final int VEOS = 2850; public static final int ICE_WARRIOR_2851 = 2851; public static final int FLY_TRAP = 2852; public static final int SHADOW_WARRIOR = 2853; public static final int RAT_2854 = 2854; public static final int RAT_2855 = 2855; public static final int GIANT_RAT_2856 = 2856; public static final int GIANT_RAT_2857 = 2857; public static final int GIANT_RAT_2858 = 2858; public static final int GIANT_RAT_2859 = 2859; public static final int GIANT_RAT_2860 = 2860; public static final int GIANT_RAT_2861 = 2861; public static final int GIANT_RAT_2862 = 2862; public static final int GIANT_RAT_2863 = 2863; public static final int GIANT_RAT_2864 = 2864; public static final int DUNGEON_RAT = 2865; public static final int DUNGEON_RAT_2866 = 2866; public static final int DUNGEON_RAT_2867 = 2867; public static final int FAIRY_SHOP_KEEPER = 2868; public static final int FAIRY_SHOP_ASSISTANT = 2869; public static final int VALAINE = 2870; public static final int SCAVVO = 2871; public static final int PEKSA = 2872; public static final int SILK_TRADER = 2873; public static final int GEM_TRADER = 2874; public static final int ZEKE = 2875; public static final int LOUIE_LEGS = 2876; public static final int KARIM = 2877; public static final int RANAEL = 2878; public static final int DOMMIK = 2879; public static final int ZAFF = 2880; public static final int BARAEK = 2881; public static final int HORVIK = 2882; public static final int LOWE = 2883; public static final int SHOP_KEEPER_2884 = 2884; public static final int SHOP_ASSISTANT_2885 = 2885; public static final int ASYFF = 2887; public static final int SHOP_KEEPER_2888 = 2888; public static final int GRUM_2889 = 2889; public static final int WYDIN_2890 = 2890; public static final int GERRANT_2891 = 2891; public static final int BRIAN = 2892; public static final int JIMINUA = 2893; public static final int SHOP_KEEPER_2894 = 2894; public static final int COOK_2895 = 2895; public static final int COOK_2896 = 2896; public static final int BANKER_2897 = 2897; public static final int BANKER_2898 = 2898; public static final int IFFIE = 2899; public static final int ELSIE = 2900; public static final int CLEANER = 2901; public static final int STRAY_DOG = 2902; public static final int ORANGE_SALAMANDER = 2903; public static final int RED_SALAMANDER = 2904; public static final int BLACK_SALAMANDER = 2905; public static final int SWAMP_LIZARD = 2906; public static final int SABRETOOTHED_KYATT = 2907; public static final int SPINED_LARUPIA = 2908; public static final int HORNED_GRAAHK = 2909; public static final int CHINCHOMPA = 2910; public static final int CARNIVOROUS_CHINCHOMPA = 2911; public static final int BLACK_CHINCHOMPA = 2912; public static final int MASTER_FISHER = 2913; public static final int OTTO_GODBLESSED = 2914; public static final int OTTO_GODBLESSED_2915 = 2915; public static final int WATERFIEND = 2916; public static final int WATERFIEND_2917 = 2917; public static final int BRUTAL_GREEN_DRAGON = 2918; public static final int MITHRIL_DRAGON = 2919; public static final int CONFUSED_BARBARIAN = 2920; public static final int LOST_BARBARIAN = 2921; public static final int STRAY_DOG_2922 = 2922; public static final int BLAST_FURNACE_FOREMAN = 2923; public static final int TIN_ORE = 2924; public static final int COPPER_ORE = 2925; public static final int IRON_ORE = 2926; public static final int MITHRIL_ORE = 2927; public static final int ADAMANTITE_ORE = 2928; public static final int RUNITE_ORE = 2929; public static final int SILVER_ORE = 2930; public static final int GOLD_ORE = 2931; public static final int COAL = 2932; public static final int PERFECT_GOLD_ORE = 2933; public static final int NAIL_BEAST = 2946; public static final int NAIL_BEAST_2947 = 2947; public static final int NAIL_BEAST_2948 = 2948; public static final int SQUIRE_2949 = 2949; public static final int VOID_KNIGHT_2950 = 2950; public static final int VOID_KNIGHT_2951 = 2951; public static final int VOID_KNIGHT_2952 = 2952; public static final int VOID_KNIGHT_2953 = 2953; public static final int ZAMORAK_WIZARD = 2954; public static final int SARADOMIN_WIZARD = 2955; public static final int SPRING_ELEMENTAL = 2956; public static final int SPRING_ELEMENTAL_2957 = 2957; public static final int SPRING_ELEMENTAL_2958 = 2958; public static final int SPRING_ELEMENTAL_2959 = 2959; public static final int SPRING_ELEMENTAL_2960 = 2960; public static final int SPRING_ELEMENTAL_2961 = 2961; public static final int SPRING_ELEMENTAL_2962 = 2962; public static final int SPRING_ELEMENTAL_2963 = 2963; public static final int KING_AWOWOGEI = 2972; public static final int KING_AWOWOGEI_2974 = 2974; public static final int MIZARU = 2975; public static final int KIKAZARU = 2976; public static final int IWAZARU = 2977; public static final int BIG_SNAKE = 2978; public static final int MAWNIS_BUROWGAR_2980 = 2980; public static final int HONOUR_GUARD_2981 = 2981; public static final int HONOUR_GUARD_2982 = 2982; public static final int FRIDLEIF_SHIELDSON_2983 = 2983; public static final int THAKKRAD_SIGMUNDSON_2984 = 2984; public static final int VELORINA = 2985; public static final int NECROVARUS = 2986; public static final int GRAVINGAS = 2987; public static final int GHOST_DISCIPLE = 2988; public static final int AKHARANU = 2989; public static final int UNDEAD_COW = 2992; public static final int UNDEAD_CHICKEN = 2993; public static final int GIANT_LOBSTER = 2994; public static final int ROBIN = 2995; public static final int OLD_CRONE = 2996; public static final int OLD_MAN = 2997; public static final int GHOST_VILLAGER = 2998; public static final int TORTURED_SOUL = 2999; public static final int GHOST_SHOPKEEPER = 3000; public static final int GHOST_INNKEEPER = 3001; public static final int GHOST_FARMER = 3002; public static final int GHOST_BANKER = 3003; public static final int GHOST_SAILOR = 3004; public static final int GHOST_CAPTAIN = 3005; public static final int GHOST_CAPTAIN_3006 = 3006; public static final int GHOST_GUARD = 3007; public static final int GHOST_ = 3008; public static final int GHOST__3009 = 3009; public static final int GUARD_3010 = 3010; public static final int GUARD_3011 = 3011; public static final int TRAINEE_GUARD = 3012; public static final int CAPTAIN = 3013; public static final int MAN_3014 = 3014; public static final int WOMAN_3015 = 3015; public static final int SHADOW_SPIDER = 3016; public static final int GIANT_SPIDER_3017 = 3017; public static final int GIANT_SPIDER_3018 = 3018; public static final int SPIDER_3019 = 3019; public static final int JUNGLE_SPIDER = 3020; public static final int DEADLY_RED_SPIDER = 3021; public static final int ICE_SPIDER = 3022; public static final int POISON_SPIDER = 3023; public static final int SCORPION_3024 = 3024; public static final int POISON_SCORPION = 3025; public static final int PIT_SCORPION = 3026; public static final int KING_SCORPION = 3027; public static final int GOBLIN_3028 = 3028; public static final int GOBLIN_3029 = 3029; public static final int GOBLIN_3030 = 3030; public static final int GOBLIN_3031 = 3031; public static final int GOBLIN_3032 = 3032; public static final int GOBLIN_3033 = 3033; public static final int GOBLIN_3034 = 3034; public static final int GOBLIN_3035 = 3035; public static final int GOBLIN_3036 = 3036; public static final int GOBLIN_3037 = 3037; public static final int GOBLIN_3038 = 3038; public static final int GOBLIN_3039 = 3039; public static final int GOBLIN_3040 = 3040; public static final int GOBLIN_3041 = 3041; public static final int GOBLIN_3042 = 3042; public static final int GOBLIN_3043 = 3043; public static final int GOBLIN_3044 = 3044; public static final int GOBLIN_3045 = 3045; public static final int GOBLIN_3046 = 3046; public static final int GOBLIN_3047 = 3047; public static final int GOBLIN_3048 = 3048; public static final int HOBGOBLIN_3049 = 3049; public static final int HOBGOBLIN_3050 = 3050; public static final int GOBLIN_3051 = 3051; public static final int GOBLIN_3052 = 3052; public static final int GOBLIN_3053 = 3053; public static final int GOBLIN_3054 = 3054; public static final int BARBARIAN = 3055; public static final int BARBARIAN_3056 = 3056; public static final int BARBARIAN_3057 = 3057; public static final int BARBARIAN_3058 = 3058; public static final int BARBARIAN_3059 = 3059; public static final int BARBARIAN_3060 = 3060; public static final int BARBARIAN_3061 = 3061; public static final int BARBARIAN_3062 = 3062; public static final int HUNDING = 3063; public static final int BARBARIAN_3064 = 3064; public static final int BARBARIAN_3065 = 3065; public static final int BARBARIAN_3066 = 3066; public static final int BARBARIAN_3067 = 3067; public static final int BARBARIAN_3068 = 3068; public static final int BARBARIAN_3069 = 3069; public static final int BARBARIAN_3070 = 3070; public static final int BARBARIAN_3071 = 3071; public static final int BARBARIAN_3072 = 3072; public static final int GOBLIN_3073 = 3073; public static final int GOBLIN_3074 = 3074; public static final int GOBLIN_3075 = 3075; public static final int GOBLIN_3076 = 3076; public static final int PHOENIX = 3077; public static final int PHOENIX_3078 = 3078; public static final int PHOENIX_3079 = 3079; public static final int PHOENIX_3080 = 3080; public static final int PHOENIX_3081 = 3081; public static final int PHOENIX_3082 = 3082; public static final int PHOENIX_3083 = 3083; public static final int PHOENIX_3084 = 3084; public static final int PORTAL_3086 = 3086; public static final int PORTAL_3088 = 3088; public static final int BANKER_3089 = 3089; public static final int BANKER_3090 = 3090; public static final int BANKER_3091 = 3091; public static final int BANKER_3092 = 3092; public static final int BANKER_3093 = 3093; public static final int BANKER_3094 = 3094; public static final int CHIEF_SERVANT = 3095; public static final int TAXIDERMIST = 3096; public static final int ESTATE_AGENT = 3097; public static final int STONEMASON = 3098; public static final int HELLPUPPY_3099 = 3099; public static final int SIR_RENITEE = 3100; public static final int SAWMILL_OPERATOR = 3101; public static final int GARDEN_SUPPLIER = 3102; public static final int GARDEN_SUPPLIER_3103 = 3103; public static final int HANS = 3105; public static final int MAN_3106 = 3106; public static final int MAN_3107 = 3107; public static final int MAN_3108 = 3108; public static final int MAN_3109 = 3109; public static final int MAN_3110 = 3110; public static final int WOMAN_3111 = 3111; public static final int WOMAN_3112 = 3112; public static final int WOMAN_3113 = 3113; public static final int FARMER = 3114; public static final int FARID_MORRISANE_ORES_AND_BARS = 3115; public static final int TZKIH_3116 = 3116; public static final int TZKIH_3117 = 3117; public static final int TZKEK_3118 = 3118; public static final int TZKEK_3119 = 3119; public static final int TZKEK_3120 = 3120; public static final int TOKXIL_3121 = 3121; public static final int TOKXIL_3122 = 3122; public static final int YTMEJKOT = 3123; public static final int YTMEJKOT_3124 = 3124; public static final int KETZEK = 3125; public static final int KETZEK_3126 = 3126; public static final int TZTOKJAD = 3127; public static final int YTHURKOT = 3128; public static final int KRIL_TSUTSAROTH = 3129; public static final int TSTANON_KARLAK = 3130; public static final int ZAKLN_GRITCH = 3131; public static final int BALFRUG_KREEYATH = 3132; public static final int HELLHOUND_3133 = 3133; public static final int IMP = 3134; public static final int WEREWOLF_3135 = 3135; public static final int WEREWOLF_3136 = 3136; public static final int FERAL_VAMPYRE = 3137; public static final int BLOODVELD_3138 = 3138; public static final int PYREFIEND_3139 = 3139; public static final int ICEFIEND = 3140; public static final int GORAK_3141 = 3141; public static final int GNOME_COACH = 3142; public static final int GNOME_BALLER = 3143; public static final int GNOME_BALLER_3144 = 3144; public static final int GNOME_BALLER_3145 = 3145; public static final int GNOME_BALLER_3146 = 3146; public static final int GNOME_BALLER_3147 = 3147; public static final int GNOME_BALLER_3148 = 3148; public static final int GNOME_BALLER_3149 = 3149; public static final int GNOME_BALLER_3150 = 3150; public static final int GNOME_BALLER_3151 = 3151; public static final int GNOME_BALLER_3152 = 3152; public static final int GNOME_BALLER_3153 = 3153; public static final int GNOME_BALLER_3154 = 3154; public static final int GNOME_WINGER = 3155; public static final int GNOME_WINGER_3156 = 3156; public static final int GNOME_BALL_REFEREE = 3157; public static final int CHEERLEADER = 3158; public static final int SPIRITUAL_WARRIOR_3159 = 3159; public static final int SPIRITUAL_RANGER_3160 = 3160; public static final int SPIRITUAL_MAGE_3161 = 3161; public static final int KREEARRA = 3162; public static final int WINGMAN_SKREE = 3163; public static final int FLOCKLEADER_GEERIN = 3164; public static final int FLIGHT_KILISA = 3165; public static final int SPIRITUAL_WARRIOR_3166 = 3166; public static final int SPIRITUAL_RANGER_3167 = 3167; public static final int SPIRITUAL_MAGE_3168 = 3168; public static final int AVIANSIE = 3169; public static final int AVIANSIE_3170 = 3170; public static final int AVIANSIE_3171 = 3171; public static final int AVIANSIE_3172 = 3172; public static final int AVIANSIE_3173 = 3173; public static final int AVIANSIE_3174 = 3174; public static final int AVIANSIE_3175 = 3175; public static final int AVIANSIE_3176 = 3176; public static final int AVIANSIE_3177 = 3177; public static final int AVIANSIE_3178 = 3178; public static final int AVIANSIE_3179 = 3179; public static final int AVIANSIE_3180 = 3180; public static final int AVIANSIE_3181 = 3181; public static final int AVIANSIE_3182 = 3182; public static final int AVIANSIE_3183 = 3183; public static final int DAGANNOTH_SPAWN = 3184; public static final int DAGANNOTH_3185 = 3185; public static final int BRIAN_ORICHARD = 3189; public static final int ROGUE_GUARD = 3190; public static final int ROGUE_GUARD_3191 = 3191; public static final int ROGUE_GUARD_3192 = 3192; public static final int MARTIN_THWAIT = 3193; public static final int EMERALD_BENEDICT = 3194; public static final int SPIN_BLADES = 3195; public static final int SPIN_BLADES_3196 = 3196; public static final int CANDLE_MAKER = 3199; public static final int ARHEIN = 3200; public static final int JUKAT = 3201; public static final int LUNDERWIN = 3202; public static final int IRKSOL = 3203; public static final int FAIRY_3204 = 3204; public static final int ZAMBO = 3205; public static final int GEM_MERCHANT = 3207; public static final int BAKER = 3208; public static final int SPICE_SELLER = 3209; public static final int FUR_TRADER = 3210; public static final int SILK_MERCHANT = 3211; public static final int HICKTON = 3212; public static final int HARRY = 3213; public static final int CASSIE = 3214; public static final int FRINCOS = 3215; public static final int MELEE_COMBAT_TUTOR = 3216; public static final int RANGED_COMBAT_TUTOR = 3217; public static final int MAGIC_COMBAT_TUTOR = 3218; public static final int COOKING_TUTOR = 3219; public static final int CRAFTING_TUTOR = 3220; public static final int FISHING_TUTOR = 3221; public static final int MINING_TUTOR = 3222; public static final int PRAYER_TUTOR = 3223; public static final int SMITHING_APPRENTICE = 3224; public static final int MASTER_SMITHING_TUTOR = 3225; public static final int WOODSMAN_TUTOR = 3226; public static final int BANKER_TUTOR = 3227; public static final int ELLIS = 3231; public static final int WIZARD_JALARAST = 3232; public static final int LEECH = 3233; public static final int FERAL_VAMPYRE_3234 = 3234; public static final int BEE_KEEPER = 3235; public static final int MIST = 3236; public static final int FERAL_VAMPYRE_3237 = 3237; public static final int VAMPYRIC_HOUND = 3238; public static final int FERAL_VAMPYRE_3239 = 3239; public static final int TREE = 3240; public static final int BLANDEBIR = 3241; public static final int METARIALUS = 3242; public static final int FARMER_3243 = 3243; public static final int FARMER_3244 = 3244; public static final int FARMER_3245 = 3245; public static final int WIZARD_FRUMSCONE = 3246; public static final int WIZARD_AKUTHA = 3247; public static final int WIZARD_SININA = 3249; public static final int FARMER_3250 = 3250; public static final int FARMER_3251 = 3251; public static final int THIEF_3252 = 3252; public static final int THIEF_3253 = 3253; public static final int GUARD_3254 = 3254; public static final int TRAMP_3255 = 3255; public static final int BARBARIAN_3256 = 3256; public static final int WIZARD_3257 = 3257; public static final int DRUID = 3258; public static final int DRUID_3259 = 3259; public static final int WARRIOR_WOMAN = 3260; public static final int MAN_3261 = 3261; public static final int BARBARIAN_3262 = 3262; public static final int DRUNKEN_MAN = 3263; public static final int MAN_3264 = 3264; public static final int MAN_3265 = 3265; public static final int NORMAN = 3266; public static final int CECILIA = 3267; public static final int WOMAN_3268 = 3268; public static final int GUARD_3269 = 3269; public static final int GUARD_3270 = 3270; public static final int GUARD_3271 = 3271; public static final int GUARD_3272 = 3272; public static final int GUARD_3273 = 3273; public static final int GUARD_3274 = 3274; public static final int GARDENER = 3275; public static final int GARDENER_3276 = 3276; public static final int APPRENTICE_WORKMAN = 3277; public static final int WORKMAN_3278 = 3278; public static final int CUFFS = 3279; public static final int NARF = 3280; public static final int RUSTY = 3281; public static final int JEFF = 3282; public static final int GUARD_3283 = 3283; public static final int HENGEL = 3284; public static final int ANJA = 3285; public static final int HOBGOBLIN_3286 = 3286; public static final int HOBGOBLIN_3287 = 3287; public static final int HOBGOBLIN_3288 = 3288; public static final int HOBGOBLIN_3289 = 3289; public static final int FROG_3290 = 3290; public static final int POSTIE_PETE = 3291; public static final int AL_KHARID_WARRIOR = 3292; public static final int PALADIN_3293 = 3293; public static final int PALADIN_3294 = 3294; public static final int HERO = 3295; public static final int FORESTER = 3296; public static final int KNIGHT_OF_ARDOUGNE = 3297; public static final int MAN_3298 = 3298; public static final int WOMAN_3299 = 3299; public static final int KNIGHT_OF_ARDOUGNE_3300 = 3300; public static final int ARCHER_3301 = 3301; public static final int ZOO_KEEPER = 3302; public static final int CHUCK = 3303; public static final int BARMAN_3304 = 3304; public static final int MASTER_CHEF = 3305; public static final int HENJA = 3306; public static final int COMBAT_INSTRUCTOR = 3307; public static final int GIELINOR_GUIDE = 3308; public static final int MAGIC_INSTRUCTOR = 3309; public static final int ACCOUNT_GUIDE = 3310; public static final int MINING_INSTRUCTOR = 3311; public static final int QUEST_GUIDE = 3312; public static final int GIANT_RAT_3313 = 3313; public static final int GIANT_RAT_3314 = 3314; public static final int GIANT_RAT_3315 = 3315; public static final int CHICKEN_3316 = 3316; public static final int FISHING_SPOT_3317 = 3317; public static final int BANKER_3318 = 3318; public static final int BROTHER_BRACE = 3319; public static final int SKIPPY_3320 = 3320; public static final int LARXUS = 3321; public static final int MYSTERY_FIGURE = 3322; public static final int MYSTERY_FIGURE_3323 = 3323; public static final int MYSTERY_FIGURE_3324 = 3324; public static final int MYSTERY_FIGURE_3325 = 3325; public static final int MYSTERY_FIGURE_3326 = 3326; public static final int MYSTERY_FIGURE_3327 = 3327; public static final int EARTH_WARRIOR_CHAMPION = 3328; public static final int GIANT_CHAMPION = 3329; public static final int GHOUL_CHAMPION = 3330; public static final int MUBARIZ = 3331; public static final int TREES = 3332; public static final int TREES_3333 = 3333; public static final int CAVEMOUTH = 3334; public static final int BULLRUSH = 3335; public static final int BULLRUSH_3336 = 3336; public static final int CAVE_SCENERY = 3337; public static final int CAVE_SCENERY_3338 = 3338; public static final int CAVE_SCENERY_3339 = 3339; public static final int FADLI = 3340; public static final int AABLA = 3341; public static final int SABREEN = 3342; public static final int SURGEON_GENERAL_TAFANI = 3343; public static final int JARAAH = 3344; public static final int ZAHWA = 3345; public static final int IMA = 3346; public static final int SABEIL = 3347; public static final int JADID = 3348; public static final int DALAL = 3349; public static final int AFRAH = 3350; public static final int JEED = 3351; public static final int HAMID = 3352; public static final int GOBLIN_CHAMPION = 3353; public static final int HOBGOBLIN_CHAMPION = 3354; public static final int IMP_CHAMPION = 3355; public static final int JOGRE_CHAMPION = 3356; public static final int LESSER_DEMON_CHAMPION = 3357; public static final int SKELETON_CHAMPION = 3358; public static final int ZOMBIES_CHAMPION = 3359; public static final int LEON_DCOUR = 3360; public static final int GUARD_3361 = 3361; public static final int LITARA = 3362; public static final int STANKERS = 3364; public static final int ANGEL = 3369; public static final int ELEMENTAL_BALANCE = 3370; public static final int ELEMENTAL_BALANCE_3371 = 3371; public static final int ELEMENTAL_BALANCE_3372 = 3372; public static final int ELEMENTAL_BALANCE_3373 = 3373; public static final int ELEMENTAL_BALANCE_3374 = 3374; public static final int ELEMENTAL_BALANCE_3375 = 3375; public static final int ELEMENTAL_BALANCE_3376 = 3376; public static final int ELEMENTAL_BALANCE_3377 = 3377; public static final int ELEMENTAL_BALANCE_3378 = 3378; public static final int ELEMENTAL_BALANCE_3379 = 3379; public static final int ELEMENTAL_BALANCE_3380 = 3380; public static final int ELEMENTAL_BALANCE_3381 = 3381; public static final int ELEMENTAL_BALANCE_3382 = 3382; public static final int ELEMENTAL_BALANCE_3383 = 3383; public static final int ELEMENTAL_BALANCE_3384 = 3384; public static final int ELEMENTAL_BALANCE_3385 = 3385; public static final int ELEMENTAL_BALANCE_3386 = 3386; public static final int ELEMENTAL_BALANCE_3387 = 3387; public static final int OSMAN_3388 = 3388; public static final int PIRATE_PETE_3389 = 3389; public static final int MOUNTAIN_DWARF = 3390; public static final int GENERAL_WARTFACE_3391 = 3391; public static final int GENERAL_BENTNOZE_3392 = 3392; public static final int LUMBRIDGE_GUIDE_3393 = 3393; public static final int EVIL_DAVE_3394 = 3394; public static final int SIR_AMIK_VARZE_3395 = 3395; public static final int AWOWOGEI = 3396; public static final int AWOWOGEI_3397 = 3397; public static final int SKRACH_UGLOGWEE = 3398; public static final int CULINAROMANCER = 3400; public static final int ELEMENTAL_BALANCE_3401 = 3401; public static final int ELEMENTAL_BALANCE_3402 = 3402; public static final int ELEMENTAL_BALANCE_3403 = 3403; public static final int ELEMENTAL_BALANCE_3404 = 3404; public static final int ELEMENTAL_BALANCE_3405 = 3405; public static final int ELEMENTAL_BALANCE_3406 = 3406; public static final int ELEMENTAL_BALANCE_3407 = 3407; public static final int ELEMENTAL_BALANCE_3408 = 3408; public static final int ELEMENTAL_BALANCE_3409 = 3409; public static final int ELEMENTAL_BALANCE_3410 = 3410; public static final int ELEMENTAL_BALANCE_3411 = 3411; public static final int ELEMENTAL_BALANCE_3412 = 3412; public static final int KOFTIK = 3413; public static final int IDRIS = 3414; public static final int ESSYLLT = 3415; public static final int MORVRAN = 3416; public static final int ROD_FISHING_SPOT_3417 = 3417; public static final int ROD_FISHING_SPOT_3418 = 3418; public static final int FISHING_SPOT_3419 = 3419; public static final int RABBIT_3420 = 3420; public static final int RABBIT_3421 = 3421; public static final int RABBIT_3422 = 3422; public static final int GRIZZLY_BEAR_3423 = 3423; public static final int GRIZZLY_BEAR_CUB = 3424; public static final int GRIZZLY_BEAR_CUB_3425 = 3425; public static final int DIRE_WOLF = 3426; public static final int IORWERTH_ARCHER = 3428; public static final int IORWERTH_WARRIOR = 3429; public static final int ARIANWYN = 3432; public static final int TYRAS_GUARD_3433 = 3433; public static final int TYRAS_GUARD_3434 = 3434; public static final int TYRAS_GUARD_3436 = 3436; public static final int GENERAL_HINING = 3437; public static final int QUARTERMASTER = 3438; public static final int KINGS_MESSENGER = 3439; public static final int WILL_O_THE_WISP = 3440; public static final int WILL_O_THE_WISP_3441 = 3441; public static final int ALI_THE_DYER = 3442; public static final int LUCIEN = 3443; public static final int LUCIEN_3444 = 3444; public static final int GUARDIAN_OF_ARMADYL = 3445; public static final int GUARDIAN_OF_ARMADYL_3446 = 3446; public static final int WINELDA = 3447; public static final int FIRE_WARRIOR_OF_LESARKUS = 3448; public static final int SHADOW_HOUND = 3449; public static final int MYSTERIOUS_GHOST = 3450; public static final int MYSTERIOUS_GHOST_3451 = 3451; public static final int MYSTERIOUS_GHOST_3452 = 3452; public static final int MYSTERIOUS_GHOST_3453 = 3453; public static final int MYSTERIOUS_GHOST_3454 = 3454; public static final int MYSTERIOUS_GHOST_3455 = 3455; public static final int FAREED = 3456; public static final int ELEMENTAL_BALANCE_3457 = 3457; public static final int KAMIL = 3458; public static final int DESSOUS = 3459; public static final int DESSOUS_3460 = 3460; public static final int RUANTUN = 3461; public static final int CYRISUS = 3462; public static final int CYRISUS_3463 = 3463; public static final int CYRISUS_3464 = 3464; public static final int FALLEN_MAN = 3465; public static final int FALLEN_MAN_3466 = 3466; public static final int CYRISUS_3467 = 3467; public static final int CYRISUS_3468 = 3468; public static final int CYRISUS_3469 = 3469; public static final int CYRISUS_3470 = 3470; public static final int CYRISUS_3471 = 3471; public static final int BIRDSEYE_JACK = 3472; public static final int THE_INADEQUACY = 3473; public static final int THE_EVERLASTING = 3474; public static final int THE_UNTOUCHABLE = 3475; public static final int THE_ILLUSIVE = 3476; public static final int A_DOUBT = 3477; public static final int THE_ILLUSIVE_3478 = 3478; public static final int MORGAN = 3479; public static final int DR_HARLOW = 3480; public static final int COUNT_DRAYNOR = 3481; public static final int COUNT_DRAYNOR_3482 = 3482; public static final int WILL_O_THE_WISP_3483 = 3483; public static final int MONK_OF_ZAMORAK_3484 = 3484; public static final int MONK_OF_ZAMORAK_3485 = 3485; public static final int MONK_OF_ZAMORAK_3486 = 3486; public static final int JORRAL = 3490; public static final int MELINA = 3491; public static final int MELINA_3492 = 3492; public static final int DROALAK = 3493; public static final int DROALAK_3494 = 3494; public static final int DRON = 3495; public static final int BLANIN = 3496; public static final int GERTRUDES_CAT_3497 = 3497; public static final int KITTEN = 3498; public static final int CRATE = 3499; public static final int SHILOP = 3501; public static final int PHILOP = 3502; public static final int WILOUGH = 3503; public static final int KANEL = 3504; public static final int CIVILIAN = 3505; public static final int CIVILIAN_3506 = 3506; public static final int CIVILIAN_3507 = 3507; public static final int BOUNCER_3508 = 3508; public static final int BOUNCER_3509 = 3509; public static final int GENERAL_KHAZARD_3510 = 3510; public static final int SCOUT = 3511; public static final int SCOUT_3512 = 3512; public static final int SCOUT_3513 = 3513; public static final int SCOUT_3514 = 3514; public static final int SIN_SEER = 3515; public static final int GHOST_3516 = 3516; public static final int RENEGADE_KNIGHT = 3517; public static final int THRANTAX_THE_MIGHTY = 3518; public static final int SIR_LANCELOT = 3519; public static final int SIR_GAWAIN = 3520; public static final int SIR_KAY = 3521; public static final int SIR_BEDIVERE = 3522; public static final int SIR_TRISTRAM = 3523; public static final int SIR_PELLEAS = 3524; public static final int SIR_LUCAN = 3525; public static final int SIR_PALOMEDES = 3526; public static final int SIR_MORDRED = 3527; public static final int MORGAN_LE_FAYE = 3528; public static final int MERLIN = 3529; public static final int THE_LADY_OF_THE_LAKE = 3530; public static final int KING_ARTHUR = 3531; public static final int BEGGAR = 3532; public static final int ALI_MORRISANE = 3533; public static final int DRUNKEN_ALI = 3534; public static final int ALI_THE_BARMAN = 3535; public static final int ALI_THE_KEBAB_SELLER = 3536; public static final int MARKET_SELLER = 3537; public static final int ALI_THE_CAMEL_MAN = 3538; public static final int STREET_URCHIN = 3539; public static final int ALI_THE_MAYOR = 3540; public static final int ALI_THE_HAG = 3541; public static final int ALI_THE_SNAKE_CHARMER = 3542; public static final int ALI_THE_CAMEL = 3543; public static final int DESERT_SNAKE = 3544; public static final int SNAKE_3545 = 3545; public static final int BLACKJACK_SELLER = 3546; public static final int MENAPHITE_LEADER = 3547; public static final int ALI_THE_OPERATOR = 3548; public static final int MENAPHITE_THUG = 3549; public static final int MENAPHITE_THUG_3550 = 3550; public static final int TOUGH_GUY = 3551; public static final int VILLAGER = 3552; public static final int VILLAGER_3553 = 3553; public static final int VILLAGER_3554 = 3554; public static final int VILLAGER_3555 = 3555; public static final int VILLAGER_3556 = 3556; public static final int VILLAGER_3557 = 3557; public static final int VILLAGER_3558 = 3558; public static final int VILLAGER_3559 = 3559; public static final int VILLAGER_3560 = 3560; public static final int VERONICA = 3561; public static final int PROFESSOR_ODDENSTEIN = 3562; public static final int ERNEST = 3563; public static final int LIL_DESTRUCTOR = 3564; public static final int SKELETON_3565 = 3565; public static final int LIL_CREATOR_3566 = 3566; public static final int PENTYN = 3568; public static final int ARISTARCHUS = 3569; public static final int BONEGUARD = 3570; public static final int PILE_OF_BONES = 3571; public static final int DESERT_SPIRIT = 3572; public static final int CRUST_OF_ICE = 3573; public static final int FURNACE_GRATE = 3574; public static final int ENAKHRA = 3575; public static final int ENAKHRA_3576 = 3576; public static final int BONEGUARD_3577 = 3577; public static final int AKTHANAKOS = 3578; public static final int AKTHANAKOS_3579 = 3579; public static final int LAZIM = 3580; public static final int ENAKHRA_3581 = 3581; public static final int AKTHANAKOS_3582 = 3582; public static final int KNIGHT = 3583; public static final int SKELETON_3584 = 3584; public static final int EFFIGY = 3585; public static final int EFFIGY_3586 = 3586; public static final int BONAFIDO = 3587; public static final int HOMUNCULUS = 3588; public static final int HOMUNCULUS_3589 = 3589; public static final int HOMUNCULUS_3590 = 3590; public static final int CAGE = 3591; public static final int TRANSMUTE_THE_ALCHEMIST = 3592; public static final int TRANSMUTE_THE_ALCHEMIST_3593 = 3593; public static final int CURRENCY_THE_ALCHEMIST = 3594; public static final int CURRENCY_THE_ALCHEMIST_3595 = 3595; public static final int BLACKEYE = 3596; public static final int NO_FINGERS = 3597; public static final int GUMMY = 3598; public static final int THE_GUNS = 3599; public static final int FROGEEL = 3600; public static final int UNICOW = 3601; public static final int SPIDINE = 3602; public static final int SWORDCHICK = 3603; public static final int JUBSTER = 3604; public static final int NEWTROOST = 3605; public static final int BROTHER_KOJO = 3606; public static final int DUNGEON_RAT_3607 = 3607; public static final int DUNGEON_RAT_3608 = 3608; public static final int DUNGEON_RAT_3609 = 3609; public static final int MINE_CART = 3610; public static final int ZEALOT = 3611; public static final int POSSESSED_PICKAXE = 3612; public static final int IRON_PICKAXE = 3613; public static final int CORPSE = 3614; public static final int SKELETAL_MINER = 3615; public static final int TREUS_DAYTH = 3616; public static final int GHOST_3617 = 3617; public static final int LOADING_CRANE = 3618; public static final int INNOCENTLOOKING_KEY = 3619; public static final int MINE_CART_3620 = 3620; public static final int MINE_CART_3621 = 3621; public static final int MINE_CART_3622 = 3622; public static final int MINE_CART_3623 = 3623; public static final int MINE_CART_3624 = 3624; public static final int GHOST_3625 = 3625; public static final int HAZE = 3626; public static final int MISCHIEVOUS_GHOST = 3627; public static final int DIGSITE_WORKMAN = 3628; public static final int DOUG_DEEPING = 3629; public static final int DIGSITE_WORKMAN_3630 = 3630; public static final int DIGSITE_WORKMAN_3631 = 3631; public static final int STUDENT = 3632; public static final int STUDENT_3633 = 3633; public static final int STUDENT_3634 = 3634; public static final int EXAMINER = 3635; public static final int EXAMINER_3636 = 3636; public static final int EXAMINER_3637 = 3637; public static final int RESEARCHER = 3638; public static final int ARCHAEOLOGICAL_EXPERT = 3639; public static final int PANNING_GUIDE = 3640; public static final int NICK = 3641; public static final int NISHA = 3642; public static final int REDBEARD_FRANK = 3643; public static final int CAPTAIN_TOBIAS = 3644; public static final int SEAMAN_LORRIS = 3645; public static final int SEAMAN_THRESNOR = 3646; public static final int LUTHAS = 3647; public static final int CUSTOMS_OFFICER = 3648; public static final int TOY_SOLDIER = 3649; public static final int GARDENER_3651 = 3651; public static final int MAN_3652 = 3652; public static final int LUMBERJACK_LEIF = 3653; public static final int MINER_MAGNUS = 3654; public static final int FISHERMAN_FRODI = 3655; public static final int GARDENER_GUNNHILD = 3656; public static final int FISHING_SPOT_3657 = 3657; public static final int CARPENTER_KJALLAK = 3658; public static final int FARMER_FROMUND = 3659; public static final int REACHER_3660 = 3660; public static final int CHICKEN_3661 = 3661; public static final int CHICKEN_3662 = 3662; public static final int ROOSTER_3663 = 3663; public static final int RABBIT_3664 = 3664; public static final int RABBIT_3665 = 3665; public static final int PRINCE_BRAND = 3666; public static final int PRINCESS_ASTRID = 3667; public static final int KING_VARGAS = 3668; public static final int GUARD_3669 = 3669; public static final int DERRIK = 3671; public static final int FARMER_3672 = 3672; public static final int FLOWER_GIRL = 3673; public static final int RAGNAR_3674 = 3674; public static final int EINAR = 3675; public static final int ALRIK = 3676; public static final int THORHILD = 3677; public static final int HALLA_3678 = 3678; public static final int YRSA = 3679; public static final int SAILOR = 3680; public static final int RANNVEIG = 3681; public static final int THORA_3682 = 3682; public static final int VALGERD = 3683; public static final int SKRAELING_3684 = 3684; public static final int BRODDI = 3685; public static final int SKRAELING_3686 = 3686; public static final int RAGNVALD = 3687; public static final int FISHMONGER_3688 = 3688; public static final int GREENGROCER_3689 = 3689; public static final int VAMPYRE_JUVINATE = 3690; public static final int VAMPYRE_JUVINATE_3691 = 3691; public static final int VAMPYRE_JUVENILE = 3692; public static final int VAMPYRE_JUVENILE_3693 = 3693; public static final int VAMPYRE_JUVINATE_3694 = 3694; public static final int VAMPYRE_JUVINATE_3695 = 3695; public static final int VAMPYRE_JUVENILE_3696 = 3696; public static final int VAMPYRE_JUVENILE_3697 = 3697; public static final int VAMPYRE_JUVINATE_3698 = 3698; public static final int VAMPYRE_JUVINATE_3699 = 3699; public static final int VAMPYRE_JUVINATE_3700 = 3700; public static final int FORMER_VAMPYRE = 3701; public static final int FORMER_VAMPYRE_3702 = 3702; public static final int FORMER_VAMPYRE_3703 = 3703; public static final int FORMER_VAMPYRE_3704 = 3704; public static final int FORMER_VAMPYRE_3705 = 3705; public static final int FORMER_VAMPYRE_3706 = 3706; public static final int FERAL_VAMPYRE_3707 = 3707; public static final int FERAL_VAMPYRE_3708 = 3708; public static final int VYREWATCH = 3709; public static final int VYREWATCH_3710 = 3710; public static final int VYREWATCH_3711 = 3711; public static final int VYREWATCH_3712 = 3712; public static final int VYREWATCH_3713 = 3713; public static final int VYREWATCH_3714 = 3714; public static final int VYREWATCH_3715 = 3715; public static final int VYREWATCH_3716 = 3716; public static final int VYREWATCH_3717 = 3717; public static final int VYREWATCH_3718 = 3718; public static final int VYREWATCH_3719 = 3719; public static final int VYREWATCH_3720 = 3720; public static final int VYREWATCH_3721 = 3721; public static final int VYREWATCH_3722 = 3722; public static final int VYREWATCH_3723 = 3723; public static final int VYREWATCH_3724 = 3724; public static final int VYREWATCH_3725 = 3725; public static final int VYREWATCH_3726 = 3726; public static final int VYREWATCH_3727 = 3727; public static final int VYREWATCH_3728 = 3728; public static final int VYREWATCH_3729 = 3729; public static final int VYREWATCH_3730 = 3730; public static final int VYREWATCH_3731 = 3731; public static final int VYREWATCH_3732 = 3732; public static final int VANSTROM_KLAUSE = 3733; public static final int VANSTROM_KLAUSE_3734 = 3734; public static final int VANSTROM_KLAUSE_3735 = 3735; public static final int VANSTROM_KLAUSE_3736 = 3736; public static final int VANSTROM_KLAUSE_3737 = 3737; public static final int VANSTROM_KLAUSE_3738 = 3738; public static final int VANSTROM_KLAUSE_3739 = 3739; public static final int VANESCULA_DRAKAN = 3740; public static final int VANESCULA_DRAKAN_3741 = 3741; public static final int VANESCULA_DRAKAN_3742 = 3742; public static final int VANESCULA_DRAKAN_3743 = 3743; public static final int RANIS_DRAKAN = 3744; public static final int RANIS_DRAKAN_3745 = 3745; public static final int RANIS_DRAKAN_3746 = 3746; public static final int RANIS_DRAKAN_3747 = 3747; public static final int VYREWATCH_3748 = 3748; public static final int VYREWATCH_3749 = 3749; public static final int VYREWATCH_3750 = 3750; public static final int VYREWATCH_3751 = 3751; public static final int VYREWATCH_3752 = 3752; public static final int VYREWATCH_3753 = 3753; public static final int VYREWATCH_3754 = 3754; public static final int VYREWATCH_3755 = 3755; public static final int VYREWATCH_3756 = 3756; public static final int VYREWATCH_3757 = 3757; public static final int VYREWATCH_3758 = 3758; public static final int VYREWATCH_3759 = 3759; public static final int VYREWATCH_3760 = 3760; public static final int VYREWATCH_3761 = 3761; public static final int VYREWATCH_3762 = 3762; public static final int VYREWATCH_3763 = 3763; public static final int FLYING_FEMALE_VAMPIRE = 3764; public static final int FLYING_FEMALE_VAMPIRE_3765 = 3765; public static final int FLYING_FEMALE_VAMPIRE_3766 = 3766; public static final int FLYING_FEMALE_VAMPIRE_3767 = 3767; public static final int VYREWATCH_3768 = 3768; public static final int VYREWATCH_3769 = 3769; public static final int VYREWATCH_3770 = 3770; public static final int VYREWATCH_3771 = 3771; public static final int OLD_MAN_RAL = 3772; public static final int AEONISIG_RAISPHER = 3774; public static final int SAFALAAN_HALLOW = 3775; public static final int SARIUS_GUILE = 3776; public static final int ELEMENTAL_BALANCE_3777 = 3777; public static final int SARIUS_GUILE_3778 = 3778; public static final int TRADER_SVEN = 3779; public static final int MEIYERDITCH_CITIZEN = 3780; public static final int MEIYERDITCH_CITIZEN_3781 = 3781; public static final int MEIYERDITCH_CITIZEN_3782 = 3782; public static final int MEIYERDITCH_CITIZEN_3783 = 3783; public static final int MEIYERDITCH_CITIZEN_3784 = 3784; public static final int MEIYERDITCH_CITIZEN_3785 = 3785; public static final int MEIYERDITCH_CITIZEN_3786 = 3786; public static final int MEIYERDITCH_CITIZEN_3787 = 3787; public static final int MEIYERDITCH_CITIZEN_3788 = 3788; public static final int MEIYERDITCH_CITIZEN_3789 = 3789; public static final int MEIYERDITCH_CITIZEN_3790 = 3790; public static final int MEIYERDITCH_CITIZEN_3791 = 3791; public static final int MEIYERDITCH_CITIZEN_3792 = 3792; public static final int MEIYERDITCH_CITIZEN_3793 = 3793; public static final int MEIYERDITCH_CITIZEN_3794 = 3794; public static final int MEIYERDITCH_CITIZEN_3795 = 3795; public static final int MEIYERDITCH_CITIZEN_3796 = 3796; public static final int MEIYERDITCH_CITIZEN_3797 = 3797; public static final int MEIYERDITCH_CITIZEN_3798 = 3798; public static final int MEIYERDITCH_CITIZEN_3799 = 3799; public static final int MEIYERDITCH_CITIZEN_3800 = 3800; public static final int MEIYERDITCH_CITIZEN_3801 = 3801; public static final int MEIYERDITCH_CITIZEN_3802 = 3802; public static final int MEIYERDITCH_CITIZEN_3803 = 3803; public static final int MEIYERDITCH_CITIZEN_3804 = 3804; public static final int MEIYERDITCH_CITIZEN_3805 = 3805; public static final int MEIYERDITCH_CITIZEN_3806 = 3806; public static final int MEIYERDITCH_CITIZEN_3807 = 3807; public static final int MEIYERDITCH_CITIZEN_3808 = 3808; public static final int CHILD_3809 = 3809; public static final int CHILD_3810 = 3810; public static final int CHILD_3811 = 3811; public static final int CHILD_3812 = 3812; public static final int CHILD_3813 = 3813; public static final int CHILD_3814 = 3814; public static final int CHILD_3815 = 3815; public static final int CHILD_3816 = 3816; public static final int CHILD_3817 = 3817; public static final int CHILD_3818 = 3818; public static final int MEIYERDITCH_MINER = 3819; public static final int MEIYERDITCH_MINER_3820 = 3820; public static final int MEIYERDITCH_MINER_3821 = 3821; public static final int MEIYERDITCH_MINER_3822 = 3822; public static final int MEIYERDITCH_MINER_3823 = 3823; public static final int MEIYERDITCH_MINER_3824 = 3824; public static final int SHADOWY_FIGURE = 3825; public static final int SHADOWY_FIGURE_3826 = 3826; public static final int SHADOWY_FIGURE_3827 = 3827; public static final int STRAY_DOG_3829 = 3829; public static final int STRAY_DOG_3830 = 3830; public static final int CAT_3831 = 3831; public static final int CAT_3832 = 3832; public static final int BOAT = 3833; public static final int BOAT_3834 = 3834; public static final int ONEIROMANCER = 3835; public static final int HOUSE = 3836; public static final int BABA_YAGA = 3837; public static final int PAULINE_POLARIS = 3838; public static final int METEORA = 3839; public static final int MELANA_MOONLANDER = 3840; public static final int SELENE = 3841; public static final int RIMAE_SIRSALIS = 3842; public static final int SIRSAL_BANKER = 3843; public static final int CLAN_GUARD = 3844; public static final int ENCHANTED_BROOM = 3845; public static final int ENCHANTED_BROOM_3846 = 3846; public static final int ENCHANTED_BROOM_3847 = 3847; public static final int ENCHANTED_BUCKET = 3848; public static final int ENCHANTED_BUCKET_3849 = 3849; public static final int BOUQUET_MAC_HYACINTH = 3850; public static final int MOSS_GIANT_3851 = 3851; public static final int MOSS_GIANT_3852 = 3852; public static final int PARROT_3853 = 3853; public static final int LOKAR_SEARUNNER = 3855; public static final int CABIN_BOY = 3856; public static final int BEEFY_BURNS = 3858; public static final int EAGLEEYE_SHULTZ = 3859; public static final int FIRST_MATE_DAVEYBOY = 3860; public static final int BIRDSEYE_JACK_3861 = 3861; public static final int PICARRON_PETE = 3862; public static final int JAKE = 3863; public static final int BEDREAD_THE_BOLD = 3864; public static final int WILSON = 3865; public static final int TOMMY_2TIMES = 3866; public static final int MURKY_PAT = 3867; public static final int JACK_SAILS = 3868; public static final int PALMER = 3869; public static final int BETTY_BBOPPIN = 3870; public static final int BEEDYEYE_JONES = 3871; public static final int JENNY_BLADE = 3872; public static final int LECHEROUS_LEE = 3873; public static final int STICKY_SANDERS = 3874; public static final int JEX = 3875; public static final int MAISA = 3876; public static final int OSMAN_3877 = 3877; public static final int OSMAN_3878 = 3878; public static final int OSMAN_3879 = 3879; public static final int OSMAN_3880 = 3880; public static final int SOPHANEM_GUARD = 3881; public static final int SOPHANEM_GUARD_3882 = 3882; public static final int SOPHANEM_GUARD_3883 = 3883; public static final int SOPHANEM_GUARD_3884 = 3884; public static final int BANKER_3887 = 3887; public static final int BANKER_3888 = 3888; public static final int STONEMASON_3889 = 3889; public static final int NATHIFA = 3890; public static final int URBI = 3891; public static final int JAMILA = 3892; public static final int DORIC = 3893; public static final int SIGMUND_THE_MERCHANT = 3894; public static final int PEER_THE_SEER = 3895; public static final int THORVALD_THE_WARRIOR = 3896; public static final int KOSCHEI_THE_DEATHLESS = 3897; public static final int KOSCHEI_THE_DEATHLESS_3898 = 3898; public static final int KOSCHEI_THE_DEATHLESS_3899 = 3899; public static final int KOSCHEI_THE_DEATHLESS_3900 = 3900; public static final int FOX = 3901; public static final int BUNNY = 3902; public static final int BUNNY_3903 = 3903; public static final int GULL_3904 = 3904; public static final int GULL_3905 = 3905; public static final int GULL_3906 = 3906; public static final int GULL_3907 = 3907; public static final int BEAR_CUB = 3908; public static final int BEAR_CUB_3909 = 3909; public static final int UNICORN_FOAL = 3910; public static final int BLACK_UNICORN_FOAL = 3911; public static final int WOLF_3912 = 3912; public static final int FISHING_SPOT_3913 = 3913; public static final int FISHING_SPOT_3914 = 3914; public static final int FISHING_SPOT_3915 = 3915; public static final int BJORN = 3916; public static final int ELDGRIM = 3917; public static final int PRINCE_BRAND_3918 = 3918; public static final int PRINCESS_ASTRID_3919 = 3919; public static final int MANNI_THE_REVELLER = 3920; public static final int COUNCIL_WORKMAN = 3921; public static final int THE_DRAUGEN = 3922; public static final int BUTTERFLY_3923 = 3923; public static final int SIGLI_THE_HUNTSMAN = 3924; public static final int SWENSEN_THE_NAVIGATOR = 3925; public static final int GUARD_3928 = 3928; public static final int GUARD_3929 = 3929; public static final int TOWN_GUARD = 3930; public static final int TOWN_GUARD_3931 = 3931; public static final int THORA_THE_BARKEEP = 3932; public static final int YRSA_3933 = 3933; public static final int FISHERMAN = 3934; public static final int SKULGRIMEN = 3935; public static final int SAILOR_3936 = 3936; public static final int AGNAR = 3937; public static final int FREIDIR = 3938; public static final int BORROKAR = 3939; public static final int LANZIG = 3940; public static final int PONTAK = 3941; public static final int FREYGERD_3942 = 3942; public static final int LENSA_3943 = 3943; public static final int JENNELLA = 3944; public static final int SASSILIK_3945 = 3945; public static final int INGA = 3946; public static final int FISH_MONGER = 3947; public static final int FUR_TRADER_3948 = 3948; public static final int MARKET_GUARD_3949 = 3949; public static final int WARRIOR_3950 = 3950; public static final int LEGENDS_GUARD = 3951; public static final int LEGENDS_GUARD_3952 = 3952; public static final int RADIMUS_ERKLE = 3953; public static final int JUNGLE_FORESTER = 3954; public static final int JUNGLE_FORESTER_3955 = 3955; public static final int GUJUO = 3956; public static final int UNGADULU = 3957; public static final int UNGADULU_3958 = 3958; public static final int JUNGLE_SAVAGE = 3959; public static final int FIONELLA = 3960; public static final int SIEGFRIED_ERKLE = 3961; public static final int NEZIKCHENED = 3962; public static final int VIYELDI = 3963; public static final int SAN_TOJALON = 3964; public static final int IRVIG_SENAY = 3965; public static final int RANALPH_DEVERE = 3966; public static final int BOULDER_3967 = 3967; public static final int ECHNED_ZEKIN = 3968; public static final int ZOMBIE_RAT = 3969; public static final int ZOMBIE_RAT_3970 = 3970; public static final int ZOMBIE_RAT_3971 = 3971; public static final int SKELETON_3972 = 3972; public static final int SKELETON_3973 = 3973; public static final int SKELETON_3974 = 3974; public static final int GHOST_3975 = 3975; public static final int GHOST_3976 = 3976; public static final int GHOST_3977 = 3977; public static final int GHOST_3978 = 3978; public static final int GHOST_3979 = 3979; public static final int ZOMBIE_3980 = 3980; public static final int ZOMBIE_3981 = 3981; public static final int LESSER_DEMON_3982 = 3982; public static final int DOCTOR_ORBON = 3984; public static final int FARMER_BRUMTY = 3985; public static final int RED_SHEEP = 3986; public static final int GREEN_SHEEP = 3987; public static final int BLUE_SHEEP = 3988; public static final int YELLOW_SHEEP = 3989; public static final int BOY = 3994; public static final int NORA_T_HAGG = 3995; public static final int WITCHS_EXPERIMENT = 3996; public static final int WITCHS_EXPERIMENT_SECOND_FORM = 3997; public static final int WITCHS_EXPERIMENT_THIRD_FORM = 3998; public static final int WITCHS_EXPERIMENT_FOURTH_FORM = 3999; public static final int MOUSE = 4000; public static final int CHOMPY_CHICK = 4001; public static final int CHOMPY_CHICK_4002 = 4002; public static final int SHADOW_4004 = 4004; public static final int DARK_BEAST = 4005; public static final int THORGEL = 4010; public static final int BILL_TEACH = 4011; public static final int BILL_TEACH_4012 = 4012; public static final int BILL_TEACH_4014 = 4014; public static final int BILL_TEACH_4015 = 4015; public static final int BILL_TEACH_4016 = 4016; public static final int CHARLEY = 4017; public static final int SMITH = 4018; public static final int JOE_4019 = 4019; public static final int MAMA = 4020; public static final int MAMA_4021 = 4021; public static final int MIKE = 4022; public static final int PIRATE_4023 = 4023; public static final int PIRATE_4024 = 4024; public static final int PIRATE_4025 = 4025; public static final int PIRATE_4026 = 4026; public static final int PIRATE_4027 = 4027; public static final int PIRATE_4028 = 4028; public static final int PIRATE_4029 = 4029; public static final int PIRATE_4030 = 4030; public static final int PIRATE_4031 = 4031; public static final int PIRATE_4032 = 4032; public static final int PIRATE_4033 = 4033; public static final int PIRATE_4034 = 4034; public static final int PIRATE_4035 = 4035; public static final int PIRATE_4036 = 4036; public static final int PIRATE_4037 = 4037; public static final int PIRATE_4038 = 4038; public static final int PIRATE_4039 = 4039; public static final int PIRATE_4040 = 4040; public static final int PIRATE_4041 = 4041; public static final int PIRATE_4042 = 4042; public static final int PIRATE_4043 = 4043; public static final int PIRATE_4044 = 4044; public static final int PIRATE_4045 = 4045; public static final int PIRATE_4046 = 4046; public static final int PIRATE_4047 = 4047; public static final int PIRATE_4048 = 4048; public static final int PIRATE_4049 = 4049; public static final int PIRATE_4050 = 4050; public static final int PIRATE_4051 = 4051; public static final int PIRATE_4052 = 4052; public static final int GULL_4053 = 4053; public static final int BANKER_4054 = 4054; public static final int BANKER_4055 = 4055; public static final int GRAIL_MAIDEN = 4056; public static final int SIR_PERCIVAL = 4057; public static final int KING_PERCIVAL = 4058; public static final int MERLIN_4059 = 4059; public static final int PEASANT = 4060; public static final int PEASANT_4061 = 4061; public static final int HIGH_PRIEST = 4062; public static final int CRONE = 4063; public static final int GALAHAD = 4064; public static final int FISHERMAN_4065 = 4065; public static final int THE_FISHER_KING = 4066; public static final int BLACK_KNIGHT_TITAN = 4067; public static final int MONK_4068 = 4068; public static final int BONZO = 4069; public static final int SINISTER_STRANGER = 4070; public static final int SINISTER_STRANGER_4071 = 4071; public static final int MORRIS = 4072; public static final int BIG_DAVE = 4073; public static final int JOSHUA = 4074; public static final int GRANDPA_JACK = 4075; public static final int FORESTER_4076 = 4076; public static final int AUSTRI = 4077; public static final int VESTRI = 4078; public static final int FISHING_SPOT_4079 = 4079; public static final int FISHING_SPOT_4080 = 4080; public static final int FISHING_SPOT_4081 = 4081; public static final int FISHING_SPOT_4082 = 4082; public static final int DENULTH = 4083; public static final int SERGEANT = 4084; public static final int SERGEANT_4085 = 4085; public static final int SOLDIER = 4086; public static final int SOLDIER_4087 = 4087; public static final int SOLDIER_4088 = 4088; public static final int SOLDIER_4089 = 4089; public static final int SOLDIER_4090 = 4090; public static final int SOLDIER_4091 = 4091; public static final int SOLDIER_4092 = 4092; public static final int SABA = 4093; public static final int TENZING = 4094; public static final int EADBURG = 4095; public static final int ARCHER_4096 = 4096; public static final int ARCHER_4097 = 4097; public static final int ARCHER_4098 = 4098; public static final int GUARD_4099 = 4099; public static final int GUARD_4100 = 4100; public static final int HAROLD = 4101; public static final int TOSTIG = 4102; public static final int EOHRIC = 4103; public static final int SERVANT_4104 = 4104; public static final int DUNSTAN = 4105; public static final int WISTAN = 4106; public static final int BREOCA = 4107; public static final int OCGA = 4108; public static final int PENDA = 4109; public static final int HYGD = 4110; public static final int CEOLBURG = 4111; public static final int HILD_4112 = 4112; public static final int WHITE_KNIGHT_4114 = 4114; public static final int FAREED_HARD = 4115; public static final int BILLY = 4116; public static final int MOUNTAIN_GOAT_4117 = 4117; public static final int EADGAR = 4118; public static final int GODRIC = 4119; public static final int TROLL_GENERAL = 4120; public static final int TROLL_GENERAL_4121 = 4121; public static final int TROLL_GENERAL_4122 = 4122; public static final int TROLL_SPECTATOR = 4123; public static final int TROLL_SPECTATOR_4124 = 4124; public static final int TROLL_SPECTATOR_4125 = 4125; public static final int TROLL_SPECTATOR_4126 = 4126; public static final int TROLL_SPECTATOR_4127 = 4127; public static final int TROLL_SPECTATOR_4128 = 4128; public static final int TROLL_SPECTATOR_4129 = 4129; public static final int DAD = 4130; public static final int TWIG_4131 = 4131; public static final int BERRY = 4132; public static final int TWIG_4133 = 4133; public static final int BERRY_4134 = 4134; public static final int THROWER_TROLL_4135 = 4135; public static final int THROWER_TROLL_4136 = 4136; public static final int THROWER_TROLL_4137 = 4137; public static final int THROWER_TROLL_4138 = 4138; public static final int THROWER_TROLL_4139 = 4139; public static final int COOK_4140 = 4140; public static final int COOK_4141 = 4141; public static final int COOK_4142 = 4142; public static final int MOUNTAIN_TROLL_4143 = 4143; public static final int MUSHROOM = 4144; public static final int MOUNTAIN_GOAT_4145 = 4145; public static final int MOUNTAIN_GOAT_4146 = 4146; public static final int MOUNTAIN_GOAT_4147 = 4147; public static final int GUARD_4148 = 4148; public static final int GUARD_4149 = 4149; public static final int GUARD_4150 = 4150; public static final int GUARD_4151 = 4151; public static final int GUARD_4152 = 4152; public static final int GUARD_4153 = 4153; public static final int GUARD_4154 = 4154; public static final int GUARD_4155 = 4155; public static final int GUARD_4156 = 4156; public static final int BURNTMEAT = 4157; public static final int RAT_BURGISS = 4158; public static final int SUROK_MAGIS = 4159; public static final int SUROK_MAGIS_4160 = 4160; public static final int ZAFF_4161 = 4161; public static final int ANNA_JONES = 4162; public static final int KING_ROALD_4163 = 4163; public static final int MISHKALUN_DORN = 4164; public static final int DAKHTHOULAN_AEGIS = 4165; public static final int SILAS_DAHCSNU = 4166; public static final int OUTLAW = 4167; public static final int OUTLAW_4168 = 4168; public static final int OUTLAW_4169 = 4169; public static final int OUTLAW_4170 = 4170; public static final int OUTLAW_4171 = 4171; public static final int OUTLAW_4172 = 4172; public static final int OUTLAW_4173 = 4173; public static final int OUTLAW_4174 = 4174; public static final int OUTLAW_4175 = 4175; public static final int OUTLAW_4176 = 4176; public static final int MONKEY_4177 = 4177; public static final int BENCH = 4178; public static final int HADLEY = 4179; public static final int GERALD = 4180; public static final int ALMERA = 4181; public static final int HUDON = 4182; public static final int GOLRIE_4183 = 4183; public static final int CROCODILE = 4184; public static final int JACKAL = 4185; public static final int ODDSKULL = 4187; public static final int SCARAB_SWARM_4192 = 4192; public static final int WANDERER = 4193; public static final int WANDERER_4194 = 4194; public static final int APPARITION = 4195; public static final int APPARITION_4196 = 4196; public static final int APPARITION_4197 = 4197; public static final int APPARITION_4198 = 4198; public static final int ICTHLARIN = 4199; public static final int EMBALMER = 4202; public static final int CARPENTER = 4203; public static final int SIAMUN = 4205; public static final int HIGH_PRIEST_4206 = 4206; public static final int PRIEST_4207 = 4207; public static final int PRIEST_4208 = 4208; public static final int SPHINX_4209 = 4209; public static final int POSSESSED_PRIEST = 4210; public static final int DONOVAN_THE_FAMILY_HANDYMAN = 4212; public static final int PIERRE = 4213; public static final int HOBBES = 4214; public static final int LOUISA = 4215; public static final int MARY = 4216; public static final int STANFORD = 4217; public static final int GUARD_4218 = 4218; public static final int GOSSIP = 4219; public static final int ANNA_4220 = 4220; public static final int BOB_4221 = 4221; public static final int CAROL = 4222; public static final int DAVID_4223 = 4223; public static final int ELIZABETH = 4224; public static final int FRANK = 4225; public static final int SINCLAIR = 4226; public static final int POISON_SALESMAN = 4227; public static final int SINCLAIR_GUARD_DOG = 4228; public static final int LOVE_CATS_4229 = 4229; public static final int NEITE_4230 = 4230; public static final int BOB_4231 = 4231; public static final int BEITE = 4232; public static final int GNOME = 4233; public static final int GNOME_4234 = 4234; public static final int ODYSSEUS_4235 = 4235; public static final int NEITE_4236 = 4236; public static final int UNFERTH = 4237; public static final int UNFERTH_4238 = 4238; public static final int UNFERTH_4239 = 4239; public static final int UNFERTH_4240 = 4240; public static final int UNFERTH_4241 = 4241; public static final int RELDO = 4242; public static final int RELDO_4243 = 4243; public static final int BROTHER_OMAD = 4244; public static final int BROTHER_CEDRIC = 4245; public static final int MONK_4246 = 4246; public static final int THIEF_4247 = 4247; public static final int HEAD_THIEF = 4248; public static final int ALRENA = 4249; public static final int ALRENA_4250 = 4250; public static final int ALRENA_4251 = 4251; public static final int BRAVEK = 4252; public static final int BRAVEK_4253 = 4253; public static final int CLERK = 4255; public static final int EDMOND_4256 = 4256; public static final int ELENA_4257 = 4257; public static final int TED_REHNISON = 4263; public static final int MARTHA_REHNISON = 4264; public static final int BILLY_REHNISON = 4265; public static final int MILLI_REHNISON = 4266; public static final int MAN_4268 = 4268; public static final int MAN_4269 = 4269; public static final int MAN_4270 = 4270; public static final int MAN_4271 = 4271; public static final int MAN_4272 = 4272; public static final int LEELA = 4274; public static final int JAIL_GUARD = 4276; public static final int JAIL_GUARD_4277 = 4277; public static final int JAIL_GUARD_4278 = 4278; public static final int JAIL_GUARD_4279 = 4279; public static final int NED = 4280; public static final int AGGIE = 4284; public static final int HASSAN = 4285; public static final int OSMAN_4286 = 4286; public static final int BORDER_GUARD = 4287; public static final int BORDER_GUARD_4288 = 4288; public static final int GULL_4289 = 4289; public static final int GULL_4290 = 4290; public static final int HERMAN_CARANOS = 4291; public static final int FRANKLIN_CARANOS = 4292; public static final int ARNOLD_LYDSPOR = 4293; public static final int DEVIN_MENDELBERG = 4294; public static final int GEORGE_LAXMEISTER = 4295; public static final int RAMARA_DU_CROISSANT = 4296; public static final int KATHY_CORKAT = 4298; public static final int KATHY_CORKAT_4299 = 4299; public static final int ELEMENTAL_BALANCE_4301 = 4301; public static final int ELEMENTAL_BALANCE_4302 = 4302; public static final int KALPHITE_QUEEN_4303 = 4303; public static final int KALPHITE_QUEEN_4304 = 4304; public static final int DRUNKEN_DWARF_4305 = 4305; public static final int WISE_OLD_MAN_4306 = 4306; public static final int WISE_OLD_MAN_4307 = 4307; public static final int SEA_TROLL = 4308; public static final int SEA_TROLL_4309 = 4309; public static final int SEA_TROLL_4310 = 4310; public static final int SEA_TROLL_4311 = 4311; public static final int SKELETON_MAGE_4312 = 4312; public static final int SEA_TROLL_4313 = 4313; public static final int SEA_TROLL_GENERAL = 4314; public static final int SEA_TROLL_QUEEN = 4315; public static final int FISHING_SPOT_4316 = 4316; public static final int CALEB = 4317; public static final int SKELETON_MAGE_4318 = 4318; public static final int SKELETON_MAGE_4319 = 4319; public static final int MORGAN_LE_FAYE_4320 = 4320; public static final int RENEGADE_KNIGHT_4321 = 4321; public static final int ZANIK_4322 = 4322; public static final int ZANIK_4323 = 4323; public static final int ZANIK_4324 = 4324; public static final int LIGHT_CREATURE = 4325; public static final int ZANIK_4326 = 4326; public static final int HAM_MEMBER_4327 = 4327; public static final int SIGMUND_4328 = 4328; public static final int HAM_DEACON_4329 = 4329; public static final int JOHANHUS_ULSBRECHT_4330 = 4330; public static final int BLACK_KNIGHT_4331 = 4331; public static final int GUARD_4332 = 4332; public static final int COURT_JUDGE = 4333; public static final int JURY = 4334; public static final int GUARD_4335 = 4335; public static final int GUARD_4336 = 4336; public static final int PROSECUTOR = 4337; public static final int ARTHUR = 4340; public static final int SIR_LUCAN_4342 = 4342; public static final int SIR_PALOMEDES_4343 = 4343; public static final int SIR_LANCELOT_4344 = 4344; public static final int SIR_BEDIVERE_4345 = 4345; public static final int SIR_TRISTRAM_4346 = 4346; public static final int SIR_PELLEAS_4347 = 4347; public static final int SIR_GAWAIN_4348 = 4348; public static final int SIR_KAY_4349 = 4349; public static final int SIR_PELLEAS_4350 = 4350; public static final int SIR_GAWAIN_4351 = 4351; public static final int SIR_KAY_4352 = 4352; public static final int SQUIRE_4353 = 4353; public static final int SIR_LANCELOT_4354 = 4354; public static final int SIR_KAY_4355 = 4355; public static final int SIR_GAWAIN_4356 = 4356; public static final int SIR_LUCAN_4357 = 4357; public static final int SIR_PALOMEDES_4358 = 4358; public static final int SIR_TRISTRAM_4359 = 4359; public static final int SIR_PELLEAS_4360 = 4360; public static final int SIR_BEDIVERE_4361 = 4361; public static final int OGRE_CHIEFTAIN = 4362; public static final int OGRE_CHIEFTAIN_4363 = 4363; public static final int OG = 4364; public static final int GREW = 4365; public static final int TOBAN = 4366; public static final int GORAD = 4367; public static final int OGRE_GUARD_4368 = 4368; public static final int OGRE_GUARD_4369 = 4369; public static final int OGRE_GUARD_4370 = 4370; public static final int OGRE_GUARD_4371 = 4371; public static final int OGRE_GUARD_4372 = 4372; public static final int CITY_GUARD = 4373; public static final int SCARED_SKAVID = 4374; public static final int MAD_SKAVID = 4375; public static final int SKAVID_4376 = 4376; public static final int SKAVID_4377 = 4377; public static final int SKAVID_4378 = 4378; public static final int SKAVID_4379 = 4379; public static final int SKAVID_4380 = 4380; public static final int ENCLAVE_GUARD = 4381; public static final int OGRE_SHAMAN_4382 = 4382; public static final int OGRE_SHAMAN_4383 = 4383; public static final int OGRE_SHAMAN_4384 = 4384; public static final int BLUE_DRAGON_4385 = 4385; public static final int OGRE_SHAMAN_4386 = 4386; public static final int OGRE_SHAMAN_4387 = 4387; public static final int OGRE_SHAMAN_4388 = 4388; public static final int OGRE_SHAMAN_4389 = 4389; public static final int OGRE_SHAMAN_4390 = 4390; public static final int OGRE_SHAMAN_4391 = 4391; public static final int OGRE_SHAMAN_4392 = 4392; public static final int OGRE_SHAMAN_4393 = 4393; public static final int OGRE_SHAMAN_4394 = 4394; public static final int OGRE_SHAMAN_4395 = 4395; public static final int OGRE_SHAMAN_4396 = 4396; public static final int WATCHTOWER_WIZARD = 4397; public static final int WIZARD_4398 = 4398; public static final int WIZARD_4399 = 4399; public static final int WIZARD_4400 = 4400; public static final int OGRE_TRADER = 4401; public static final int OGRE_MERCHANT = 4402; public static final int OGRE_TRADER_4403 = 4403; public static final int OGRE_TRADER_4404 = 4404; public static final int TOWER_GUARD = 4405; public static final int COLONEL_RADICK = 4406; public static final int AVA = 4407; public static final int WITCH_4409 = 4409; public static final int ALICES_HUSBAND = 4411; public static final int ALICES_HUSBAND_4412 = 4412; public static final int ALICES_HUSBAND_4413 = 4413; public static final int ALICES_HUSBAND_4414 = 4414; public static final int TREE_4416 = 4416; public static final int UNDEAD_TREE = 4417; public static final int _SNEAKY_UNDEAD_FOWL = 4419; public static final int COW31337KILLER = 4420; public static final int UNDEAD_COW_4421 = 4421; public static final int ALICE_4422 = 4422; public static final int JOSSIK = 4423; public static final int JOSSIK_4424 = 4424; public static final int LARRISSA = 4425; public static final int LARRISSA_4426 = 4426; public static final int VAMPYRE_JUVINATE_4427 = 4427; public static final int VAMPYRE_JUVINATE_4428 = 4428; public static final int VAMPYRE_JUVINATE_4429 = 4429; public static final int VAMPYRE_JUVINATE_4430 = 4430; public static final int FERAL_VAMPYRE_4431 = 4431; public static final int VAMPYRE_JUVINATE_4432 = 4432; public static final int VAMPYRE_JUVINATE_4433 = 4433; public static final int VAMPYRE_JUVINATE_4434 = 4434; public static final int MIST_4435 = 4435; public static final int VAMPYRE_JUVENILE_4436 = 4436; public static final int VAMPYRE_JUVENILE_4437 = 4437; public static final int VAMPYRE_JUVENILE_4438 = 4438; public static final int VAMPYRE_JUVENILE_4439 = 4439; public static final int IVAN_STROM = 4440; public static final int IVAN_STROM_4441 = 4441; public static final int VAMPYRE_JUVINATE_4442 = 4442; public static final int VAMPYRE_JUVINATE_4443 = 4443; public static final int ELISABETA = 4444; public static final int AUREL = 4445; public static final int SORIN = 4446; public static final int LUSCION = 4447; public static final int SERGIU = 4448; public static final int RADU = 4449; public static final int GRIGORE = 4450; public static final int ILEANA = 4451; public static final int VALERIA = 4452; public static final int EMILIA = 4453; public static final int FLORIN = 4454; public static final int CATALINA = 4455; public static final int IVAN = 4456; public static final int VICTOR = 4457; public static final int HELENA = 4458; public static final int TEODOR = 4459; public static final int MARIUS = 4460; public static final int GABRIELA = 4461; public static final int VLADIMIR = 4462; public static final int CALIN = 4463; public static final int MIHAIL = 4464; public static final int NICOLETA = 4465; public static final int SIMONA = 4466; public static final int VASILE = 4467; public static final int RAZVAN = 4468; public static final int LUMINATA = 4469; public static final int CORNELIUS = 4470; public static final int CORNELIUS_4471 = 4471; public static final int BENJAMIN_4472 = 4472; public static final int LIAM_4473 = 4473; public static final int MIALA_4474 = 4474; public static final int VERAK_4475 = 4475; public static final int FISHING_SPOT_4476 = 4476; public static final int FISHING_SPOT_4477 = 4477; public static final int SORIN_4478 = 4478; public static final int WISKIT = 4480; public static final int VAMPYRE_JUVINATE_4481 = 4481; public static final int VAMPYRE_JUVINATE_4482 = 4482; public static final int GADDERANKS = 4483; public static final int GADDERANKS_4484 = 4484; public static final int GADDERANKS_4485 = 4485; public static final int VAMPYRE_JUVINATE_4486 = 4486; public static final int VAMPYRE_JUVINATE_4487 = 4487; public static final int OLAF_HRADSON = 4488; public static final int VOLF_OLAFSON = 4489; public static final int INGRID_HRADSON = 4490; public static final int SKELETON_FREMENNIK = 4491; public static final int SKELETON_FREMENNIK_4492 = 4492; public static final int SKELETON_FREMENNIK_4493 = 4493; public static final int SKELETON_FREMENNIK_4494 = 4494; public static final int SKELETON_FREMENNIK_4495 = 4495; public static final int SKELETON_FREMENNIK_4496 = 4496; public static final int SKELETON_FREMENNIK_4497 = 4497; public static final int SKELETON_FREMENNIK_4498 = 4498; public static final int SKELETON_FREMENNIK_4499 = 4499; public static final int ULFRIC = 4500; public static final int BRINE_RAT = 4501; public static final int BOULDER_4502 = 4502; public static final int BOULDER_4503 = 4503; public static final int GIANT_BAT_4504 = 4504; public static final int ULFRIC_4505 = 4505; public static final int ZANIK_4506 = 4506; public static final int ZANIK_4508 = 4508; public static final int ZANIK_4509 = 4509; public static final int ZANIK_4510 = 4510; public static final int ZANIK_4511 = 4511; public static final int DWARF_4512 = 4512; public static final int HAM_MEMBER_4513 = 4513; public static final int HAM_MEMBER_4514 = 4514; public static final int GUARD_4516 = 4516; public static final int GUARD_4517 = 4517; public static final int GUARD_4518 = 4518; public static final int GUARD_4519 = 4519; public static final int GUARD_4520 = 4520; public static final int GUARD_4521 = 4521; public static final int GUARD_4522 = 4522; public static final int GUARD_4523 = 4523; public static final int GUARD_4524 = 4524; public static final int GUARD_4525 = 4525; public static final int GUARD_4526 = 4526; public static final int CHADWELL = 4527; public static final int BLESSED_SPIDER = 4533; public static final int BLESSED_GIANT_RAT = 4534; public static final int BLESSED_GIANT_RAT_4535 = 4535; public static final int BOULDER_4543 = 4543; public static final int NILOOF = 4551; public static final int KLANK = 4552; public static final int KAMEN = 4553; public static final int SPIDER_4561 = 4561; public static final int GIANT_BAT_4562 = 4562; public static final int MONK_4563 = 4563; public static final int DEAD_MONK = 4564; public static final int HIGH_PRIEST_4565 = 4565; public static final int MONK_4566 = 4566; public static final int MONK_4567 = 4567; public static final int ASSASSIN = 4568; public static final int RED_AXE_HENCHMAN_4569 = 4569; public static final int RED_AXE_HENCHMAN_4570 = 4570; public static final int OGRE_SHAMAN_4571 = 4571; public static final int THE_BEAST = 4572; public static final int BELLEMORDE = 4573; public static final int POX = 4574; public static final int POX_4575 = 4575; public static final int BONES_4576 = 4576; public static final int CERIL_CARNILLEAN_4577 = 4577; public static final int COUNCILLOR_HALGRIVE = 4578; public static final int SPICE_SELLER_4579 = 4579; public static final int FUR_TRADER_4580 = 4580; public static final int GEM_MERCHANT_4581 = 4581; public static final int SILVER_MERCHANT = 4582; public static final int SILK_MERCHANT_4583 = 4583; public static final int ZENESHA = 4584; public static final int ALI_MORRISANE_4585 = 4585; public static final int GRIMESQUIT = 4586; public static final int PHINGSPET = 4587; public static final int HOOKNOSED_JACK = 4588; public static final int JIMMY_DAZZLER = 4589; public static final int THE_FACE = 4590; public static final int FELKRASH = 4591; public static final int SMOKIN_JOE = 4592; public static final int RAT_4593 = 4593; public static final int RAT_4594 = 4594; public static final int KING_RAT = 4595; public static final int TURBOGROOMER = 4596; public static final int PUSSKINS = 4597; public static final int LOKI = 4598; public static final int CAPTAIN_TOM = 4599; public static final int TREACLE = 4600; public static final int MITTENS = 4601; public static final int CLAUDE = 4602; public static final int TOPSY = 4603; public static final int RAUBORN = 4604; public static final int VAERINGK = 4605; public static final int OXI = 4606; public static final int FIOR = 4607; public static final int SAGIRA = 4608; public static final int ANLEIF = 4609; public static final int RAT_4610 = 4610; public static final int RAT_4611 = 4611; public static final int RAT_4612 = 4612; public static final int RAT_4613 = 4613; public static final int RAT_4614 = 4614; public static final int RAT_4615 = 4615; public static final int RAT_4616 = 4616; public static final int RAT_4617 = 4617; public static final int RAT_4618 = 4618; public static final int HETTY = 4619; public static final int ELEMENTAL_BALANCE_4620 = 4620; public static final int ELEMENTAL_BALANCE_4621 = 4621; public static final int ELEMENTAL_BALANCE_4622 = 4622; public static final int ELEMENTAL_BALANCE_4623 = 4623; public static final int ELEMENTAL_BALANCE_4624 = 4624; public static final int TRUFITUS = 4625; public static final int COOK_4626 = 4626; public static final int MILLIE_MILLER = 4627; public static final int GILLIE_GROATS = 4628; public static final int ANA = 4629; public static final int ANA_4630 = 4630; public static final int FEMALE_SLAVE = 4631; public static final int MALE_SLAVE = 4632; public static final int ESCAPING_SLAVE = 4633; public static final int ROWDY_SLAVE = 4634; public static final int MERCENARY_CAPTAIN = 4635; public static final int CAPTAIN_SIAD = 4636; public static final int AL_SHABIM = 4637; public static final int BEDABIN_NOMAD = 4638; public static final int BEDABIN_NOMAD_GUARD = 4639; public static final int IRENA = 4640; public static final int IRENA_4641 = 4641; public static final int SHANTAY = 4642; public static final int SHANTAY_GUARD = 4643; public static final int OAKNOCK_THE_ENGINEER = 4644; public static final int GLOUPHRIE_THE_UNTRUSTED = 4645; public static final int KING_HEALTHORG = 4646; public static final int HAZELMERE_4647 = 4647; public static final int SHANTAY_GUARD_4648 = 4648; public static final int DESERT_WOLF = 4649; public static final int DESERT_WOLF_4650 = 4650; public static final int DESERT_WOLF_4651 = 4651; public static final int UGTHANKI = 4652; public static final int MINE_CART_DRIVER = 4653; public static final int ROWDY_GUARD = 4654; public static final int BEDABIN_NOMAD_FIGHTER = 4655; public static final int MERCENARY = 4656; public static final int MERCENARY_4657 = 4657; public static final int MERCENARY_4658 = 4658; public static final int MERCENARY_4659 = 4659; public static final int GUARD_4660 = 4660; public static final int GUARD_4661 = 4661; public static final int GUARD_4662 = 4662; public static final int GUARD_4663 = 4663; public static final int GUARD_4664 = 4664; public static final int GUARD_4665 = 4665; public static final int GUARD_4666 = 4666; public static final int GUARD_4667 = 4667; public static final int GUARD_4668 = 4668; public static final int GUARD_4669 = 4669; public static final int MALE_SLAVE_4670 = 4670; public static final int MALE_SLAVE_4671 = 4671; public static final int FEMALE_SLAVE_4672 = 4672; public static final int FEMALE_SLAVE_4673 = 4673; public static final int CART_CAMEL = 4674; public static final int MINE_CART_4675 = 4675; public static final int MINE_CART_4676 = 4676; public static final int ANA_4677 = 4677; public static final int MERCENARY_4678 = 4678; public static final int SIR_SPISHYUS = 4679; public static final int LADY_TABLE = 4680; public static final int SIR_KUAM_FERENTSE = 4681; public static final int SIR_LEYE = 4682; public static final int SIR_TINLEY = 4683; public static final int SIR_REN_ITCHOOD = 4684; public static final int MISS_CHEEVERS = 4685; public static final int MS_HYNN_TERPRETT = 4686; public static final int SIR_TIFFY_CASHIEN = 4687; public static final int ANGRY_UNICORN_4688 = 4688; public static final int ANGRY_GIANT_RAT_4689 = 4689; public static final int ANGRY_GIANT_RAT_4690 = 4690; public static final int ANGRY_GOBLIN_4691 = 4691; public static final int ANGRY_BEAR_4692 = 4692; public static final int FEAR_REAPER_4693 = 4693; public static final int CONFUSION_BEAST_4694 = 4694; public static final int HOPELESS_CREATURE_4695 = 4695; public static final int HOPELESS_BEAST = 4696; public static final int HOPELESS_BEAST_4697 = 4697; public static final int TIMFRAKU = 4698; public static final int TIADECHE = 4699; public static final int TIADECHE_4700 = 4700; public static final int TINSAY = 4701; public static final int TINSAY_4702 = 4702; public static final int TAMAYU = 4703; public static final int TAMAYU_4704 = 4704; public static final int TAMAYU_4705 = 4705; public static final int TAMAYU_4706 = 4706; public static final int LUBUFU = 4707; public static final int THE_SHAIKAHAN = 4708; public static final int THE_SHAIKAHAN_4709 = 4709; public static final int FISHING_SPOT_4710 = 4710; public static final int FISHING_SPOT_4711 = 4711; public static final int FISHING_SPOT_4712 = 4712; public static final int FISHING_SPOT_4713 = 4713; public static final int FISHING_SPOT_4714 = 4714; public static final int AUGUSTE = 4715; public static final int AUGUSTE_4716 = 4716; public static final int AUGUSTE_4717 = 4717; public static final int AUGUSTE_4718 = 4718; public static final int ASSISTANT_SERF = 4719; public static final int ASSISTANT_BROCK = 4720; public static final int ASSISTANT_MARROW = 4721; public static final int ASSISTANT_LE_SMITH = 4722; public static final int ASSISTANT_STAN = 4723; public static final int BOB_4724 = 4724; public static final int CURLY = 4725; public static final int MOE = 4726; public static final int LARRY_4727 = 4727; public static final int THURGO = 4733; public static final int GULL_4734 = 4734; public static final int GULL_4735 = 4735; public static final int SIR_VYVIN = 4736; public static final int SQUIRE_4737 = 4737; public static final int GENIE_4738 = 4738; public static final int NIRRIE = 4739; public static final int TIRRIE = 4740; public static final int HALLAK = 4741; public static final int BLACK_GOLEM = 4742; public static final int WHITE_GOLEM = 4743; public static final int GREY_GOLEM = 4744; public static final int GHASLOR_THE_ELDER = 4745; public static final int ALI_THE_CARTER = 4746; public static final int USI = 4747; public static final int NKUKU = 4748; public static final int GARAI = 4749; public static final int HABIBAH = 4750; public static final int MESKHENET = 4751; public static final int ZAHRA = 4752; public static final int ZAHUR = 4753; public static final int SEDDU = 4754; public static final int KAZEMDE = 4755; public static final int AWUSAH_THE_MAYOR = 4756; public static final int TARIK_4757 = 4757; public static final int POLTENIP = 4758; public static final int RADAT = 4759; public static final int SHIRATTI_THE_CUSTODIAN = 4760; public static final int ROKUH = 4761; public static final int NARDAH_BANKER = 4762; public static final int TARGET = 4763; public static final int TARGET_4764 = 4764; public static final int TEGID = 4766; public static final int THISTLE = 4767; public static final int PARROTS = 4768; public static final int PARROTY_PETE = 4769; public static final int FAKE_MAN = 4770; public static final int SIR_AMIK_VARZE_4771 = 4771; public static final int FORTRESS_GUARD = 4772; public static final int FORTRESS_GUARD_4773 = 4773; public static final int FORTRESS_GUARD_4774 = 4774; public static final int FORTRESS_GUARD_4775 = 4775; public static final int FORTRESS_GUARD_4776 = 4776; public static final int BLACK_KNIGHT_CAPTAIN = 4777; public static final int WITCH_4778 = 4778; public static final int GRELDO = 4779; public static final int BLACK_CAT = 4780; public static final int COL_ONIALL = 4781; public static final int COL_ONIALL_4782 = 4782; public static final int MAYOR_HOBB = 4783; public static final int MAYOR_HOBB_4784 = 4784; public static final int BROTHER_MALEDICT = 4787; public static final int BROTHER_MALEDICT_4788 = 4788; public static final int EZEKIAL_LOVECRAFT = 4789; public static final int WITCHAVEN_VILLAGER = 4790; public static final int WITCHAVEN_VILLAGER_4791 = 4791; public static final int WITCHAVEN_VILLAGER_4792 = 4792; public static final int WITCHAVEN_VILLAGER_4793 = 4793; public static final int WITCHAVEN_VILLAGER_4794 = 4794; public static final int WITCHAVEN_VILLAGER_4795 = 4795; public static final int MOTHER_MALLUM = 4796; public static final int SLUG_PRINCE = 4797; public static final int SLUG_PRINCE_4798 = 4798; public static final int GIANT_LOBSTER_4799 = 4799; public static final int GIANT_LOBSTER_4800 = 4800; public static final int SEA_SLUG = 4801; public static final int JEB = 4802; public static final int JEB_4803 = 4803; public static final int SIR_TINLEY_4804 = 4804; public static final int HOBGOBLIN_4805 = 4805; public static final int EVIL_DAVE_4806 = 4806; public static final int EVIL_DAVE_4807 = 4807; public static final int DORIS = 4808; public static final int HELLRAT = 4809; public static final int AN_OLD_DWARF = 4810; public static final int ROHAK = 4811; public static final int ROHAK_4812 = 4812; public static final int ICEFIEND_4813 = 4813; public static final int PIRATE_PETE_4814 = 4814; public static final int PIRATE_PETE_4816 = 4816; public static final int MOGRE_GUARD = 4817; public static final int NUNG = 4818; public static final int CRAB_4819 = 4819; public static final int MUDSKIPPER = 4820; public static final int MUDSKIPPER_4821 = 4821; public static final int CRAB_4822 = 4822; public static final int FISH = 4823; public static final int FISH_4824 = 4824; public static final int FISH_4825 = 4825; public static final int FISH_4826 = 4826; public static final int FISH_4827 = 4827; public static final int FISH_4828 = 4828; public static final int FISH_4829 = 4829; public static final int FISH_4830 = 4830; public static final int FISH_4831 = 4831; public static final int FISH_4832 = 4832; public static final int FISH_4833 = 4833; public static final int FISH_4834 = 4834; public static final int FISH_4835 = 4835; public static final int FISH_4836 = 4836; public static final int FISH_4837 = 4837; public static final int FISH_4838 = 4838; public static final int FISH_4839 = 4839; public static final int FISH_4840 = 4840; public static final int FISH_4841 = 4841; public static final int FISH_4842 = 4842; public static final int FISH_4843 = 4843; public static final int FISH_4844 = 4844; public static final int FISH_4845 = 4845; public static final int FISH_4846 = 4846; public static final int GYPSY = 4847; public static final int GYPSY_4848 = 4848; public static final int CULINAROMANCER_4849 = 4849; public static final int GOBLIN_COOK = 4850; public static final int GOBLIN_COOK_4851 = 4851; public static final int GOBLIN_COOK_4852 = 4852; public static final int SKRACH_UGLOGWEE_4853 = 4853; public static final int SKRACH_UGLOGWEE_4854 = 4854; public static final int RANTZ_4855 = 4855; public static final int RANTZ_4856 = 4856; public static final int RANTZ_4857 = 4857; public static final int OGRE_BOAT = 4858; public static final int OGRE_BOAT_4859 = 4859; public static final int BALLOON_TOAD = 4860; public static final int BALLOON_TOAD_4861 = 4861; public static final int BALLOON_TOAD_4862 = 4862; public static final int JUBBLY_BIRD = 4863; public static final int JUBBLY_BIRD_4864 = 4864; public static final int ELEMENTAL_BALANCE_4865 = 4865; public static final int ELEMENTAL_BALANCE_4866 = 4866; public static final int ELEMENTAL_BALANCE_4867 = 4867; public static final int ELEMENTAL_BALANCE_4868 = 4868; public static final int ELEMENTAL_BALANCE_4869 = 4869; public static final int ELEMENTAL_BALANCE_4870 = 4870; public static final int ELEMENTAL_BALANCE_4871 = 4871; public static final int CULINAROMANCER_4872 = 4872; public static final int CULINAROMANCER_4873 = 4873; public static final int CULINAROMANCER_4874 = 4874; public static final int CULINAROMANCER_4875 = 4875; public static final int CULINAROMANCER_4876 = 4876; public static final int CULINAROMANCER_4877 = 4877; public static final int CULINAROMANCER_4878 = 4878; public static final int CULINAROMANCER_4879 = 4879; public static final int AGRITHNANA = 4880; public static final int FLAMBEED = 4881; public static final int KARAMEL = 4882; public static final int DESSOURT = 4883; public static final int GELATINNOTH_MOTHER = 4884; public static final int GELATINNOTH_MOTHER_4885 = 4885; public static final int GELATINNOTH_MOTHER_4886 = 4886; public static final int GELATINNOTH_MOTHER_4887 = 4887; public static final int GELATINNOTH_MOTHER_4888 = 4888; public static final int GELATINNOTH_MOTHER_4889 = 4889; public static final int DONDAKAN_THE_DWARF = 4890; public static final int DONDAKAN_THE_DWARF_4891 = 4891; public static final int DONDAKAN_THE_DWARF_4892 = 4892; public static final int DWARVEN_ENGINEER = 4893; public static final int ROLAD = 4894; public static final int KHORVAK_A_DWARVEN_ENGINEER = 4895; public static final int DWARVEN_FERRYMAN = 4896; public static final int DWARVEN_FERRYMAN_4897 = 4897; public static final int DWARVEN_BOATMAN_4898 = 4898; public static final int MIODVETNIR = 4899; public static final int DERNU = 4900; public static final int DERNI = 4901; public static final int GOBLIN_4902 = 4902; public static final int GOBLIN_4903 = 4903; public static final int GOBLIN_4904 = 4904; public static final int GOBLIN_4905 = 4905; public static final int GOBLIN_4906 = 4906; public static final int GNOME_SOLDIER = 4907; public static final int GNOME_SOLDIER_4908 = 4908; public static final int GNOME_SOLDIER_4909 = 4909; public static final int GNOME_SOLDIER_4910 = 4910; public static final int GNOME_SOLDIER_4911 = 4911; public static final int HEALTHORG_AND_TORTOISE = 4912; public static final int BRIMSTAIL = 4914; public static final int GARV = 4915; public static final int GRUBOR = 4916; public static final int TROBERT = 4917; public static final int SETH = 4918; public static final int GRIP = 4919; public static final int ALFONSE_THE_WAITER = 4920; public static final int CHARLIE_THE_COOK = 4921; public static final int ICE_QUEEN = 4922; public static final int ACHIETTIES = 4923; public static final int HELEMOS = 4924; public static final int VELRAK_THE_EXPLORER = 4925; public static final int PIRATE_GUARD = 4926; public static final int ENTRANA_FIREBIRD = 4927; public static final int FISHING_SPOT_4928 = 4928; public static final int LORD_DAQUARIUS = 4929; public static final int SOLUS_DELLAGAR = 4930; public static final int SAVANT = 4931; public static final int LORD_DAQUARIUS_4932 = 4932; public static final int SOLUS_DELLAGAR_4933 = 4933; public static final int BLACK_KNIGHT_4934 = 4934; public static final int LORD_DAQUARIUS_4935 = 4935; public static final int MAGE_OF_ZAMORAK_4936 = 4936; public static final int MAGE_OF_ZAMORAK_4937 = 4937; public static final int MAGE_OF_ZAMORAK_4938 = 4938; public static final int WOMAN_4958 = 4958; public static final int BLACK_KNIGHT_4959 = 4959; public static final int BLACK_KNIGHT_4960 = 4960; public static final int RANGER = 4961; public static final int SOLUS_DELLAGAR_4962 = 4962; public static final int KING_BOLREN = 4963; public static final int COMMANDER_MONTAI = 4964; public static final int BOLKOY = 4965; public static final int REMSAI = 4966; public static final int ELKOY = 4967; public static final int ELKOY_4968 = 4968; public static final int KHAZARD_TROOPER = 4969; public static final int KHAZARD_TROOPER_4970 = 4970; public static final int KHAZARD_COMMANDER = 4972; public static final int GNOME_TROOP = 4973; public static final int GNOME_TROOP_4974 = 4974; public static final int TRACKER_GNOME_1 = 4975; public static final int TRACKER_GNOME_2 = 4976; public static final int TRACKER_GNOME_3 = 4977; public static final int LOCAL_GNOME = 4978; public static final int LOCAL_GNOME_4979 = 4979; public static final int KALRON = 4980; public static final int SPIRIT_TREE = 4981; public static final int SPIRIT_TREE_4982 = 4982; public static final int DIMINTHEIS = 4984; public static final int BOOT = 4985; public static final int CHRONOZON = 4987; public static final int ELEMENTAL_BALANCE_4989 = 4989; public static final int ELEMENTAL_BALANCE_4990 = 4990; public static final int ELEMENTAL_BALANCE_4991 = 4991; public static final int ELEMENTAL_BALANCE_4992 = 4992; public static final int ELEMENTAL_BALANCE_4993 = 4993; public static final int ELEMENTAL_BALANCE_4994 = 4994; public static final int ELEMENTAL_BALANCE_4995 = 4995; public static final int ELEMENTAL_BALANCE_4996 = 4996; public static final int ELEMENTAL_BALANCE_4997 = 4997; public static final int ELEMENTAL_BALANCE_4998 = 4998; public static final int ELEMENTAL_BALANCE_4999 = 4999; public static final int ELEMENTAL_BALANCE_5000 = 5000; public static final int ELEMENTAL_BALANCE_5001 = 5001; public static final int ELEMENTAL_BALANCE_5002 = 5002; public static final int ELEMENTAL_BALANCE_5003 = 5003; public static final int ELEMENTAL_BALANCE_5004 = 5004; public static final int WIZARD_GRAYZAG = 5006; public static final int IMP_5007 = 5007; public static final int LIL_DESTRUCTOR_5008 = 5008; public static final int ELEMENTAL_BALANCE_5009 = 5009; public static final int ELEMENTAL_BALANCE_5010 = 5010; public static final int ELEMENTAL_BALANCE_5011 = 5011; public static final int ELEMENTAL_BALANCE_5012 = 5012; public static final int ELEMENTAL_BALANCE_5013 = 5013; public static final int ELEMENTAL_BALANCE_5014 = 5014; public static final int ELEMENTAL_BALANCE_5015 = 5015; public static final int ELEMENTAL_BALANCE_5016 = 5016; public static final int ELEMENTAL_BALANCE_5017 = 5017; public static final int ELEMENTAL_BALANCE_5018 = 5018; public static final int ELEMENTAL_BALANCE_5019 = 5019; public static final int ELEMENTAL_BALANCE_5020 = 5020; public static final int ELEMENTAL_BALANCE_5021 = 5021; public static final int COMBAT_STONE_5022 = 5022; public static final int COMBAT_STONE_5023 = 5023; public static final int COMBAT_STONE_5024 = 5024; public static final int COMBAT_STONE_5025 = 5025; public static final int COMBAT_STONE_5026 = 5026; public static final int COMBAT_STONE_5027 = 5027; public static final int COMBAT_STONE_5028 = 5028; public static final int COMBAT_STONE_5029 = 5029; public static final int COMBAT_STONE_5030 = 5030; public static final int COMBAT_STONE_5031 = 5031; public static final int COMBAT_STONE_5032 = 5032; public static final int COMBAT_STONE_5033 = 5033; public static final int JULIET = 5035; public static final int APOTHECARY = 5036; public static final int ROMEO = 5037; public static final int FATHER_LAWRENCE = 5038; public static final int DRAUL_LEPTOC = 5039; public static final int PHILLIPA = 5040; public static final int MARTINA_SCORSBY = 5041; public static final int JEREMY_CLERKSIN = 5042; public static final int SUIT_OF_ARMOUR = 5043; public static final int SANFEW = 5044; public static final int KAQEMEEX = 5045; public static final int CYREG_PADDLEHORN = 5046; public static final int VELIAF_HURTZ_5048 = 5048; public static final int RADIGAD_PONFIT = 5051; public static final int POLMAFI_FERDYGRIS = 5052; public static final int IVAN_STROM_5053 = 5053; public static final int SKELETON_HELLHOUND = 5054; public static final int STRANGER_5055 = 5055; public static final int VANSTROM_KLAUSE_5056 = 5056; public static final int MIST_5057 = 5057; public static final int SEA_SLUG_5061 = 5061; public static final int KENNITH = 5062; public static final int KENNITH_5063 = 5063; public static final int BAILEY = 5066; public static final int CAROLINE = 5067; public static final int HOLGART = 5068; public static final int HOLGART_5069 = 5069; public static final int HOLGART_5070 = 5070; public static final int HOLGART_5072 = 5072; public static final int HOLGART_5073 = 5073; public static final int KENT = 5074; public static final int FISHERMAN_5075 = 5075; public static final int FISHERMAN_5076 = 5076; public static final int FISHERMAN_5077 = 5077; public static final int FISHERMAN_5078 = 5078; public static final int DELRITH = 5079; public static final int WEAKENED_DELRITH = 5080; public static final int WIZARD_TRAIBORN = 5081; public static final int GYPSY_ARIS = 5082; public static final int SIR_PRYSIN = 5083; public static final int SIR_PRYSIN_5084 = 5084; public static final int CAPTAIN_ROVIN = 5085; public static final int DARK_WIZARD_5086 = 5086; public static final int DARK_WIZARD_5087 = 5087; public static final int DARK_WIZARD_5088 = 5088; public static final int DARK_WIZARD_5089 = 5089; public static final int DENATH_5090 = 5090; public static final int DENATH_5091 = 5091; public static final int WALLY = 5092; public static final int COMBAT_STONE_5093 = 5093; public static final int COMBAT_STONE_5094 = 5094; public static final int COMBAT_STONE_5095 = 5095; public static final int COMBAT_STONE_5096 = 5096; public static final int COMBAT_STONE_5097 = 5097; public static final int COMBAT_STONE_5098 = 5098; public static final int COMBAT_STONE_5099 = 5099; public static final int COMBAT_STONE_5100 = 5100; public static final int COMBAT_STONE_5101 = 5101; public static final int COMBAT_STONE_5102 = 5102; public static final int COMBAT_STONE_5103 = 5103; public static final int COMBAT_STONE_5104 = 5104; public static final int COMBAT_STONE_5105 = 5105; public static final int COMBAT_STONE_5106 = 5106; public static final int COMBAT_STONE_5107 = 5107; public static final int COMBAT_STONE_5108 = 5108; public static final int COMBAT_STONE_5109 = 5109; public static final int COMBAT_STONE_5110 = 5110; public static final int COMBAT_STONE_5111 = 5111; public static final int COMBAT_STONE_5112 = 5112; public static final int COMBAT_STONE_5113 = 5113; public static final int COMBAT_STONE_5114 = 5114; public static final int COMBAT_STONE_5115 = 5115; public static final int COMBAT_STONE_5116 = 5116; public static final int COMBAT_STONE_5117 = 5117; public static final int SYLAS = 5118; public static final int GRIMGNASH = 5119; public static final int RUPERT_THE_BEARD = 5120; public static final int RUPERT_THE_BEARD_5121 = 5121; public static final int DRAIN_PIPE = 5122; public static final int RUPERT_THE_BEARD_5123 = 5123; public static final int RUPERT_THE_BEARD_5124 = 5124; public static final int MIAZRQA = 5125; public static final int EXPERIMENT_NO2 = 5126; public static final int MOUSE_5127 = 5127; public static final int MOUSE_5128 = 5128; public static final int GLOD = 5129; public static final int GNOME_5130 = 5130; public static final int WINKIN = 5131; public static final int GNOME_5132 = 5132; public static final int CAGE_5133 = 5133; public static final int BROKEN_CLAY_GOLEM = 5134; public static final int DAMAGED_CLAY_GOLEM = 5135; public static final int CLAY_GOLEM_5136 = 5136; public static final int DESERT_PHOENIX = 5137; public static final int ELISSA = 5138; public static final int SIGMUND_5139 = 5139; public static final int ZANIK_5140 = 5140; public static final int GUARD_5141 = 5141; public static final int SIGMUND_5142 = 5142; public static final int SIGMUND_5143 = 5143; public static final int SIGMUND_5144 = 5144; public static final int SIGMUND_5145 = 5145; public static final int SIGMUND_5146 = 5146; public static final int ZANIK_5147 = 5147; public static final int ZANIK_5148 = 5148; public static final int GENERAL_BENTNOZE_5149 = 5149; public static final int GENERAL_WARTFACE_5150 = 5150; public static final int GRUBFOOT_5151 = 5151; public static final int GOBLIN_5152 = 5152; public static final int GOBLIN_5153 = 5153; public static final int GOBLIN_5154 = 5154; public static final int ZANIK_5155 = 5155; public static final int URTAG_5156 = 5156; public static final int HAM_ARCHER = 5157; public static final int HAM_MAGE = 5158; public static final int ZANIK_5159 = 5159; public static final int SIGMUND_AND_ZANIK = 5160; public static final int SERGEANT_MOSSFISTS = 5161; public static final int SERGEANT_SLIMETOES = 5162; public static final int CAVE_GOBLIN_5163 = 5163; public static final int CAVE_GOBLIN_5164 = 5164; public static final int CAVE_GOBLIN_5165 = 5165; public static final int CAVE_GOBLIN_5166 = 5166; public static final int CAVE_GOBLIN_5167 = 5167; public static final int CAVE_GOBLIN_5168 = 5168; public static final int TICKET_GOBLIN = 5169; public static final int DWARF_5170 = 5170; public static final int DWARF_5171 = 5171; public static final int DWARF_5172 = 5172; public static final int DWARF_5173 = 5173; public static final int DWARF_5174 = 5174; public static final int DWARF_5175 = 5175; public static final int TICKET_DWARF = 5176; public static final int AMBASSADOR_ALVIJAR = 5177; public static final int BUILDER = 5178; public static final int BUILDER_5179 = 5179; public static final int BUILDER_5180 = 5180; public static final int BUILDER_5181 = 5181; public static final int TEGDAK = 5182; public static final int ZANIK_5184 = 5184; public static final int GUARD_5185 = 5185; public static final int GUARD_5186 = 5186; public static final int GUARD_5187 = 5187; public static final int GUARD_5188 = 5188; public static final int GUARD_5189 = 5189; public static final int LOLLK = 5190; public static final int CAPTAIN_LAWGOF = 5191; public static final int GOBLIN_5192 = 5192; public static final int GOBLIN_5193 = 5193; public static final int BABY_GREEN_DRAGON = 5194; public static final int GOBLIN_5195 = 5195; public static final int GOBLIN_5196 = 5196; public static final int GOBLIN_5197 = 5197; public static final int GOBLIN_5198 = 5198; public static final int GOBLIN_5199 = 5199; public static final int GOBLIN_5200 = 5200; public static final int GOBLIN_5201 = 5201; public static final int GOBLIN_5202 = 5202; public static final int GOBLIN_5203 = 5203; public static final int GOBLIN_5204 = 5204; public static final int GOBLIN_5205 = 5205; public static final int GOBLIN_5206 = 5206; public static final int GOBLIN_5207 = 5207; public static final int GOBLIN_5208 = 5208; public static final int CHARLIE_THE_TRAMP = 5209; public static final int KATRINE = 5210; public static final int WEAPONSMASTER = 5211; public static final int STRAVEN = 5212; public static final int JONNY_THE_BEARD = 5213; public static final int CURATOR_HAIG_HALEN = 5214; public static final int KING_ROALD_5215 = 5215; public static final int BENNY = 5216; public static final int THIEF_5217 = 5217; public static final int THIEF_5218 = 5218; public static final int THIEF_5219 = 5219; public static final int THIEF_5220 = 5220; public static final int JIG_CART = 5221; public static final int JIG_CART_5222 = 5222; public static final int JIG_CART_5223 = 5223; public static final int JIG_CART_5224 = 5224; public static final int JIG_CART_5225 = 5225; public static final int JIG_CART_5226 = 5226; public static final int KHARID_SCORPION = 5228; public static final int KHARID_SCORPION_5229 = 5229; public static final int KHARID_SCORPION_5230 = 5230; public static final int SEER = 5231; public static final int THORMAC = 5232; public static final int FISHING_SPOT_5233 = 5233; public static final int FISHING_SPOT_5234 = 5234; public static final int MONKEY_MINDER = 5235; public static final int SKELETON_5237 = 5237; public static final int SPIDER_5238 = 5238; public static final int SPIDER_5239 = 5239; public static final int BIRD = 5240; public static final int BIRD_5241 = 5241; public static final int SCORPION_5242 = 5242; public static final int JUNGLE_SPIDER_5243 = 5243; public static final int SNAKE_5244 = 5244; public static final int DUGOPUL = 5245; public static final int SALENAB = 5246; public static final int TREFAJI = 5247; public static final int ABERAB = 5248; public static final int SOLIHIB = 5249; public static final int DAGA = 5250; public static final int TUTAB = 5251; public static final int IFABA = 5252; public static final int HAMAB = 5253; public static final int HAFUBA = 5254; public static final int DENADU = 5255; public static final int LOFU = 5256; public static final int KRUK = 5257; public static final int DUKE = 5258; public static final int OIPUIS = 5259; public static final int UYORO = 5260; public static final int OUHAI = 5261; public static final int UODAI = 5262; public static final int PADULAH = 5263; public static final int AWOWOGEI_5264 = 5264; public static final int UWOGO = 5265; public static final int MURUWOI = 5266; public static final int SLEEPING_MONKEY = 5267; public static final int MONKEY_CHILD = 5268; public static final int THE_MONKEYS_UNCLE = 5269; public static final int THE_MONKEYS_AUNT = 5270; public static final int MONKEY_GUARD = 5271; public static final int MONKEY_ARCHER = 5272; public static final int MONKEY_ARCHER_5273 = 5273; public static final int MONKEY_ARCHER_5274 = 5274; public static final int MONKEY_GUARD_5275 = 5275; public static final int MONKEY_GUARD_5276 = 5276; public static final int ELDER_GUARD = 5277; public static final int ELDER_GUARD_5278 = 5278; public static final int MONKEY_5279 = 5279; public static final int MONKEY_5280 = 5280; public static final int MONKEY_ZOMBIE = 5281; public static final int MONKEY_ZOMBIE_5282 = 5282; public static final int MONKEY_ZOMBIE_5283 = 5283; public static final int BONZARA = 5284; public static final int ELF_WARRIOR = 5293; public static final int ELF_WARRIOR_5294 = 5294; public static final int ELF_ARCHER = 5295; public static final int ELF_ARCHER_5296 = 5296; public static final int GOREU = 5297; public static final int ARVEL = 5299; public static final int MAWRTH = 5300; public static final int EOIN = 5302; public static final int IONA = 5303; public static final int ELUNED = 5304; public static final int RED_SHEEP_5305 = 5305; public static final int GREEN_SHEEP_5306 = 5306; public static final int BLUE_SHEEP_5307 = 5307; public static final int YELLOW_SHEEP_5308 = 5308; public static final int GNOME_5309 = 5309; public static final int GPDT_EMPLOYEE = 5313; public static final int HORACIO = 5315; public static final int KANGAI_MAU = 5316; public static final int EAGLE_5317 = 5317; public static final int EAGLE_5318 = 5318; public static final int EAGLE_5319 = 5319; public static final int EAGLE_5320 = 5320; public static final int COMBAT_STONE_5321 = 5321; public static final int SIGMUND_5322 = 5322; public static final int SIGMUND_5323 = 5323; public static final int URTAG_5326 = 5326; public static final int DUKE_HORACIO_5327 = 5327; public static final int MISTAG = 5328; public static final int SIGMUND_5329 = 5329; public static final int CAVE_GOBLIN_MINER = 5330; public static final int CAVE_GOBLIN_MINER_5331 = 5331; public static final int CAVE_GOBLIN_MINER_5332 = 5332; public static final int CAVE_GOBLIN_MINER_5333 = 5333; public static final int CAVE_GOBLIN_GUARD = 5334; public static final int CAVE_GOBLIN_GUARD_5335 = 5335; public static final int CAVE_GOBLIN_MINER_5336 = 5336; public static final int CAVE_GOBLIN_MINER_5337 = 5337; public static final int CAVE_GOBLIN_MINER_5338 = 5338; public static final int CAVE_GOBLIN_MINER_5339 = 5339; public static final int MOSOL_REI = 5340; public static final int SPIRIT_OF_ZADIMUS = 5341; public static final int UNDEAD_ONE = 5342; public static final int UNDEAD_ONE_5343 = 5343; public static final int UNDEAD_ONE_5344 = 5344; public static final int UNDEAD_ONE_5345 = 5345; public static final int UNDEAD_ONE_5346 = 5346; public static final int UNDEAD_ONE_5347 = 5347; public static final int UNDEAD_ONE_5348 = 5348; public static final int UNDEAD_ONE_5349 = 5349; public static final int UNDEAD_ONE_5350 = 5350; public static final int UNDEAD_ONE_5351 = 5351; public static final int RASHILIYIA = 5352; public static final int NAZASTAROOL = 5353; public static final int NAZASTAROOL_5354 = 5354; public static final int NAZASTAROOL_5355 = 5355; public static final int HAJEDY = 5356; public static final int VIGROY = 5357; public static final int KALEB_PARAMAYA = 5358; public static final int YOHNUS = 5359; public static final int SERAVEL = 5360; public static final int YANNI_SALIKA = 5361; public static final int OBLI = 5362; public static final int FERNAHEI = 5363; public static final int CAPTAIN_SHANKS = 5364; public static final int OBSERVATORY_ASSISTANT = 5365; public static final int OBSERVATORY_PROFESSOR = 5366; public static final int OBSERVATORY_PROFESSOR_5367 = 5367; public static final int SLEEPING_GUARD = 5368; public static final int GOBLIN_GUARD = 5369; public static final int GHOST_5370 = 5370; public static final int SPIRIT_OF_SCORPIUS = 5371; public static final int GRAVE_SCORPION = 5372; public static final int POISON_SPIDER_5373 = 5373; public static final int NAGHEAD = 5374; public static final int WAGCHIN = 5375; public static final int GOBLIN_5376 = 5376; public static final int GOBLIN_5377 = 5377; public static final int GREASYCHEEKS = 5378; public static final int SMELLYTOES = 5379; public static final int CREAKYKNEES = 5380; public static final int CLOTHEARS = 5381; public static final int GUARD_CAPTAIN = 5383; public static final int SANDY = 5384; public static final int SANDY_5385 = 5385; public static final int MAZION = 5386; public static final int BLAEC = 5387; public static final int REESO = 5388; public static final int COMBAT_STONE_5389 = 5389; public static final int COMBAT_STONE_5390 = 5390; public static final int COMBAT_STONE_5391 = 5391; public static final int COMBAT_STONE_5392 = 5392; public static final int COMBAT_STONE_5393 = 5393; public static final int COMBAT_STONE_5394 = 5394; public static final int COMBAT_STONE_5395 = 5395; public static final int COMBAT_STONE_5396 = 5396; public static final int COMBAT_STONE_5397 = 5397; public static final int COMBAT_STONE_5398 = 5398; public static final int COMBAT_STONE_5399 = 5399; public static final int COMBAT_STONE_5400 = 5400; public static final int COMBAT_STONE_5401 = 5401; public static final int COMBAT_STONE_5402 = 5402; public static final int COMBAT_STONE_5403 = 5403; public static final int COMBAT_STONE_5404 = 5404; public static final int COMBAT_STONE_5405 = 5405; public static final int COMBAT_STONE_5406 = 5406; public static final int COMBAT_STONE_5407 = 5407; public static final int COMBAT_STONE_5408 = 5408; public static final int COMBAT_STONE_5409 = 5409; public static final int COMBAT_STONE_5410 = 5410; public static final int COMBAT_STONE_5412 = 5412; public static final int COMBAT_STONE_5413 = 5413; public static final int COMBAT_STONE_5414 = 5414; public static final int COMBAT_STONE_5415 = 5415; public static final int COMBAT_STONE_5416 = 5416; public static final int PRIEST_5417 = 5417; public static final int GUARD_5418 = 5418; public static final int DOOR_MAN = 5419; public static final int WATCHMAN = 5420; public static final int SOLDIER_5421 = 5421; public static final int WYSON_THE_GARDENER = 5422; public static final int SIGBERT_THE_ADVENTURER = 5423; public static final int CAPT_ARNAV = 5426; public static final int FLIPPA = 5427; public static final int TILT = 5428; public static final int FROG_5429 = 5429; public static final int FROG_5430 = 5430; public static final int FROG_5431 = 5431; public static final int FROG_5432 = 5432; public static final int CALEB_5433 = 5433; public static final int FROG_PRINCE = 5434; public static final int FROG_PRINCESS = 5435; public static final int NILES = 5436; public static final int MILES = 5437; public static final int GILES = 5438; public static final int NILES_5439 = 5439; public static final int MILES_5440 = 5440; public static final int GILES_5441 = 5441; public static final int SECURITY_GUARD = 5442; public static final int JOHNATHON = 5443; public static final int CAPN_HAND = 5444; public static final int JOHNATHON_5445 = 5445; public static final int ADVISOR_GHRIM = 5447; public static final int ADVISOR_GHRIM_5448 = 5448; public static final int BOB_BARTER_HERBS = 5449; public static final int MURKY_MATT_RUNES = 5450; public static final int RELOBO_BLINYO_LOGS = 5451; public static final int HOFUTHAND_WEAPONS_AND_ARMOUR = 5452; public static final int RESHI = 5453; public static final int THUMPY = 5454; public static final int THOMDRIL = 5455; public static final int KENDALL = 5456; public static final int SHIPYARD_WORKER_5457 = 5457; public static final int SUSPECT_5458 = 5458; public static final int SUSPECT_5459 = 5459; public static final int SUSPECT_5460 = 5460; public static final int SUSPECT_5461 = 5461; public static final int SUSPECT_5462 = 5462; public static final int SUSPECT_5463 = 5463; public static final int MOLLY_5464 = 5464; public static final int SUSPECT_5465 = 5465; public static final int SUSPECT_5466 = 5466; public static final int MOLLY_5467 = 5467; public static final int SUSPECT_5468 = 5468; public static final int SUSPECT_5469 = 5469; public static final int SUSPECT_5470 = 5470; public static final int MOLLY_5471 = 5471; public static final int SUSPECT_5472 = 5472; public static final int SUSPECT_5473 = 5473; public static final int MOLLY_5474 = 5474; public static final int SUSPECT_5475 = 5475; public static final int MOLLY_5476 = 5476; public static final int SUSPECT_5477 = 5477; public static final int MOLLY_5478 = 5478; public static final int SUSPECT_5479 = 5479; public static final int MOLLY_5480 = 5480; public static final int SUSPECT_5481 = 5481; public static final int SUSPECT_5482 = 5482; public static final int SUSPECT_5483 = 5483; public static final int SUSPECT_5484 = 5484; public static final int MOLLY_5485 = 5485; public static final int MOLLY_5486 = 5486; public static final int MOLLY_5487 = 5487; public static final int BALLOON_ANIMAL_5488 = 5488; public static final int BALLOON_ANIMAL_5489 = 5489; public static final int BALLOON_ANIMAL_5491 = 5491; public static final int BALLOON_ANIMAL_5492 = 5492; public static final int BALLOON_ANIMAL_5493 = 5493; public static final int PHEASANT_5500 = 5500; public static final int PHEASANT_5502 = 5502; public static final int DUNCE = 5503; public static final int MR_MORDAUT = 5504; public static final int GIANT = 5505; public static final int MUMMY_5506 = 5506; public static final int ZOMBIE_5507 = 5507; public static final int GOBLIN_5508 = 5508; public static final int GOBLIN_5509 = 5509; public static final int SANDWICH_LADY = 5510; public static final int GUARD_RECRUITER = 5511; public static final int GARDENER_5512 = 5512; public static final int ELITE_VOID_KNIGHT = 5513; public static final int LESSER_FANATIC = 5514; public static final int LUNA = 5515; public static final int THE_WEDGE = 5517; public static final int ELDER_GNOME_CHILD = 5518; public static final int TWOPINTS = 5519; public static final int JARR = 5520; public static final int LESABR = 5521; public static final int FLAX_KEEPER = 5522; public static final int HATIUS_COSAINTUS = 5523; public static final int SIR_REBRAL = 5524; public static final int TOBY = 5525; public static final int THORODIN_5526 = 5526; public static final int TWIGGY_OKORN = 5527; public static final int SQUIRREL_5528 = 5528; public static final int HUNTING_EXPERT_5529 = 5529; public static final int SPOTTED_KEBBIT = 5531; public static final int DARK_KEBBIT = 5532; public static final int DASHING_KEBBIT = 5533; public static final int WHIRLPOOL_5534 = 5534; public static final int ENORMOUS_TENTACLE = 5535; public static final int VETION_JR = 5536; public static final int VETION_JR_5537 = 5537; public static final int EGG = 5538; public static final int EGG_5539 = 5539; public static final int EGG_5540 = 5540; public static final int EGG_5541 = 5541; public static final int EGG_5542 = 5542; public static final int EGG_5543 = 5543; public static final int JACK = 5544; public static final int JILL = 5545; public static final int JEFF_5546 = 5546; public static final int SCORPIAS_OFFSPRING = 5547; public static final int TROPICAL_WAGTAIL = 5548; public static final int CRIMSON_SWIFT = 5549; public static final int CERULEAN_TWITCH = 5550; public static final int GOLDEN_WARBLER = 5551; public static final int COPPER_LONGTAIL = 5552; public static final int BLACK_WARLOCK = 5553; public static final int SNOWY_KNIGHT = 5554; public static final int SAPPHIRE_GLACIALIS = 5555; public static final int RUBY_HARVEST = 5556; public static final int VENENATIS_SPIDERLING_5557 = 5557; public static final int CALLISTO_CUB_5558 = 5558; public static final int VETION_JR_5559 = 5559; public static final int VETION_JR_5560 = 5560; public static final int SCORPIAS_OFFSPRING_5561 = 5561; public static final int MERCY = 5562; public static final int ANGRY_BARBARIAN_SPIRIT = 5563; public static final int ENRAGED_BARBARIAN_SPIRIT = 5564; public static final int BERSERK_BARBARIAN_SPIRIT = 5565; public static final int FEROCIOUS_BARBARIAN_SPIRIT = 5566; public static final int DEATH = 5567; public static final int ZOMBIE_5568 = 5568; public static final int MOST_OF_A_ZOMBIE = 5569; public static final int MOST_OF_A_ZOMBIE_5570 = 5570; public static final int ZOMBIE_5571 = 5571; public static final int MOST_OF_A_ZOMBIE_5572 = 5572; public static final int ZOMBIE_HEAD = 5573; public static final int ZOMBIE_5574 = 5574; public static final int HALFZOMBIE = 5575; public static final int OTHER_HALFZOMBIE = 5576; public static final int CHILD_5577 = 5577; public static final int CHILD_5578 = 5578; public static final int CHILD_5579 = 5579; public static final int CHILD_5580 = 5580; public static final int CHILD_5581 = 5581; public static final int CHILD_5582 = 5582; public static final int ZOMBIE_5583 = 5583; public static final int WILY_CAT = 5584; public static final int WILY_CAT_5585 = 5585; public static final int WILY_CAT_5586 = 5586; public static final int WILY_CAT_5587 = 5587; public static final int WILY_CAT_5588 = 5588; public static final int WILY_CAT_5589 = 5589; public static final int WILY_HELLCAT = 5590; public static final int KITTEN_5591 = 5591; public static final int KITTEN_5592 = 5592; public static final int KITTEN_5593 = 5593; public static final int KITTEN_5594 = 5594; public static final int KITTEN_5595 = 5595; public static final int KITTEN_5596 = 5596; public static final int HELLKITTEN = 5597; public static final int OVERGROWN_CAT = 5598; public static final int OVERGROWN_CAT_5599 = 5599; public static final int OVERGROWN_CAT_5600 = 5600; public static final int OVERGROWN_CAT_5601 = 5601; public static final int OVERGROWN_CAT_5602 = 5602; public static final int OVERGROWN_CAT_5603 = 5603; public static final int OVERGROWN_HELLCAT = 5604; public static final int PEACEFUL_BARBARIAN_SPIRIT = 5605; public static final int MINER_5606 = 5606; public static final int MURPHY = 5607; public static final int MURPHY_5608 = 5608; public static final int MURPHY_5609 = 5609; public static final int MURPHY_5610 = 5610; public static final int SHARK_5611 = 5611; public static final int SHARK_5612 = 5612; public static final int SAM_5613 = 5613; public static final int RACHAEL = 5614; public static final int SWAMP_SNAKE = 5615; public static final int SWAMP_SNAKE_5616 = 5616; public static final int SWAMP_SNAKE_5617 = 5617; public static final int SWAMP_SNAKE_5618 = 5618; public static final int DEAD_SWAMP_SNAKE = 5619; public static final int DEAD_SWAMP_SNAKE_5620 = 5620; public static final int DEAD_SWAMP_SNAKE_5621 = 5621; public static final int GHAST_5622 = 5622; public static final int GHAST_5623 = 5623; public static final int GHAST_5624 = 5624; public static final int GHAST_5625 = 5625; public static final int GHAST_5626 = 5626; public static final int GHAST_5627 = 5627; public static final int GIANT_SNAIL = 5628; public static final int GIANT_SNAIL_5629 = 5629; public static final int GIANT_SNAIL_5630 = 5630; public static final int RIYL_SHADOW_5631 = 5631; public static final int ASYN_SHADOW_5632 = 5632; public static final int SHADE = 5633; public static final int VAMPYRE_JUVINATE_5634 = 5634; public static final int VAMPYRE_JUVINATE_5635 = 5635; public static final int VAMPYRE_JUVINATE_5636 = 5636; public static final int VAMPYRE_JUVINATE_5637 = 5637; public static final int VAMPYRE_JUVINATE_5638 = 5638; public static final int VAMPYRE_JUVINATE_5639 = 5639; public static final int FERAL_VAMPYRE_5640 = 5640; public static final int FERAL_VAMPYRE_5641 = 5641; public static final int FERAL_VAMPYRE_5642 = 5642; public static final int TENTACLE_5643 = 5643; public static final int HEAD = 5644; public static final int HEAD_5645 = 5645; public static final int TENTACLE_5646 = 5646; public static final int ZOMBIE_5647 = 5647; public static final int UNDEAD_LUMBERJACK = 5648; public static final int UNDEAD_LUMBERJACK_5649 = 5649; public static final int UNDEAD_LUMBERJACK_5650 = 5650; public static final int UNDEAD_LUMBERJACK_5651 = 5651; public static final int UNDEAD_LUMBERJACK_5652 = 5652; public static final int UNDEAD_LUMBERJACK_5653 = 5653; public static final int UNDEAD_LUMBERJACK_5654 = 5654; public static final int UNDEAD_LUMBERJACK_5655 = 5655; public static final int UNDEAD_LUMBERJACK_5656 = 5656; public static final int UNDEAD_LUMBERJACK_5657 = 5657; public static final int UNDEAD_LUMBERJACK_5658 = 5658; public static final int UNDEAD_LUMBERJACK_5659 = 5659; public static final int UNDEAD_LUMBERJACK_5660 = 5660; public static final int UNDEAD_LUMBERJACK_5661 = 5661; public static final int UNDEAD_LUMBERJACK_5662 = 5662; public static final int UNDEAD_LUMBERJACK_5663 = 5663; public static final int UNDEAD_LUMBERJACK_5665 = 5665; public static final int UNDEAD_LUMBERJACK_5666 = 5666; public static final int UNDEAD_LUMBERJACK_5667 = 5667; public static final int UNDEAD_LUMBERJACK_5668 = 5668; public static final int UNDEAD_LUMBERJACK_5669 = 5669; public static final int UNDEAD_LUMBERJACK_5670 = 5670; public static final int UNDEAD_LUMBERJACK_5671 = 5671; public static final int UNDEAD_LUMBERJACK_5672 = 5672; public static final int UNDEAD_LUMBERJACK_5673 = 5673; public static final int UNDEAD_LUMBERJACK_5674 = 5674; public static final int UNDEAD_LUMBERJACK_5675 = 5675; public static final int UNDEAD_LUMBERJACK_5676 = 5676; public static final int UNDEAD_LUMBERJACK_5677 = 5677; public static final int UNDEAD_LUMBERJACK_5678 = 5678; public static final int UNDEAD_LUMBERJACK_5679 = 5679; public static final int UNDEAD_LUMBERJACK_5680 = 5680; public static final int UNDEAD_LUMBERJACK_5681 = 5681; public static final int UNDEAD_LUMBERJACK_5682 = 5682; public static final int UNDEAD_LUMBERJACK_5683 = 5683; public static final int UNDEAD_LUMBERJACK_5684 = 5684; public static final int UNDEAD_LUMBERJACK_5685 = 5685; public static final int UNDEAD_LUMBERJACK_5686 = 5686; public static final int UNDEAD_LUMBERJACK_5687 = 5687; public static final int UNDEAD_LUMBERJACK_5688 = 5688; public static final int UNDEAD_LUMBERJACK_5689 = 5689; public static final int UNDEAD_LUMBERJACK_5690 = 5690; public static final int UNDEAD_LUMBERJACK_5691 = 5691; public static final int UNDEAD_LUMBERJACK_5692 = 5692; public static final int UNDEAD_LUMBERJACK_5693 = 5693; public static final int UNDEAD_LUMBERJACK_5694 = 5694; public static final int UNDEAD_LUMBERJACK_5695 = 5695; public static final int UNDEAD_LUMBERJACK_5696 = 5696; public static final int UNDEAD_LUMBERJACK_5697 = 5697; public static final int UNDEAD_LUMBERJACK_5698 = 5698; public static final int UNDEAD_LUMBERJACK_5699 = 5699; public static final int UNDEAD_LUMBERJACK_5700 = 5700; public static final int UNDEAD_LUMBERJACK_5701 = 5701; public static final int UNDEAD_LUMBERJACK_5702 = 5702; public static final int UNDEAD_LUMBERJACK_5703 = 5703; public static final int UNDEAD_LUMBERJACK_5704 = 5704; public static final int UNDEAD_LUMBERJACK_5705 = 5705; public static final int UNDEAD_LUMBERJACK_5706 = 5706; public static final int UNDEAD_LUMBERJACK_5707 = 5707; public static final int UNDEAD_LUMBERJACK_5708 = 5708; public static final int UNDEAD_LUMBERJACK_5709 = 5709; public static final int UNDEAD_LUMBERJACK_5710 = 5710; public static final int UNDEAD_LUMBERJACK_5711 = 5711; public static final int UNDEAD_LUMBERJACK_5712 = 5712; public static final int UNDEAD_LUMBERJACK_5713 = 5713; public static final int UNDEAD_LUMBERJACK_5714 = 5714; public static final int UNDEAD_LUMBERJACK_5715 = 5715; public static final int UNDEAD_LUMBERJACK_5716 = 5716; public static final int UNDEAD_LUMBERJACK_5717 = 5717; public static final int UNDEAD_LUMBERJACK_5718 = 5718; public static final int UNDEAD_LUMBERJACK_5719 = 5719; public static final int UNDEAD_LUMBERJACK_5720 = 5720; public static final int BARRICADE = 5722; public static final int BARRICADE_5723 = 5723; public static final int BARRICADE_5724 = 5724; public static final int BARRICADE_5725 = 5725; public static final int SHEEP_5726 = 5726; public static final int RABBIT_5727 = 5727; public static final int IMP_5728 = 5728; public static final int SHIPYARD_WORKER_5729 = 5729; public static final int MASTER_FARMER = 5730; public static final int MASTER_FARMER_5731 = 5731; public static final int MARKET_GUARD_5732 = 5732; public static final int ELNOCK_INQUISITOR = 5734; public static final int IMMENIZZ = 5735; public static final int FAIRY_AERYKA = 5736; public static final int WANDERING_IMPLING = 5737; public static final int IMP_DEFENDER = 5738; public static final int PENANCE_FIGHTER_5739 = 5739; public static final int PENANCE_FIGHTER_5740 = 5740; public static final int PENANCE_FIGHTER_5741 = 5741; public static final int PENANCE_FIGHTER_5742 = 5742; public static final int PENANCE_FIGHTER_5743 = 5743; public static final int PENANCE_FIGHTER_5744 = 5744; public static final int PENANCE_FIGHTER_5745 = 5745; public static final int PENANCE_FIGHTER_5746 = 5746; public static final int PENANCE_FIGHTER_5747 = 5747; public static final int PENANCE_RUNNER_5748 = 5748; public static final int PENANCE_RUNNER_5749 = 5749; public static final int PENANCE_RUNNER_5750 = 5750; public static final int PENANCE_RUNNER_5751 = 5751; public static final int PENANCE_RUNNER_5752 = 5752; public static final int PENANCE_RUNNER_5753 = 5753; public static final int PENANCE_RUNNER_5754 = 5754; public static final int PENANCE_RUNNER_5755 = 5755; public static final int PENANCE_RUNNER_5756 = 5756; public static final int PENANCE_RANGER_5757 = 5757; public static final int PENANCE_RANGER_5758 = 5758; public static final int PENANCE_RANGER_5759 = 5759; public static final int PENANCE_RANGER_5760 = 5760; public static final int PENANCE_RANGER_5761 = 5761; public static final int PENANCE_RANGER_5762 = 5762; public static final int PENANCE_RANGER_5763 = 5763; public static final int PENANCE_RANGER_5764 = 5764; public static final int PENANCE_RANGER_5765 = 5765; public static final int PENANCE_HEALER_5766 = 5766; public static final int PENANCE_HEALER_5767 = 5767; public static final int PENANCE_HEALER_5768 = 5768; public static final int PENANCE_HEALER_5769 = 5769; public static final int PENANCE_HEALER_5770 = 5770; public static final int PENANCE_HEALER_5771 = 5771; public static final int PENANCE_HEALER_5772 = 5772; public static final int PENANCE_HEALER_5773 = 5773; public static final int PENANCE_HEALER_5774 = 5774; public static final int PENANCE_QUEEN = 5775; public static final int QUEEN_SPAWN = 5776; public static final int EGG_LAUNCHER_5777 = 5777; public static final int EGG_LAUNCHER_5778 = 5778; public static final int GIANT_MOLE = 5779; public static final int BABY_MOLE = 5780; public static final int BABY_MOLE_5781 = 5781; public static final int BABY_MOLE_5782 = 5782; public static final int LIGHT_CREATURE_5783 = 5783; public static final int LIGHT_CREATURE_5784 = 5784; public static final int JUNA = 5785; public static final int SIMON_TEMPLETON = 5786; public static final int PYRAMID_BLOCK = 5787; public static final int PYRAMID_BLOCK_5788 = 5788; public static final int CAPN_IZZY_NOBEARD = 5789; public static final int RAULYN = 5790; public static final int GIANT_BAT_5791 = 5791; public static final int PARTY_PETE = 5792; public static final int KNIGHT_5793 = 5793; public static final int MEGAN = 5794; public static final int LUCY = 5795; public static final int WINTER_ELEMENTAL = 5796; public static final int WINTER_ELEMENTAL_5797 = 5797; public static final int WINTER_ELEMENTAL_5798 = 5798; public static final int WINTER_ELEMENTAL_5799 = 5799; public static final int WINTER_ELEMENTAL_5800 = 5800; public static final int WINTER_ELEMENTAL_5801 = 5801; public static final int AUTUMN_ELEMENTAL = 5802; public static final int AUTUMN_ELEMENTAL_5803 = 5803; public static final int AUTUMN_ELEMENTAL_5804 = 5804; public static final int AUTUMN_ELEMENTAL_5805 = 5805; public static final int AUTUMN_ELEMENTAL_5806 = 5806; public static final int AUTUMN_ELEMENTAL_5807 = 5807; public static final int REACHER_5808 = 5808; public static final int TANNER = 5809; public static final int MASTER_CRAFTER = 5810; public static final int MASTER_CRAFTER_5811 = 5811; public static final int MASTER_CRAFTER_5812 = 5812; public static final int MINER_5813 = 5813; public static final int MINER_5814 = 5814; public static final int BERT = 5815; public static final int YAK = 5816; public static final int ICEBERG = 5817; public static final int ICEBERG_5818 = 5818; public static final int BERT_5819 = 5819; public static final int FISHING_SPOT_5820 = 5820; public static final int FISHING_SPOT_5821 = 5821; public static final int ICE_TROLL_KING = 5822; public static final int ICE_TROLL_RUNT_5823 = 5823; public static final int ICE_TROLL_MALE_5824 = 5824; public static final int ICE_TROLL_FEMALE_5825 = 5825; public static final int ICE_TROLL_GRUNT_5826 = 5826; public static final int BORK_SIGMUNDSON = 5827; public static final int ICE_TROLL_RUNT_5828 = 5828; public static final int ICE_TROLL_MALE_5829 = 5829; public static final int ICE_TROLL_FEMALE_5830 = 5830; public static final int ICE_TROLL_GRUNT_5831 = 5831; public static final int MARTIN_THE_MASTER_GARDENER = 5832; public static final int FROG_5833 = 5833; public static final int STORM_CLOUD_5834 = 5834; public static final int COORDINATOR = 5835; public static final int FAIRY_NUFF_5836 = 5836; public static final int FAIRY_GODFATHER_5837 = 5837; public static final int SLIM_LOUIE = 5838; public static final int FAT_ROCCO = 5839; public static final int GATEKEEPER = 5840; public static final int ZANDAR_HORFYRE = 5841; public static final int COW_5842 = 5842; public static final int SHEEP_5843 = 5843; public static final int SHEEP_5844 = 5844; public static final int SHEEP_5845 = 5845; public static final int SHEEP_5846 = 5846; public static final int ZANARIS_CHOIR = 5847; public static final int TANGLEFOOT = 5848; public static final int BABY_TANGLEFOOT = 5853; public static final int BABY_TANGLEFOOT_5854 = 5854; public static final int GATEKEEPER_5855 = 5855; public static final int FAIRY_CHEF = 5856; public static final int CERBERUS = 5862; public static final int CERBERUS_5863 = 5863; public static final int CAPTAIN_NED_5864 = 5864; public static final int CERBERUS_5866 = 5866; public static final int SUMMONED_SOUL = 5867; public static final int SUMMONED_SOUL_5868 = 5868; public static final int SUMMONED_SOUL_5869 = 5869; public static final int KEY_MASTER = 5870; public static final int KING_ARTHUR_5871 = 5871; public static final int BABY_GREEN_DRAGON_5872 = 5872; public static final int BABY_GREEN_DRAGON_5873 = 5873; public static final int BLACK_DEMON_5874 = 5874; public static final int BLACK_DEMON_5875 = 5875; public static final int BLACK_DEMON_5876 = 5876; public static final int BLACK_DEMON_5877 = 5877; public static final int BLUE_DRAGON_5878 = 5878; public static final int BLUE_DRAGON_5879 = 5879; public static final int BLUE_DRAGON_5880 = 5880; public static final int BLUE_DRAGON_5881 = 5881; public static final int BLUE_DRAGON_5882 = 5882; public static final int ABYSSAL_ORPHAN = 5883; public static final int ABYSSAL_ORPHAN_5884 = 5884; public static final int ABYSSAL_SIRE = 5886; public static final int ABYSSAL_SIRE_5887 = 5887; public static final int ABYSSAL_SIRE_5888 = 5888; public static final int ABYSSAL_SIRE_5889 = 5889; public static final int ABYSSAL_SIRE_5890 = 5890; public static final int ABYSSAL_SIRE_5891 = 5891; public static final int TZREKJAD = 5892; public static final int TZREKJAD_5893 = 5893; public static final int BAST = 5894; public static final int DROGO_DWARF = 5895; public static final int FLYNN = 5896; public static final int WAYNE = 5897; public static final int DWARF_5904 = 5904; public static final int BETTY_5905 = 5905; public static final int PROBITA = 5906; public static final int CHAOS_ELEMENTAL_JR_5907 = 5907; public static final int ABYSSAL_SIRE_5908 = 5908; public static final int TENTACLE_5909 = 5909; public static final int TENTACLE_5910 = 5910; public static final int TENTACLE_5911 = 5911; public static final int TENTACLE_5912 = 5912; public static final int TENTACLE_5913 = 5913; public static final int RESPIRATORY_SYSTEM = 5914; public static final int VENT = 5915; public static final int SPAWN = 5916; public static final int SPAWN_5917 = 5917; public static final int SCION = 5918; public static final int GRACE = 5919; public static final int MARK = 5920; public static final int BIGREDJAPAN = 5921; public static final int SKULLBALL = 5922; public static final int SKULLBALL_BOSS = 5923; public static final int AGILITY_BOSS = 5924; public static final int SKULLBALL_TRAINER = 5925; public static final int AGILITY_TRAINER = 5926; public static final int AGILITY_TRAINER_5927 = 5927; public static final int WEREWOLF_5928 = 5928; public static final int KNIGHT_5929 = 5929; public static final int EGG_5932 = 5932; public static final int EGG_5933 = 5933; public static final int EGG_5934 = 5934; public static final int SAND_CRAB = 5935; public static final int SANDY_ROCKS = 5936; public static final int JARVALD = 5937; public static final int WALLASALKI = 5938; public static final int WALLASALKI_5939 = 5939; public static final int GIANT_ROCK_CRAB_5940 = 5940; public static final int BOULDER_5941 = 5941; public static final int DAGANNOTH_5942 = 5942; public static final int DAGANNOTH_5943 = 5943; public static final int ROCK_LOBSTER = 5944; public static final int ROCK_5945 = 5945; public static final int SUSPICIOUS_WATER = 5946; public static final int SPINOLYP = 5947; public static final int SUSPICIOUS_WATER_5948 = 5948; public static final int AL_THE_CAMEL = 5949; public static final int ELLY_THE_CAMEL = 5950; public static final int OLLIE_THE_CAMEL = 5951; public static final int CAM_THE_CAMEL = 5952; public static final int ALICE_THE_CAMEL = 5954; public static final int NEFERTI_THE_CAMEL = 5955; public static final int ALI_THE_LEAFLET_DROPPER = 5956; public static final int ALI_THE_SMITH = 5957; public static final int ALI_THE_FARMER = 5958; public static final int ALI_THE_TAILOR = 5959; public static final int ALI_THE_GUARD = 5960; public static final int SPINOLYP_5961 = 5961; public static final int SUSPICIOUS_WATER_5962 = 5962; public static final int SPINOLYP_5963 = 5963; public static final int KHAZARD_TROOPER_5964 = 5964; public static final int KHAZARD_TROOPER_5965 = 5965; public static final int GNOME_TROOP_5966 = 5966; public static final int GNOME_TROOP_5967 = 5967; public static final int GNOME_5968 = 5968; public static final int GNOME_5969 = 5969; public static final int GNOME_5970 = 5970; public static final int MOUNTED_TERRORBIRD_GNOME_5971 = 5971; public static final int MOUNTED_TERRORBIRD_GNOME_5972 = 5972; public static final int MOUNTED_TERRORBIRD_GNOME_5973 = 5973; public static final int SWEEPER = 5974; public static final int FLYING_BOOK = 5975; public static final int FLYING_BOOK_5976 = 5976; public static final int JUSTICIAR_ZACHARIAH = 5977; public static final int ENTRANCE_GUARDIAN = 5978; public static final int TELEKINETIC_GUARDIAN = 5979; public static final int ALCHEMY_GUARDIAN = 5980; public static final int ENCHANTMENT_GUARDIAN = 5981; public static final int GRAVEYARD_GUARDIAN = 5982; public static final int PET_ROCK = 5983; public static final int REWARDS_GUARDIAN = 5984; public static final int CHARMED_WARRIOR = 5985; public static final int CHARMED_WARRIOR_5986 = 5986; public static final int CHARMED_WARRIOR_5987 = 5987; public static final int CHARMED_WARRIOR_5988 = 5988; public static final int SECRETARY = 5989; public static final int PURPLE_PEWTER_SECRETARY = 5990; public static final int YELLOW_FORTUNE_SECRETARY = 5991; public static final int BLUE_OPAL_SECRETARY = 5992; public static final int GREEN_GEMSTONE_SECRETARY = 5993; public static final int WHITE_CHISEL_SECRETARY = 5994; public static final int SILVER_COG_SECRETARY = 5995; public static final int BROWN_ENGINE_SECRETARY = 5996; public static final int RED_AXE_SECRETARY = 5997; public static final int PURPLE_PEWTER_DIRECTOR_5998 = 5998; public static final int BLUE_OPAL_DIRECTOR_5999 = 5999; public static final int YELLOW_FORTUNE_DIRECTOR_6000 = 6000; public static final int ORLANDO_SMITH = 6001; public static final int NATURAL_HISTORIAN = 6002; public static final int NATURAL_HISTORIAN_6003 = 6003; public static final int NATURAL_HISTORIAN_6004 = 6004; public static final int NATURAL_HISTORIAN_6005 = 6005; public static final int NATURAL_HISTORIAN_6006 = 6006; public static final int LEECH_DISPLAY = 6007; public static final int SEA_SLUGS_DISPLAY = 6008; public static final int SNAIL_DISPLAY = 6009; public static final int MONKEY_DISPLAY = 6010; public static final int LIZARD_DISPLAY = 6011; public static final int PENGUIN_DISPLAY = 6012; public static final int CAMEL_DISPLAY = 6013; public static final int TERRORBIRD_DISPLAY = 6014; public static final int DRAGON_DISPLAY = 6015; public static final int WYVERN_DISPLAY = 6016; public static final int BATTLE_TORTOISE_DISPLAY = 6017; public static final int MOLE_DISPLAY = 6018; public static final int TORRCS = 6019; public static final int MARFET = 6020; public static final int GREEN_GEMSTONE_DIRECTOR_6021 = 6021; public static final int WHITE_CHISEL_DIRECTOR_6022 = 6022; public static final int SILVER_COG_DIRECTOR_6023 = 6023; public static final int BROWN_ENGINE_DIRECTOR_6024 = 6024; public static final int RED_AXE_DIRECTOR_6025 = 6025; public static final int RED_AXE_CAT_6026 = 6026; public static final int TRADER = 6027; public static final int TRADER_6028 = 6028; public static final int TRADER_6029 = 6029; public static final int TRADER_6030 = 6030; public static final int TRADER_6031 = 6031; public static final int TRADER_6032 = 6032; public static final int TRADER_6033 = 6033; public static final int TRADER_6034 = 6034; public static final int TRADER_6035 = 6035; public static final int TRADER_6036 = 6036; public static final int TRADER_6037 = 6037; public static final int TRADER_6038 = 6038; public static final int TRADER_6039 = 6039; public static final int TRADER_6040 = 6040; public static final int TRADER_6041 = 6041; public static final int TRADER_6042 = 6042; public static final int TRADE_REFEREE = 6043; public static final int SUPREME_COMMANDER = 6044; public static final int COMMANDER_VELDABAN_6045 = 6045; public static final int BLACK_GUARD_6046 = 6046; public static final int BLACK_GUARD_6047 = 6047; public static final int BLACK_GUARD_6048 = 6048; public static final int BLACK_GUARD_6049 = 6049; public static final int BLACK_GUARD_BERSERKER_6050 = 6050; public static final int BLACK_GUARD_BERSERKER_6051 = 6051; public static final int BLACK_GUARD_BERSERKER_6052 = 6052; public static final int GNOME_EMISSARY_6053 = 6053; public static final int GNOME_TRAVELLER = 6054; public static final int GNOME_TRAVELLER_6055 = 6055; public static final int GUARD_6056 = 6056; public static final int RANGING_GUILD_DOORMAN = 6057; public static final int LEATHERWORKER = 6058; public static final int ARMOUR_SALESMAN = 6059; public static final int BOW_AND_ARROW_SALESMAN = 6060; public static final int TOWER_ADVISOR = 6061; public static final int TOWER_ADVISOR_6062 = 6062; public static final int TOWER_ADVISOR_6063 = 6063; public static final int TOWER_ADVISOR_6064 = 6064; public static final int TOWER_ARCHER = 6065; public static final int TOWER_ARCHER_6066 = 6066; public static final int TOWER_ARCHER_6067 = 6067; public static final int TOWER_ARCHER_6068 = 6068; public static final int TRIBAL_WEAPON_SALESMAN = 6069; public static final int COMPETITION_JUDGE = 6070; public static final int TICKET_MERCHANT = 6071; public static final int JIMMY = 6072; public static final int REF = 6073; public static final int REF_6074 = 6074; public static final int TORTOISE = 6075; public static final int TORTOISE_6076 = 6076; public static final int GNOME_CHILD = 6077; public static final int GNOME_CHILD_6078 = 6078; public static final int GNOME_CHILD_6079 = 6079; public static final int GNOME_TRAINER = 6080; public static final int GNOME_GUARD_6081 = 6081; public static final int GNOME_GUARD_6082 = 6082; public static final int GNOME_SHOP_KEEPER_6083 = 6083; public static final int GNOME_BANKER = 6084; public static final int GNOME_BALLER_6085 = 6085; public static final int GNOME_WOMAN = 6086; public static final int GNOME_WOMAN_6087 = 6087; public static final int CAPTAIN_ERRDO = 6088; public static final int GNOME_6094 = 6094; public static final int GNOME_6095 = 6095; public static final int GNOME_6096 = 6096; public static final int GNOME_ARCHER = 6097; public static final int GNOME_DRIVER = 6098; public static final int GNOME_MAGE = 6099; public static final int LIEUTENANT_SCHEPBUR = 6100; public static final int TRAINER_NACKLEPEN = 6101; public static final int BUSH_SNAKE = 6102; public static final int BUSH_SNAKE_6103 = 6103; public static final int ELVARG_HARD = 6118; public static final int THE_INADEQUACY_HARD = 6119; public static final int THE_EVERLASTING_HARD = 6120; public static final int THE_UNTOUCHABLE_HARD = 6121; public static final int URIUM_SHADOW = 6143; public static final int SCION_6177 = 6177; public static final int JUNGLE_SPIDER_6267 = 6267; public static final int JUNGLE_SPIDER_6271 = 6271; public static final int LARGE_MOSQUITO = 6272; public static final int MOSQUITO_SWARM = 6273; public static final int TANGLEFOOT_HARD = 6291; public static final int CHRONOZON_HARD = 6292; public static final int BOUNCER_HARD = 6293; public static final int ICE_TROLL_KING_HARD = 6294; public static final int BLACK_DEMON_HARD = 6295; public static final int BLOODHOUND = 6296; public static final int GLOD_HARD = 6297; public static final int TREUS_DAYTH_HARD = 6298; public static final int BLACK_KNIGHT_TITAN_HARD = 6299; public static final int DAGANNOTH_MOTHER_HARD = 6300; public static final int DAGANNOTH_MOTHER_HARD_6301 = 6301; public static final int DAGANNOTH_MOTHER_HARD_6302 = 6302; public static final int DAGANNOTH_MOTHER_HARD_6303 = 6303; public static final int DAGANNOTH_MOTHER_HARD_6304 = 6304; public static final int DAGANNOTH_MOTHER_HARD_6305 = 6305; public static final int EVIL_CHICKEN_HARD = 6306; public static final int CULINAROMANCER_HARD = 6307; public static final int AGRITHNANA_HARD = 6308; public static final int FLAMBEED_HARD = 6309; public static final int KARAMEL_HARD = 6310; public static final int DESSOURT_HARD = 6311; public static final int GELATINNOTH_MOTHER_HARD = 6312; public static final int GELATINNOTH_MOTHER_HARD_6313 = 6313; public static final int GELATINNOTH_MOTHER_HARD_6314 = 6314; public static final int GELATINNOTH_MOTHER_HARD_6315 = 6315; public static final int GELATINNOTH_MOTHER_HARD_6316 = 6316; public static final int GELATINNOTH_MOTHER_HARD_6317 = 6317; public static final int NEZIKCHENED_HARD = 6318; public static final int TREE_SPIRIT_HARD = 6319; public static final int ME_HARD = 6320; public static final int JUNGLE_DEMON_HARD = 6321; public static final int THE_KENDAL_HARD = 6322; public static final int GIANT_ROC_HARD = 6323; public static final int SLAGILITH_HARD = 6324; public static final int MOSS_GUARDIAN_HARD = 6325; public static final int SKELETON_HELLHOUND_HARD = 6326; public static final int AGRITH_NAAR_HARD = 6327; public static final int KING_ROALD_HARD = 6328; public static final int KHAZARD_WARLORD_HARD = 6329; public static final int DAD_HARD = 6330; public static final int ARRG_HARD = 6331; public static final int COUNT_DRAYNOR_HARD = 6332; public static final int WITCHS_EXPERIMENT_HARD = 6333; public static final int WITCHS_EXPERIMENT_SECOND_FORM_HARD = 6334; public static final int WITCHS_EXPERIMENT_THIRD_FORM_HARD = 6335; public static final int WITCHS_EXPERIMENT_FOURTH_FORM_HARD = 6336; public static final int NAZASTAROOL_HARD = 6337; public static final int NAZASTAROOL_HARD_6338 = 6338; public static final int NAZASTAROOL_HARD_6339 = 6339; public static final int COW_HARD = 6340; public static final int ZAPPER = 6341; public static final int BARRELCHEST_6342 = 6342; public static final int GIANT_SCARAB_6343 = 6343; public static final int DESSOUS_6344 = 6344; public static final int KAMIL_6345 = 6345; public static final int DAMIS_6346 = 6346; public static final int DAMIS_6347 = 6347; public static final int FAREED_6348 = 6348; public static final int ELVARG_6349 = 6349; public static final int THE_INADEQUACY_6350 = 6350; public static final int THE_EVERLASTING_6351 = 6351; public static final int THE_UNTOUCHABLE_6352 = 6352; public static final int TANGLEFOOT_6353 = 6353; public static final int CHRONOZON_6354 = 6354; public static final int BOUNCER_6355 = 6355; public static final int ICE_TROLL_KING_6356 = 6356; public static final int BLACK_DEMON_6357 = 6357; public static final int GLOD_6358 = 6358; public static final int TREUS_DAYTH_6359 = 6359; public static final int BLACK_KNIGHT_TITAN_6360 = 6360; public static final int DAGANNOTH_MOTHER_6361 = 6361; public static final int DAGANNOTH_MOTHER_6362 = 6362; public static final int DAGANNOTH_MOTHER_6363 = 6363; public static final int DAGANNOTH_MOTHER_6364 = 6364; public static final int DAGANNOTH_MOTHER_6365 = 6365; public static final int DAGANNOTH_MOTHER_6366 = 6366; public static final int EVIL_CHICKEN_6367 = 6367; public static final int CULINAROMANCER_6368 = 6368; public static final int AGRITHNANA_6369 = 6369; public static final int FLAMBEED_6370 = 6370; public static final int KARAMEL_6371 = 6371; public static final int DESSOURT_6372 = 6372; public static final int GELATINNOTH_MOTHER_6373 = 6373; public static final int GELATINNOTH_MOTHER_6374 = 6374; public static final int GELATINNOTH_MOTHER_6375 = 6375; public static final int GELATINNOTH_MOTHER_6376 = 6376; public static final int GELATINNOTH_MOTHER_6377 = 6377; public static final int GELATINNOTH_MOTHER_6378 = 6378; public static final int NEZIKCHENED_6379 = 6379; public static final int TREE_SPIRIT_6380 = 6380; public static final int ME_6381 = 6381; public static final int JUNGLE_DEMON_6382 = 6382; public static final int THE_KENDAL_6383 = 6383; public static final int GIANT_ROC_6384 = 6384; public static final int SLAGILITH_6385 = 6385; public static final int MOSS_GUARDIAN_6386 = 6386; public static final int SKELETON_HELLHOUND_6387 = 6387; public static final int AGRITH_NAAR_6388 = 6388; public static final int KING_ROALD_6389 = 6389; public static final int KHAZARD_WARLORD = 6390; public static final int DAD_6391 = 6391; public static final int ARRG_6392 = 6392; public static final int COUNT_DRAYNOR_6393 = 6393; public static final int WITCHS_EXPERIMENT_6394 = 6394; public static final int WITCHS_EXPERIMENT_SECOND_FORM_6395 = 6395; public static final int WITCHS_EXPERIMENT_THIRD_FORM_6396 = 6396; public static final int WITCHS_EXPERIMENT_FOURTH_FORM_6397 = 6397; public static final int NAZASTAROOL_6398 = 6398; public static final int NAZASTAROOL_6399 = 6399; public static final int NAZASTAROOL_6400 = 6400; public static final int COW_6401 = 6401; public static final int MOSQUITO_SWARM_6402 = 6402; public static final int TRIBESMAN_6406 = 6406; public static final int TRIBESMAN_6407 = 6407; public static final int BROODOO_VICTIM = 6408; public static final int BROODOO_VICTIM_6409 = 6409; public static final int BROODOO_VICTIM_6410 = 6410; public static final int BROODOO_VICTIM_6411 = 6411; public static final int BROODOO_VICTIM_6412 = 6412; public static final int BROODOO_VICTIM_6413 = 6413; public static final int SHARIMIKA = 6414; public static final int SHARIMIKA_6415 = 6415; public static final int MAMMA_BUFETTA = 6416; public static final int MAMMA_BUFETTA_6417 = 6417; public static final int LAYLEEN = 6418; public static final int LAYLEEN_6419 = 6419; public static final int KARADAY = 6420; public static final int KARADAY_6421 = 6421; public static final int SAFTA_DOC = 6422; public static final int SAFTA_DOC_6423 = 6423; public static final int GABOOTY = 6424; public static final int GABOOTY_6425 = 6425; public static final int FANELLAMAN = 6426; public static final int FANELLAMAN_6427 = 6427; public static final int JAGBAKOBA_6428 = 6428; public static final int JAGBAKOBA_6429 = 6429; public static final int MURCAILY_6430 = 6430; public static final int MURCAILY_6431 = 6431; public static final int RIONASTA = 6432; public static final int RIONASTA_6433 = 6433; public static final int CAVE_GOBLIN_6434 = 6434; public static final int CAVE_GOBLIN_6435 = 6435; public static final int CAVE_GOBLIN_6436 = 6436; public static final int CAVE_GOBLIN_6437 = 6437; public static final int ANIMATED_STEEL_ARMOUR_6438 = 6438; public static final int AMY = 6439; public static final int GIANT_SKELETON_6440 = 6440; public static final int SKELETON_6441 = 6441; public static final int SKELETON_6442 = 6442; public static final int SKELETON_6443 = 6443; public static final int SKELETON_6444 = 6444; public static final int SKELETON_6445 = 6445; public static final int SKELETON_6446 = 6446; public static final int SKELETON_6447 = 6447; public static final int SKELETON_6448 = 6448; public static final int ZOMBIE_6449 = 6449; public static final int ZOMBIE_6450 = 6450; public static final int ZOMBIE_6451 = 6451; public static final int ZOMBIE_6452 = 6452; public static final int ZOMBIE_6453 = 6453; public static final int ZOMBIE_6454 = 6454; public static final int ZOMBIE_6455 = 6455; public static final int ZOMBIE_6456 = 6456; public static final int ZOMBIE_6457 = 6457; public static final int ZOMBIE_6458 = 6458; public static final int ZOMBIE_6459 = 6459; public static final int ZOMBIE_6460 = 6460; public static final int ZOMBIE_6461 = 6461; public static final int ZOMBIE_6462 = 6462; public static final int ZOMBIE_6463 = 6463; public static final int ZOMBIE_6464 = 6464; public static final int ZOMBIE_6465 = 6465; public static final int ZOMBIE_6466 = 6466; public static final int SKELETON_6467 = 6467; public static final int SKELETON_6468 = 6468; public static final int POSSESSED_PICKAXE_6469 = 6469; public static final int ANIMATED_SPADE = 6470; public static final int TERROR_DOG_STATUE = 6471; public static final int TERROR_DOG_STATUE_6472 = 6472; public static final int TERROR_DOG = 6473; public static final int TERROR_DOG_6474 = 6474; public static final int TARN = 6475; public static final int TARN_6476 = 6476; public static final int MUTANT_TARN = 6477; public static final int RUFUS_6478 = 6478; public static final int EYE = 6479; public static final int EYE_6480 = 6480; public static final int MAC = 6481; public static final int BOULDER_6482 = 6482; public static final int MONKEY_6483 = 6483; public static final int GELIN = 6484; public static final int FINANCIAL_SEER = 6485; public static final int FISHING_SPOT_6488 = 6488; public static final int KREEARRA_6492 = 6492; public static final int COMMANDER_ZILYANA_6493 = 6493; public static final int GENERAL_GRAARDOR_6494 = 6494; public static final int KRIL_TSUTSAROTH_6495 = 6495; public static final int DAGANNOTH_SUPREME_6496 = 6496; public static final int DAGANNOTH_PRIME_6497 = 6497; public static final int DAGANNOTH_REX_6498 = 6498; public static final int GIANT_MOLE_6499 = 6499; public static final int KALPHITE_QUEEN_6500 = 6500; public static final int KALPHITE_QUEEN_6501 = 6501; public static final int KING_BLACK_DRAGON_6502 = 6502; public static final int CALLISTO = 6503; public static final int VENENATIS = 6504; public static final int CHAOS_ELEMENTAL_6505 = 6505; public static final int TZTOKJAD_6506 = 6506; public static final int SQUIRE_6509 = 6509; public static final int FINANCIAL_WIZARD = 6510; public static final int MAGNUS_GRAM = 6512; public static final int MAGNUS_GRAM_6513 = 6513; public static final int FINANCIAL_WIZARD_6514 = 6514; public static final int FINANCIAL_WIZARD_6515 = 6515; public static final int FINANCIAL_WIZARD_6516 = 6516; public static final int FINANCIAL_WIZARD_6517 = 6517; public static final int FINANCIAL_WIZARD_6518 = 6518; public static final int FINANCIAL_WIZARD_6519 = 6519; public static final int BARKER = 6524; public static final int FIDELIO = 6525; public static final int SBOTT = 6526; public static final int ROAVAR = 6527; public static final int HERQUIN = 6529; public static final int ROMMIK = 6530; public static final int BLURBERRY = 6531; public static final int BARMAN_6532 = 6532; public static final int ROMILY_WEAKLAX = 6533; public static final int GUARD_6561 = 6561; public static final int PROSPECTOR_PERCY = 6562; public static final int PAYDIRT = 6564; public static final int MINER_6565 = 6565; public static final int RUNITE_MINOR = 6566; public static final int MINER_6567 = 6567; public static final int MINER_6568 = 6568; public static final int MINER_6569 = 6569; public static final int MINER_6570 = 6570; public static final int MINER_6571 = 6571; public static final int MINER_6572 = 6572; public static final int GNOME_GUARD_6574 = 6574; public static final int GUARD_6575 = 6575; public static final int GUARD_6576 = 6576; public static final int GUARD_6579 = 6579; public static final int GUARD_6580 = 6580; public static final int GUARD_6581 = 6581; public static final int GUARD_6582 = 6582; public static final int GUARD_6583 = 6583; public static final int URI_6584 = 6584; public static final int SHERLOCK = 6586; public static final int ARMADYLEAN_GUARD = 6587; public static final int BANDOSIAN_GUARD = 6588; public static final int DR_FORD = 6589; public static final int SISTER_SCAROPHIA = 6590; public static final int LAVA_DRAGON = 6593; public static final int ENT = 6594; public static final int PRIFDDINAS_GUARD = 6595; public static final int ZOMBIE_6596 = 6596; public static final int ZOMBIE_6597 = 6597; public static final int ZOMBIE_6598 = 6598; public static final int MANDRITH = 6599; public static final int RUNITE_GOLEM = 6600; public static final int ROCKS_6601 = 6601; public static final int NUMPTY = 6602; public static final int ROGUE_6603 = 6603; public static final int MAMMOTH = 6604; public static final int BANDIT_6605 = 6605; public static final int DARK_WARRIOR_6606 = 6606; public static final int ELDER_CHAOS_DRUID = 6607; public static final int ANKOU_6608 = 6608; public static final int CALLISTO_6609 = 6609; public static final int VENENATIS_6610 = 6610; public static final int VETION = 6611; public static final int VETION_REBORN = 6612; public static final int SKELETON_HELLHOUND_6613 = 6613; public static final int GREATER_SKELETON_HELLHOUND = 6614; public static final int SCORPIA = 6615; public static final int SCORPIAS_OFFSPRING_6616 = 6616; public static final int SCORPIAS_GUARDIAN = 6617; public static final int CRAZY_ARCHAEOLOGIST = 6618; public static final int CHAOS_FANATIC = 6619; public static final int MINIATURE_CHAOTIC_CLOUDS = 6620; public static final int BOULDER_6621 = 6621; public static final int ENERGY_SPRITE = 6624; public static final int REACHER_6625 = 6625; public static final int DAGANNOTH_SUPREME_JR = 6626; public static final int DAGANNOTH_PRIME_JR = 6627; public static final int DAGANNOTH_SUPREME_JR_6628 = 6628; public static final int DAGANNOTH_PRIME_JR_6629 = 6629; public static final int DAGANNOTH_REX_JR = 6630; public static final int KREEARRA_JR = 6631; public static final int GENERAL_GRAARDOR_JR = 6632; public static final int ZILYANA_JR = 6633; public static final int KRIL_TSUTSAROTH_JR = 6634; public static final int BABY_MOLE_6635 = 6635; public static final int PRINCE_BLACK_DRAGON = 6636; public static final int KALPHITE_PRINCESS = 6637; public static final int KALPHITE_PRINCESS_6638 = 6638; public static final int SMOKE_DEVIL_6639 = 6639; public static final int KRAKEN_6640 = 6640; public static final int DAGANNOTH_REX_JR_6641 = 6641; public static final int PENANCE_PET = 6642; public static final int KREEARRA_JR_6643 = 6643; public static final int GENERAL_GRAARDOR_JR_6644 = 6644; public static final int MINER_6645 = 6645; public static final int ZILYANA_JR_6646 = 6646; public static final int KRIL_TSUTSAROTH_JR_6647 = 6647; public static final int LOKAR_SEARUNNER_6648 = 6648; public static final int CAPTAIN_BENTLEY = 6649; public static final int CAPTAIN_BENTLEY_6650 = 6650; public static final int BABY_MOLE_6651 = 6651; public static final int PRINCE_BLACK_DRAGON_6652 = 6652; public static final int KALPHITE_PRINCESS_6653 = 6653; public static final int KALPHITE_PRINCESS_6654 = 6654; public static final int SMOKE_DEVIL_6655 = 6655; public static final int KRAKEN_6656 = 6656; public static final int PET_ROCK_6657 = 6657; public static final int FISHBOWL = 6658; public static final int FISHBOWL_6659 = 6659; public static final int FISHBOWL_6660 = 6660; public static final int CLOCKWORK_CAT_6661 = 6661; public static final int CAT_6662 = 6662; public static final int CAT_6663 = 6663; public static final int CAT_6664 = 6664; public static final int CAT_6665 = 6665; public static final int CAT_6666 = 6666; public static final int CAT_6667 = 6667; public static final int HELLCAT_6668 = 6668; public static final int JOHN = 6669; public static final int REACHER_6670 = 6670; public static final int JOHN_6671 = 6671; public static final int JOHN_6672 = 6672; public static final int REACHER_6673 = 6673; public static final int PENANCE_PET_6674 = 6674; public static final int WAYDAR_6675 = 6675; public static final int OVERGROWN_CAT_6676 = 6676; public static final int OVERGROWN_CAT_6677 = 6677; public static final int OVERGROWN_CAT_6678 = 6678; public static final int OVERGROWN_CAT_6679 = 6679; public static final int OVERGROWN_CAT_6680 = 6680; public static final int OVERGROWN_CAT_6681 = 6681; public static final int OVERGROWN_HELLCAT_6682 = 6682; public static final int LAZY_CAT_6683 = 6683; public static final int LAZY_CAT_6684 = 6684; public static final int LAZY_CAT_6685 = 6685; public static final int LAZY_CAT_6686 = 6686; public static final int LAZY_CAT_6687 = 6687; public static final int LAZY_CAT_6688 = 6688; public static final int LAZY_HELLCAT_6689 = 6689; public static final int WILY_CAT_6690 = 6690; public static final int WILY_CAT_6691 = 6691; public static final int WILY_CAT_6692 = 6692; public static final int WILY_CAT_6693 = 6693; public static final int WILY_CAT_6694 = 6694; public static final int WILY_CAT_6695 = 6695; public static final int WILY_HELLCAT_6696 = 6696; public static final int GHOST_GUARD_6698 = 6698; public static final int GUARD_6699 = 6699; public static final int GUARD_6700 = 6700; public static final int GUARD_6701 = 6701; public static final int GUARD_6702 = 6702; public static final int FINANCIAL_WIZARD_6703 = 6703; public static final int HERON = 6715; public static final int CHAOTIC_DEATH_SPAWN = 6716; public static final int BEAVER = 6717; public static final int BABY_CHINCHOMPA = 6718; public static final int BABY_CHINCHOMPA_6719 = 6719; public static final int BABY_CHINCHOMPA_6720 = 6720; public static final int BABY_CHINCHOMPA_6721 = 6721; public static final int HERON_6722 = 6722; public static final int CHAOTIC_DEATH_SPAWN_6723 = 6723; public static final int BEAVER_6724 = 6724; public static final int ROCK_GOLEM_6725 = 6725; public static final int ROCK_GOLEM_6726 = 6726; public static final int ROCK_GOLEM_6727 = 6727; public static final int ROCK_GOLEM_6728 = 6728; public static final int ROCK_GOLEM_6729 = 6729; public static final int ROCK_GOLEM_6730 = 6730; public static final int FISHING_SPOT_6731 = 6731; public static final int RIVER_TROLL = 6732; public static final int RIVER_TROLL_6733 = 6733; public static final int RIVER_TROLL_6734 = 6734; public static final int RIVER_TROLL_6735 = 6735; public static final int RIVER_TROLL_6736 = 6736; public static final int RIVER_TROLL_6737 = 6737; public static final int POSTIE_PETE_6738 = 6738; public static final int EVIL_CHICKEN_6739 = 6739; public static final int SHADE_6740 = 6740; public static final int ZOMBIE_6741 = 6741; public static final int MYSTERIOUS_OLD_MAN_6742 = 6742; public static final int SERGEANT_DAMIEN_6743 = 6743; public static final int FLIPPA_6744 = 6744; public static final int LEO = 6745; public static final int LEO_6746 = 6746; public static final int BEE_KEEPER_6747 = 6747; public static final int FREAKY_FORESTER_6748 = 6748; public static final int DUNCE_6749 = 6749; public static final int MYSTERIOUS_OLD_MAN_6750 = 6750; public static final int MYSTERIOUS_OLD_MAN_6751 = 6751; public static final int MYSTERIOUS_OLD_MAN_6752 = 6752; public static final int MYSTERIOUS_OLD_MAN_6753 = 6753; public static final int EVIL_BOB_6754 = 6754; public static final int QUIZ_MASTER_6755 = 6755; public static final int BABY_CHINCHOMPA_6756 = 6756; public static final int BABY_CHINCHOMPA_6757 = 6757; public static final int BABY_CHINCHOMPA_6758 = 6758; public static final int BABY_CHINCHOMPA_6759 = 6759; public static final int PYRELORD = 6762; public static final int LIZARDMAN_SHAMAN = 6766; public static final int LIZARDMAN_SHAMAN_6767 = 6767; public static final int SPAWN_6768 = 6768; public static final int OSTEN = 6769; public static final int ARCIS = 6770; public static final int DREW = 6771; public static final int LOVADA = 6772; public static final int DOOMSAYER = 6773; public static final int DOOMSAYER_6774 = 6774; public static final int GALLOW = 6775; public static final int MAN_6776 = 6776; public static final int MAZE_GUARDIAN = 6777; public static final int MAZE_GUARDIAN_6779 = 6779; public static final int PILIAR = 6780; public static final int SHAYDA = 6781; public static final int FISHING_SPOT_6784 = 6784; public static final int HOSA = 6785; public static final int HELLRAT_BEHEMOTH = 6793; public static final int MONKEY_ARCHER_6794 = 6794; public static final int PYRELORD_6795 = 6795; public static final int NIEVE = 6797; public static final int STEVE = 6798; public static final int STEVE_6799 = 6799; public static final int PIEVE = 6801; public static final int COMBAT_TEST = 6802; public static final int MANIACAL_MONKEY = 6803; public static final int KRUK_6804 = 6804; public static final int KRUK_6805 = 6805; public static final int ASSISTANT_LE_SMITH_6806 = 6806; public static final int MONKEY_GUARD_6811 = 6811; public static final int AWOWOGEI_6812 = 6812; public static final int MONKEY_ARCHER_6813 = 6813; public static final int LAMMY_LANGLE = 6814; public static final int MAN_6815 = 6815; public static final int GEE = 6816; public static final int GREAT_BLUE_HERON = 6817; public static final int MAN_6818 = 6818; public static final int TOWN_CRIER_6823 = 6823; public static final int GIANT_BAT_6824 = 6824; public static final int ROD_FISHING_SPOT_6825 = 6825; public static final int WOUNDED_SOLDIER = 6826; public static final int WOUNDED_SOLDIER_6827 = 6827; public static final int WOUNDED_SOLDIER_6828 = 6828; public static final int WOUNDED_SOLDIER_6829 = 6829; public static final int WOUNDED_SOLDIER_6830 = 6830; public static final int WOUNDED_SOLDIER_6831 = 6831; public static final int WOUNDED_SOLDIER_6832 = 6832; public static final int WOUNDED_SOLDIER_6833 = 6833; public static final int WOUNDED_SOLDIER_6834 = 6834; public static final int WOUNDED_SOLDIER_6835 = 6835; public static final int WOUNDED_SOLDIER_6836 = 6836; public static final int WOUNDED_SOLDIER_6837 = 6837; public static final int WOUNDED_SOLDIER_6838 = 6838; public static final int WOUNDED_SOLDIER_6839 = 6839; public static final int WOUNDED_SOLDIER_6840 = 6840; public static final int WOUNDED_SOLDIER_6841 = 6841; public static final int WOUNDED_SOLDIER_6842 = 6842; public static final int WOUNDED_SOLDIER_6843 = 6843; public static final int WOUNDED_SOLDIER_6844 = 6844; public static final int WOUNDED_SOLDIER_6845 = 6845; public static final int WOUNDED_SOLDIER_6846 = 6846; public static final int WOUNDED_SOLDIER_6847 = 6847; public static final int WOUNDED_SOLDIER_6848 = 6848; public static final int WOUNDED_SOLDIER_6849 = 6849; public static final int WOUNDED_SOLDIER_6850 = 6850; public static final int WOUNDED_SOLDIER_6851 = 6851; public static final int WOUNDED_SOLDIER_6852 = 6852; public static final int WOUNDED_SOLDIER_6853 = 6853; public static final int WOUNDED_SOLDIER_6854 = 6854; public static final int WOUNDED_SOLDIER_6855 = 6855; public static final int WOUNDED_SOLDIER_6856 = 6856; public static final int WOUNDED_SOLDIER_6857 = 6857; public static final int LOOKOUT = 6858; public static final int BANKER_6859 = 6859; public static final int BANKER_6860 = 6860; public static final int BANKER_6861 = 6861; public static final int BANKER_6862 = 6862; public static final int BANKER_6863 = 6863; public static final int BANKER_6864 = 6864; public static final int GENERAL_SALARA = 6865; public static final int GENERAL_BABACUS = 6866; public static final int GENERAL_KILIAN = 6867; public static final int SOLDIER_6868 = 6868; public static final int SOLDIER_6869 = 6869; public static final int SOLDIER_6870 = 6870; public static final int SOLDIER_6871 = 6871; public static final int NEW_RECRUIT_TONY = 6872; public static final int NURSE_WOONED = 6873; public static final int NURSE_INNJUREE = 6874; public static final int NURSE_BOUBOU = 6875; public static final int CAPTAIN_RACHELLE = 6876; public static final int SOLDIER_6877 = 6877; public static final int SOLDIER_6878 = 6878; public static final int SOLDIER_6879 = 6879; public static final int SOLDIER_6880 = 6880; public static final int RANGER_6881 = 6881; public static final int DRILL_SERGEANT = 6882; public static final int SOLDIER_6883 = 6883; public static final int SOLDIER_6884 = 6884; public static final int SOLDIER_6885 = 6885; public static final int SOLDIER_6886 = 6886; public static final int SOLDIER_6887 = 6887; public static final int SOLDIER_6888 = 6888; public static final int SOLDIER_6889 = 6889; public static final int SOLDIER_6890 = 6890; public static final int SOLDIER_6891 = 6891; public static final int SOLDIER_6892 = 6892; public static final int SOLDIER_6893 = 6893; public static final int SOLDIER_6894 = 6894; public static final int CAPTAIN_GINEA = 6895; public static final int GANGSTER = 6896; public static final int GANGSTER_6897 = 6897; public static final int GANGSTER_6898 = 6898; public static final int GANGSTER_6899 = 6899; public static final int GANG_BOSS = 6900; public static final int GANG_BOSS_6901 = 6901; public static final int GANG_BOSS_6902 = 6902; public static final int GANG_BOSS_6903 = 6903; public static final int SOLDIER_TIER_1 = 6904; public static final int SOLDIER_TIER_1_6905 = 6905; public static final int SOLDIER_TIER_2 = 6906; public static final int SOLDIER_TIER_2_6907 = 6907; public static final int SOLDIER_TIER_3 = 6908; public static final int SOLDIER_TIER_3_6909 = 6909; public static final int SOLDIER_TIER_4 = 6910; public static final int SOLDIER_TIER_4_6911 = 6911; public static final int SOLDIER_TIER_5 = 6912; public static final int SOLDIER_TIER_5_6913 = 6913; public static final int LIZARDMAN = 6914; public static final int LIZARDMAN_6915 = 6915; public static final int LIZARDMAN_6916 = 6916; public static final int LIZARDMAN_6917 = 6917; public static final int LIZARDMAN_BRUTE = 6918; public static final int LIZARDMAN_BRUTE_6919 = 6919; public static final int FARMER_GRICOLLER = 6920; public static final int MARISI = 6921; public static final int KONOO = 6922; public static final int CLERK_6923 = 6923; public static final int PLOUGH = 6924; public static final int PLOUGH_6925 = 6925; public static final int EWESEY = 6926; public static final int SERVERY_ASSISTANT = 6927; public static final int SERVERY_ASSISTANT_6928 = 6928; public static final int SOLDIER_6929 = 6929; public static final int SOLDIER_6930 = 6930; public static final int SOLDIER_6931 = 6931; public static final int SOLDIER_6932 = 6932; public static final int SOLDIER_6933 = 6933; public static final int SOLDIER_6934 = 6934; public static final int SOLDIER_6935 = 6935; public static final int SOLDIER_6936 = 6936; public static final int RAMOCEAN = 6937; public static final int TALIA = 6938; public static final int BANKER_6939 = 6939; public static final int BANKER_6940 = 6940; public static final int BANKER_6941 = 6941; public static final int BANKER_6942 = 6942; public static final int HORACE = 6943; public static final int VANNAH = 6944; public static final int LOGAVA = 6945; public static final int FARMER_6947 = 6947; public static final int FARMER_6948 = 6948; public static final int FARMER_6949 = 6949; public static final int FARMER_6950 = 6950; public static final int FARMER_6951 = 6951; public static final int FARMER_6952 = 6952; public static final int GOLOVA = 6953; public static final int RICHARD_6954 = 6954; public static final int FATHER_JEAN = 6955; public static final int MONK_6956 = 6956; public static final int CHIEF_FARMER = 6957; public static final int FARMERS_WIFE = 6958; public static final int FARMER_6959 = 6959; public static final int FARMER_6960 = 6960; public static final int FARMER_6961 = 6961; public static final int FARMER_HAYFIELD = 6962; public static final int FRANKIE = 6963; public static final int TYNAN = 6964; public static final int NICHOLAS = 6965; public static final int DOCKMASTER = 6966; public static final int DOCK_WORKER = 6967; public static final int DOCK_WORKER_6968 = 6968; public static final int BANKER_6969 = 6969; public static final int BANKER_6970 = 6970; public static final int CAPTAIN_KHALED = 6971; public static final int CAPTAIN_KHALED_6972 = 6972; public static final int PATROLMAN = 6973; public static final int PATROLMAN_6974 = 6974; public static final int PATROLMAN_6975 = 6975; public static final int PATROLWOMAN = 6976; public static final int PATROLMAN_6977 = 6977; public static final int PATROLWOMAN_6978 = 6978; public static final int PATROLMAN_6979 = 6979; public static final int PATROLMAN_6980 = 6980; public static final int FISHERMAN_6981 = 6981; public static final int POOR_LOOKING_MAN = 6982; public static final int POOR_LOOKING_MAN_6983 = 6983; public static final int POOR_LOOKING_WOMAN = 6984; public static final int POOR_LOOKING_WOMAN_6985 = 6985; public static final int LEENZ = 6986; public static final int MAN_6987 = 6987; public static final int MAN_6988 = 6988; public static final int MAN_6989 = 6989; public static final int WOMAN_6990 = 6990; public static final int WOMAN_6991 = 6991; public static final int WOMAN_6992 = 6992; public static final int PIRATE_6993 = 6993; public static final int PIRATE_6994 = 6994; public static final int PIRATE_6995 = 6995; public static final int MUGGER_6996 = 6996; public static final int DARK_WIZARD_6997 = 6997; public static final int PIRATE_6998 = 6998; public static final int PORT_OFFICIAL = 6999; public static final int CAPTAIN_JANAWAY = 7000; public static final int PORT_WORKER = 7001; public static final int MARK_7002 = 7002; public static final int CHERYL = 7003; public static final int CHARLES = 7004; public static final int SARAH_7005 = 7005; public static final int DARREN_7006 = 7006; public static final int MELVIN = 7007; public static final int SIMON_7008 = 7008; public static final int ANDREA = 7009; public static final int ELIZABETH_7010 = 7010; public static final int LORRAINE = 7011; public static final int ROSS_AND_BEN = 7012; public static final int DOBWINKLE = 7013; public static final int ALEXANDER = 7014; public static final int CHARLIE_BROWN = 7015; public static final int REANIMATED_GOBLIN = 7018; public static final int REANIMATED_MONKEY = 7019; public static final int REANIMATED_IMP = 7020; public static final int REANIMATED_MINOTAUR = 7021; public static final int REANIMATED_SCORPION = 7022; public static final int REANIMATED_BEAR = 7023; public static final int REANIMATED_UNICORN = 7024; public static final int REANIMATED_DOG = 7025; public static final int REANIMATED_CHAOS_DRUID = 7026; public static final int REANIMATED_GIANT = 7027; public static final int REANIMATED_OGRE = 7028; public static final int REANIMATED_ELF = 7029; public static final int REANIMATED_TROLL = 7030; public static final int REANIMATED_HORROR = 7031; public static final int REANIMATED_KALPHITE = 7032; public static final int REANIMATED_DAGANNOTH = 7033; public static final int REANIMATED_BLOODVELD = 7034; public static final int REANIMATED_TZHAAR = 7035; public static final int REANIMATED_DEMON = 7036; public static final int REANIMATED_AVIANSIE = 7037; public static final int REANIMATED_ABYSSAL = 7038; public static final int REANIMATED_DRAGON = 7039; public static final int CLERRIS = 7040; public static final int ENOCH = 7041; public static final int ARETHA = 7042; public static final int SISTER_SOUL_JAR = 7043; public static final int LOGOSIA = 7044; public static final int BIBLIA = 7045; public static final int HORPHIS = 7046; public static final int VILLIA = 7047; public static final int PROFESSOR_GRACKLEBONE = 7048; public static final int SAM_7049 = 7049; public static final int TYSS = 7050; public static final int TROSSA = 7051; public static final int TOWER_MAGE = 7052; public static final int RASSAIN = 7053; public static final int MOFINA = 7054; public static final int NOVICE = 7055; public static final int REGATH = 7056; public static final int BANKER_7057 = 7057; public static final int BANKER_7058 = 7058; public static final int BANKER_7059 = 7059; public static final int BANKER_7060 = 7060; public static final int BATT_MELLAMY = 7061; public static final int FREALD = 7062; public static final int COB = 7063; public static final int DARK_WIZARD_7064 = 7064; public static final int DARK_WIZARD_7065 = 7065; public static final int WIZARD_7066 = 7066; public static final int WIZARD_7067 = 7067; public static final int OUDITOR = 7068; public static final int SMOGGY = 7069; public static final int TOOTHY = 7071; public static final int OPERATOR = 7072; public static final int OPERATOR_7073 = 7073; public static final int BLASTED_ORE = 7074; public static final int MINE_SUPERVISOR = 7075; public static final int MINE_SUPERVISOR_7076 = 7076; public static final int BANKER_7077 = 7077; public static final int BANKER_7078 = 7078; public static final int BANKER_7079 = 7079; public static final int BANKER_7080 = 7080; public static final int BANKER_7081 = 7081; public static final int BANKER_7082 = 7082; public static final int ARMOURER_TIER_1 = 7083; public static final int ARMOURER_TIER_2 = 7084; public static final int ARMOURER_TIER_3 = 7085; public static final int ARMOURER_TIER_4 = 7086; public static final int ARMOURER_TIER_5 = 7087; public static final int MUNTY = 7088; public static final int MOGGY = 7089; public static final int FUGGY = 7090; public static final int MINER_7091 = 7091; public static final int MINER_7092 = 7092; public static final int MINER_7093 = 7093; public static final int MINER_7094 = 7094; public static final int TORTURED_GORILLA = 7095; public static final int TORTURED_GORILLA_7096 = 7096; public static final int TORTURED_GORILLA_7097 = 7097; public static final int STUNTED_DEMONIC_GORILLA = 7098; public static final int KRUK_7099 = 7099; public static final int GLOUGH_7100 = 7100; public static final int GLOUGH_7101 = 7101; public static final int GLOUGH_7102 = 7102; public static final int GLOUGH_7103 = 7103; public static final int KEEF = 7104; public static final int KEEF_7105 = 7105; public static final int KOB = 7106; public static final int KOB_7107 = 7107; public static final int NIEVE_7108 = 7108; public static final int NIEVE_7109 = 7109; public static final int NIEVE_7110 = 7110; public static final int GARKOR_7111 = 7111; public static final int LUMO_7112 = 7112; public static final int ZOOKNOCK_7113 = 7113; public static final int CARADO_7114 = 7114; public static final int GLOUGH_7115 = 7115; public static final int LOOMING_SHADOW = 7116; public static final int KINEER = 7117; public static final int MANIACAL_MONKEY_7118 = 7118; public static final int MANIACAL_MONKEY_ARCHER = 7119; public static final int OOBAPOHK = 7120; public static final int JUMAANE = 7121; public static final int MONKEY_GUARD_7122 = 7122; public static final int MONKEY_GUARD_7123 = 7123; public static final int MONKEY_GUARD_7124 = 7124; public static final int MONKEY_GUARD_7125 = 7125; public static final int MONKEY_GUARD_7126 = 7126; public static final int MONKEY_GUARD_7127 = 7127; public static final int MONKEY_GUARD_7128 = 7128; public static final int MONKEY_GUARD_7129 = 7129; public static final int MONKEY_GUARD_7130 = 7130; public static final int MONKEY_GUARD_7131 = 7131; public static final int MONKEY_GUARD_7132 = 7132; public static final int MONKEY_GUARD_7133 = 7133; public static final int MONKEY_GUARD_7134 = 7134; public static final int MONKEY_GUARD_7135 = 7135; public static final int MONKEY_GUARD_7136 = 7136; public static final int MONKEY_GUARD_7137 = 7137; public static final int MONKEY_GUARD_7138 = 7138; public static final int MONKEY_GUARD_7139 = 7139; public static final int MONKEY_GUARD_7140 = 7140; public static final int MONKEY_GUARD_7141 = 7141; public static final int MONKEY_GUARD_7142 = 7142; public static final int MONKEY_GUARD_7143 = 7143; public static final int DEMONIC_GORILLA = 7144; public static final int DEMONIC_GORILLA_7145 = 7145; public static final int DEMONIC_GORILLA_7146 = 7146; public static final int DEMONIC_GORILLA_7147 = 7147; public static final int DEMONIC_GORILLA_7148 = 7148; public static final int DEMONIC_GORILLA_7149 = 7149; public static final int TORTURED_GORILLA_7150 = 7150; public static final int TORTURED_GORILLA_7151 = 7151; public static final int DEMONIC_GORILLA_7152 = 7152; public static final int TORTURED_GORILLA_7153 = 7153; public static final int ASSISTANT_LORI = 7154; public static final int FISHING_SPOT_7155 = 7155; public static final int ANITA = 7156; public static final int ANITA_7157 = 7157; public static final int GARKOR_7158 = 7158; public static final int GARKOR_7159 = 7159; public static final int LUMO_7160 = 7160; public static final int LUMO_7161 = 7161; public static final int BUNKDO_7162 = 7162; public static final int BUNKDO_7163 = 7163; public static final int CARADO_7164 = 7164; public static final int CARADO_7165 = 7165; public static final int BUNKWICKET_7166 = 7166; public static final int BUNKWICKET_7167 = 7167; public static final int WAYMOTTIN_7168 = 7168; public static final int WAYMOTTIN_7169 = 7169; public static final int ZOOKNOCK_7170 = 7170; public static final int ZOOKNOCK_7171 = 7171; public static final int KARAM_7172 = 7172; public static final int KARAM_7173 = 7173; public static final int KARAM_7174 = 7174; public static final int DUKE_7176 = 7176; public static final int CAPTAIN_SHORACKS = 7178; public static final int FISHING_SPOT_7199 = 7199; public static final int FISHING_SPOT_7200 = 7200; public static final int BRIGET = 7201; public static final int KENELME = 7202; public static final int THYRIA = 7203; public static final int FILAMINA = 7204; public static final int JARVALD_7205 = 7205; public static final int SAND_CRAB_7206 = 7206; public static final int SANDY_ROCKS_7207 = 7207; public static final int GUARD_DOG_7209 = 7209; public static final int MANIACAL_MONKEY_7212 = 7212; public static final int MANIACAL_MONKEY_7213 = 7213; public static final int MANIACAL_MONKEY_7214 = 7214; public static final int MANIACAL_MONKEY_7215 = 7215; public static final int MANIACAL_MONKEY_7216 = 7216; public static final int MIRIAM = 7217; public static final int MIRIAM_7218 = 7218; public static final int TRAXI = 7219; public static final int TRAXI_7220 = 7220; public static final int RAELI = 7221; public static final int RAELI_7222 = 7222; public static final int MOGRIM = 7223; public static final int MOGRIM_7224 = 7224; public static final int LOINUR = 7225; public static final int LOINUR_7226 = 7226; public static final int BLOODHOUND_7232 = 7232; public static final int LUCKY_IMPLING = 7233; public static final int ENT_7234 = 7234; public static final int BERRY_7235 = 7235; public static final int GUILDMASTER_LARS = 7236; public static final int MURFET = 7237; public static final int FORESTER_7238 = 7238; public static final int KAI = 7239; public static final int PERRY = 7240; public static final int ABYSSAL_DEMON_7241 = 7241; public static final int BLACK_DEMON_7242 = 7242; public static final int BLACK_DEMON_7243 = 7243; public static final int GREATER_DEMON_7244 = 7244; public static final int GREATER_DEMON_7245 = 7245; public static final int GREATER_DEMON_7246 = 7246; public static final int LESSER_DEMON_7247 = 7247; public static final int LESSER_DEMON_7248 = 7248; public static final int DUST_DEVIL_7249 = 7249; public static final int DARK_BEAST_7250 = 7250; public static final int FIRE_GIANT_7251 = 7251; public static final int FIRE_GIANT_7252 = 7252; public static final int BRONZE_DRAGON_7253 = 7253; public static final int IRON_DRAGON_7254 = 7254; public static final int STEEL_DRAGON_7255 = 7255; public static final int HELLHOUND_7256 = 7256; public static final int ANKOU_7257 = 7257; public static final int SHADE_7258 = 7258; public static final int DAGANNOTH_7259 = 7259; public static final int DAGANNOTH_7260 = 7260; public static final int HILL_GIANT_7261 = 7261; public static final int MOSS_GIANT_7262 = 7262; public static final int GHOST_7263 = 7263; public static final int GHOST_7264 = 7264; public static final int SKELETON_7265 = 7265; public static final int KING_SAND_CRAB = 7266; public static final int SANDY_BOULDER = 7267; public static final int POSSESSED_PICKAXE_7268 = 7268; public static final int MAGIC_AXE_7269 = 7269; public static final int CYCLOPS_7270 = 7270; public static final int CYCLOPS_7271 = 7271; public static final int TWISTED_BANSHEE = 7272; public static final int BRUTAL_BLUE_DRAGON = 7273; public static final int BRUTAL_RED_DRAGON = 7274; public static final int BRUTAL_BLACK_DRAGON = 7275; public static final int MUTATED_BLOODVELD = 7276; public static final int WARPED_JELLY = 7277; public static final int GREATER_NECHRYAEL = 7278; public static final int DEVIANT_SPECTRE = 7279; public static final int KINEER_7280 = 7280; public static final int MAN_7281 = 7281; public static final int PIRATE_7282 = 7282; public static final int LILLIA = 7283; public static final int GERTRUDE = 7284; public static final int BARBARIAN_GUARD_7285 = 7285; public static final int SKOTIZO = 7286; public static final int REANIMATED_DEMON_SPAWN = 7287; public static final int AWAKENED_ALTAR = 7288; public static final int ALTAR = 7289; public static final int AWAKENED_ALTAR_7290 = 7290; public static final int ALTAR_7291 = 7291; public static final int AWAKENED_ALTAR_7292 = 7292; public static final int ALTAR_7293 = 7293; public static final int AWAKENED_ALTAR_7294 = 7294; public static final int ALTAR_7295 = 7295; public static final int DARK_ANKOU = 7296; public static final int MISTAG_7297 = 7297; public static final int MISTAG_7298 = 7298; public static final int MISTAG_7299 = 7299; public static final int KAZGAR = 7300; public static final int KAZGAR_7301 = 7301; public static final int LUCKY_IMPLING_7302 = 7302; public static final int WATSON = 7303; public static final int WATSON_7304 = 7304; public static final int GRUFF_MCSCRUFF = 7305; public static final int FALO_THE_BARD = 7306; public static final int ANCIENT_WIZARD = 7307; public static final int ANCIENT_WIZARD_7308 = 7308; public static final int ANCIENT_WIZARD_7309 = 7309; public static final int BRASSICAN_MAGE = 7310; public static final int URI_7311 = 7311; public static final int DOUBLE_AGENT_7312 = 7312; public static final int LISA = 7316; public static final int LISA_7317 = 7317; public static final int NESTY = 7321; public static final int FISHING_SPOT_7323 = 7323; public static final int HOLGART_7324 = 7324; public static final int RICK_7327 = 7327; public static final int MAID_7328 = 7328; public static final int COOK_7329 = 7329; public static final int BUTLER_7330 = 7330; public static final int DEMON_BUTLER_7331 = 7331; public static final int FAIRY_FIXIT = 7332; public static final int FAIRY_FIXIT_7333 = 7333; public static final int GIANT_SQUIRREL = 7334; public static final int TANGLEROOT = 7335; public static final int ROCKY = 7336; public static final int RIFT_GUARDIAN = 7337; public static final int RIFT_GUARDIAN_7338 = 7338; public static final int RIFT_GUARDIAN_7339 = 7339; public static final int RIFT_GUARDIAN_7340 = 7340; public static final int RIFT_GUARDIAN_7341 = 7341; public static final int RIFT_GUARDIAN_7342 = 7342; public static final int RIFT_GUARDIAN_7343 = 7343; public static final int RIFT_GUARDIAN_7344 = 7344; public static final int RIFT_GUARDIAN_7345 = 7345; public static final int RIFT_GUARDIAN_7346 = 7346; public static final int RIFT_GUARDIAN_7347 = 7347; public static final int RIFT_GUARDIAN_7348 = 7348; public static final int RIFT_GUARDIAN_7349 = 7349; public static final int RIFT_GUARDIAN_7350 = 7350; public static final int GIANT_SQUIRREL_7351 = 7351; public static final int TANGLEROOT_7352 = 7352; public static final int ROCKY_7353 = 7353; public static final int RIFT_GUARDIAN_7354 = 7354; public static final int RIFT_GUARDIAN_7355 = 7355; public static final int RIFT_GUARDIAN_7356 = 7356; public static final int RIFT_GUARDIAN_7357 = 7357; public static final int RIFT_GUARDIAN_7358 = 7358; public static final int RIFT_GUARDIAN_7359 = 7359; public static final int RIFT_GUARDIAN_7360 = 7360; public static final int RIFT_GUARDIAN_7361 = 7361; public static final int RIFT_GUARDIAN_7362 = 7362; public static final int RIFT_GUARDIAN_7363 = 7363; public static final int RIFT_GUARDIAN_7364 = 7364; public static final int RIFT_GUARDIAN_7365 = 7365; public static final int RIFT_GUARDIAN_7366 = 7366; public static final int RIFT_GUARDIAN_7367 = 7367; public static final int PHOENIX_7368 = 7368; public static final int WESLEY = 7369; public static final int PHOENIX_7370 = 7370; public static final int PYROMANCER = 7371; public static final int INCAPACITATED_PYROMANCER = 7372; public static final int IGNISIA = 7374; public static final int ESTHER = 7376; public static final int CAPTAIN_KALT = 7377; public static final int ISH_THE_NAVIGATOR = 7378; public static final int WINTER_SOLDIER = 7379; public static final int CAT_7380 = 7380; public static final int WINTERTOAD = 7381; public static final int SNOW = 7383; public static final int STUMPY = 7384; public static final int PUMPY = 7385; public static final int DUMPY = 7386; public static final int DUMPY_7387 = 7387; public static final int CRUSHING_HAND = 7388; public static final int CHASM_CRAWLER = 7389; public static final int SCREAMING_BANSHEE = 7390; public static final int SCREAMING_TWISTED_BANSHEE = 7391; public static final int GIANT_ROCKSLUG = 7392; public static final int COCKATHRICE = 7393; public static final int FLAMING_PYRELORD = 7394; public static final int MONSTROUS_BASILISK = 7395; public static final int MALEVOLENT_MAGE = 7396; public static final int INSATIABLE_BLOODVELD = 7397; public static final int INSATIABLE_MUTATED_BLOODVELD = 7398; public static final int VITREOUS_JELLY = 7399; public static final int VITREOUS_WARPED_JELLY = 7400; public static final int CAVE_ABOMINATION = 7401; public static final int ABHORRENT_SPECTRE = 7402; public static final int REPUGNANT_SPECTRE = 7403; public static final int CHOKE_DEVIL = 7404; public static final int KING_KURASK = 7405; public static final int NUCLEAR_SMOKE_DEVIL = 7406; public static final int MARBLE_GARGOYLE = 7407; public static final int MARBLE_GARGOYLE_7408 = 7408; public static final int NIGHT_BEAST = 7409; public static final int GREATER_ABYSSAL_DEMON = 7410; public static final int NECHRYARCH = 7411; public static final int LIEVE_MCCRACKEN = 7412; public static final int UNDEAD_COMBAT_DUMMY = 7413; public static final int COUNT_CHECK = 7414; public static final int BOLOGA = 7415; public static final int OBOR = 7416; public static final int AMY_7417 = 7417; public static final int ZAMORAK_WARRIOR = 7418; public static final int ZAMORAK_WARRIOR_7419 = 7419; public static final int ZAMORAK_RANGER = 7420; public static final int ZAMORAK_RANGER_7421 = 7421; public static final int ZAMORAK_MAGE = 7422; public static final int ZAMORAK_MAGE_7423 = 7423; public static final int CAVE_LIZARD = 7424; public static final int MAGE_OF_ZAMORAK_7425 = 7425; public static final int ZAMORAK_CRAFTER = 7426; public static final int ZAMORAK_CRAFTER_7427 = 7427; public static final int GUARD_7437 = 7437; public static final int GUARD_7438 = 7438; public static final int ROCK_GOLEM_7439 = 7439; public static final int ROCK_GOLEM_7440 = 7440; public static final int ROCK_GOLEM_7441 = 7441; public static final int ROCK_GOLEM_7442 = 7442; public static final int ROCK_GOLEM_7443 = 7443; public static final int ROCK_GOLEM_7444 = 7444; public static final int ROCK_GOLEM_7445 = 7445; public static final int ROCK_GOLEM_7446 = 7446; public static final int ROCK_GOLEM_7447 = 7447; public static final int ROCK_GOLEM_7448 = 7448; public static final int ROCK_GOLEM_7449 = 7449; public static final int ROCK_GOLEM_7450 = 7450; public static final int ROCK_GOLEM_7451 = 7451; public static final int ROCK_GOLEM_7452 = 7452; public static final int ROCK_GOLEM_7453 = 7453; public static final int ROCK_GOLEM_7454 = 7454; public static final int ROCK_GOLEM_7455 = 7455; public static final int PERDU = 7456; public static final int FISHING_SPOT_7459 = 7459; public static final int FISHING_SPOT_7460 = 7460; public static final int FISHING_SPOT_7461 = 7461; public static final int FISHING_SPOT_7462 = 7462; public static final int ROD_FISHING_SPOT_7463 = 7463; public static final int ROD_FISHING_SPOT_7464 = 7464; public static final int FISHING_SPOT_7465 = 7465; public static final int FISHING_SPOT_7466 = 7466; public static final int FISHING_SPOT_7467 = 7467; public static final int ROD_FISHING_SPOT_7468 = 7468; public static final int FISHING_SPOT_7469 = 7469; public static final int FISHING_SPOT_7470 = 7470; public static final int CAPTAIN_MAGORO = 7471; public static final int RANGER_7472 = 7472; public static final int DUCK_7473 = 7473; public static final int REGINALD = 7474; public static final int ROY_JR = 7475; public static final int ROBERT_BOSS = 7476; public static final int KNIGHT_OF_VARLAMORE = 7477; public static final int HUGOR = 7478; public static final int LAN_THE_BUTCHER = 7479; public static final int RAKKAR = 7480; public static final int HOPLEEZ = 7481; public static final int CAPTAIN_SDIAR = 7482; public static final int SANDICRAHB = 7483; public static final int SANDICRAHB_7484 = 7484; public static final int ZOMBIE_7485 = 7485; public static final int ZOMBIE_7486 = 7486; public static final int ZOMBIE_7487 = 7487; public static final int ZOMBIE_7488 = 7488; public static final int JARDRIC = 7509; public static final int ANNETTE = 7510; public static final int SHIELD_MASTER = 7511; public static final int PIZAZZ_HAT = 7512; public static final int DERWEN = 7513; public static final int ENERGY_BALL = 7514; public static final int PORAZDIR = 7515; public static final int GNORMADIUM_AVLAFRIM = 7516; public static final int GNORMADIUM_AVLAFRIM_7517 = 7517; public static final int JELLY_7518 = 7518; public static final int OLMLET = 7519; public static final int OLMLET_7520 = 7520; public static final int SOLDIER_7521 = 7521; public static final int SOLDIER_7522 = 7522; public static final int SOLDIER_7523 = 7523; public static final int SOLDIER_7524 = 7524; public static final int VANGUARD = 7525; public static final int VANGUARD_7526 = 7526; public static final int VANGUARD_7527 = 7527; public static final int VANGUARD_7528 = 7528; public static final int VANGUARD_7529 = 7529; public static final int VESPULA = 7530; public static final int VESPULA_7531 = 7531; public static final int VESPULA_7532 = 7532; public static final int ABYSSAL_PORTAL = 7533; public static final int LUX_GRUB = 7534; public static final int LUX_GRUB_7535 = 7535; public static final int LUX_GRUB_7536 = 7536; public static final int LUX_GRUB_7537 = 7537; public static final int VESPINE_SOLDIER = 7538; public static final int VESPINE_SOLDIER_7539 = 7539; public static final int TEKTON = 7540; public static final int TEKTON_7541 = 7541; public static final int TEKTON_7542 = 7542; public static final int TEKTON_ENRAGED = 7543; public static final int TEKTON_ENRAGED_7544 = 7544; public static final int TEKTON_7545 = 7545; public static final int BARTENDER_7546 = 7546; public static final int SCAVENGER_BEAST = 7548; public static final int SCAVENGER_BEAST_7549 = 7549; public static final int GREAT_OLM_RIGHT_CLAW = 7550; public static final int GREAT_OLM = 7551; public static final int GREAT_OLM_LEFT_CLAW = 7552; public static final int GREAT_OLM_RIGHT_CLAW_7553 = 7553; public static final int GREAT_OLM_7554 = 7554; public static final int GREAT_OLM_LEFT_CLAW_7555 = 7555; public static final int FIRE = 7558; public static final int DEATHLY_RANGER = 7559; public static final int DEATHLY_MAGE = 7560; public static final int MUTTADILE = 7561; public static final int MUTTADILE_7562 = 7562; public static final int MUTTADILE_7563 = 7563; public static final int MEAT_TREE = 7564; public static final int ROCKS_7565 = 7565; public static final int VASA_NISTIRIO = 7566; public static final int VASA_NISTIRIO_7567 = 7567; public static final int GLOWING_CRYSTAL = 7568; public static final int GUARDIAN = 7569; public static final int GUARDIAN_7570 = 7570; public static final int GUARDIAN_7571 = 7571; public static final int GUARDIAN_7572 = 7572; public static final int LIZARDMAN_SHAMAN_7573 = 7573; public static final int LIZARDMAN_SHAMAN_7574 = 7574; public static final int SPAWN_7575 = 7575; public static final int JEWELLED_CRAB = 7576; public static final int JEWELLED_CRAB_RED = 7577; public static final int JEWELLED_CRAB_GREEN = 7578; public static final int JEWELLED_CRAB_BLUE = 7579; public static final int ENERGY_FOCUS_WHITE = 7580; public static final int ENERGY_FOCUS_RED = 7581; public static final int ENERGY_FOCUS_GREEN = 7582; public static final int ENERGY_FOCUS_BLUE = 7583; public static final int ICE_DEMON = 7584; public static final int ICE_DEMON_7585 = 7585; public static final int ICEFIEND_7586 = 7586; public static final int GUANIC_BAT = 7587; public static final int PRAEL_BAT = 7588; public static final int GIRAL_BAT = 7589; public static final int PHLUXIA_BAT = 7590; public static final int KRYKET_BAT = 7591; public static final int MURNG_BAT = 7592; public static final int PSYKK_BAT = 7593; public static final int CAVE_SNAKE = 7594; public static final int CAPTAIN_RIMOR = 7595; public static final int LIZARD_7597 = 7597; public static final int STRANGE_DEVICE = 7598; public static final int MOUNTAIN_GUIDE = 7599; public static final int MOUNTAIN_GUIDE_7600 = 7600; public static final int SWAMP_PRIEST = 7601; public static final int CORRUPTED_SCAVENGER = 7602; public static final int CORRUPTED_SCAVENGER_7603 = 7603; public static final int SKELETAL_MYSTIC = 7604; public static final int SKELETAL_MYSTIC_7605 = 7605; public static final int SKELETAL_MYSTIC_7606 = 7606; public static final int IMEROMINIA = 7607; public static final int PAGIDA = 7608; public static final int LOGIOS = 7610; public static final int MELETI = 7611; public static final int KRATO = 7612; public static final int EKTHEME = 7613; public static final int ARCHEIO = 7614; public static final int STULIETTE = 7615; public static final int STULIETTE_7616 = 7616; public static final int TEMPLE_GUARDIAN = 7620; public static final int KHAZARD_WARLORD_7621 = 7621; public static final int KHAZARD_WARLORD_7622 = 7622; public static final int ABIGALE = 7623; public static final int HEWEY = 7624; public static final int SID = 7625; public static final int SID_7626 = 7626; public static final int TAYTEN = 7627; public static final int LACEY = 7628; public static final int MANDY = 7629; public static final int MANDY_7630 = 7630; public static final int MANDY_7631 = 7631; public static final int KILLER = 7632; public static final int ABIGALE_7633 = 7633; public static final int ABIGALE_7635 = 7635; public static final int KILLER_7636 = 7636; public static final int HEWEY_7637 = 7637; public static final int SHADY_FIGURE = 7638; public static final int MIRROR = 7640; public static final int MIRROR_7641 = 7641; public static final int ROCK_GOLEM_7642 = 7642; public static final int ROCK_GOLEM_7643 = 7643; public static final int ROCK_GOLEM_7644 = 7644; public static final int ROCK_GOLEM_7645 = 7645; public static final int ROCK_GOLEM_7646 = 7646; public static final int ROCK_GOLEM_7647 = 7647; public static final int ROCK_GOLEM_7648 = 7648; public static final int CHAOTIC_DEATH_SPAWN_7649 = 7649; public static final int PIRATE_JACKIE_THE_FRUIT = 7650; public static final int PIRATE_JACKIE_THE_FRUIT_7651 = 7651; public static final int TZHAARMEJ_7652 = 7652; public static final int SLIEVE = 7653; public static final int BREIVE = 7654; public static final int LESSER_DEMON_7656 = 7656; public static final int LESSER_DEMON_7657 = 7657; public static final int MUMMY_7658 = 7658; public static final int MUMMY_7659 = 7659; public static final int MUMMY_7660 = 7660; public static final int MUMMY_7661 = 7661; public static final int MUMMY_7662 = 7662; public static final int KRYSTILIA = 7663; public static final int LESSER_DEMON_7664 = 7664; public static final int BANISOCH = 7665; public static final int BANISOCH_7666 = 7666; public static final int HIEVE = 7667; public static final int VOICE_OF_YAMA = 7668; public static final int DISCIPLE_OF_YAMA = 7669; public static final int DISCIPLE_OF_YAMA_7670 = 7670; public static final int SKOTOS_7671 = 7671; public static final int EVE = 7672; public static final int SOLZTUN = 7673; public static final int JALNIBREK = 7674; public static final int JALNIBREK_7675 = 7675; public static final int ROD_FISHING_SPOT_7676 = 7676; public static final int TZHAARKETZUH = 7677; public static final int TZHAARKETYIL = 7678; public static final int TZHAARKET_7679 = 7679; public static final int TZHAARMEJDIR = 7680; public static final int TZHAARMEJBAL = 7681; public static final int TZHAARHUR_7682 = 7682; public static final int TZHAARHUR_7683 = 7683; public static final int TZHAARHUR_7684 = 7684; public static final int TZHAARHUR_7685 = 7685; public static final int TZHAARHUR_7686 = 7686; public static final int TZHAARHUR_7687 = 7687; public static final int TZHAARHURZAL = 7688; public static final int TZHAARHURRIN = 7689; public static final int JALNIB = 7691; public static final int JALMEJRAH = 7692; public static final int JALAK = 7693; public static final int JALAKREKMEJ = 7694; public static final int JALAKREKXIL = 7695; public static final int JALAKREKKET = 7696; public static final int JALIMKOT = 7697; public static final int JALXIL = 7698; public static final int JALZEK = 7699; public static final int JALTOKJAD = 7700; public static final int YTHURKOT_7701 = 7701; public static final int JALXIL_7702 = 7702; public static final int JALZEK_7703 = 7703; public static final int JALTOKJAD_7704 = 7704; public static final int YTHURKOT_7705 = 7705; public static final int TZKALZUK = 7706; public static final int ANCESTRAL_GLYPH = 7707; public static final int JALMEJJAK = 7708; public static final int ROCKY_SUPPORT = 7709; public static final int ROCKY_SUPPORT_7710 = 7710; public static final int ROCK_GOLEM_7711 = 7711; public static final int DWARF_7712 = 7712; public static final int DWARF_7713 = 7713; public static final int DWARF_7714 = 7714; public static final int DWARF_7715 = 7715; public static final int GADRIN = 7716; public static final int HENDOR = 7717; public static final int YARSUL = 7718; public static final int BELONA = 7719; public static final int UTREC = 7720; public static final int DWARF_7721 = 7721; public static final int ROCKS_7722 = 7722; public static final int GERTRUDE_7723 = 7723; public static final int BARBARIAN_GUARD_7724 = 7724; public static final int DWARVEN_BOATMAN_7725 = 7725; public static final int DWARVEN_BOATMAN_7726 = 7726; public static final int KYLIE_MINNOW = 7727; public static final int KYLIE_MINNOW_7728 = 7728; public static final int FISHING_SPOT_7730 = 7730; public static final int FISHING_SPOT_7731 = 7731; public static final int FISHING_SPOT_7732 = 7732; public static final int FISHING_SPOT_7733 = 7733; public static final int RECRUITER = 7734; public static final int ROCK_GOLEM_7736 = 7736; public static final int ROCK_GOLEM_7737 = 7737; public static final int ROCK_GOLEM_7738 = 7738; public static final int ROCK_GOLEM_7739 = 7739; public static final int ROCK_GOLEM_7740 = 7740; public static final int ROCK_GOLEM_7741 = 7741; public static final int CAPTAIN_CLEIVE = 7742; public static final int SOLDIER_7743 = 7743; public static final int LIZARDMAN_SHAMAN_7744 = 7744; public static final int LIZARDMAN_SHAMAN_7745 = 7745; public static final int WIZARD_MIZGOG = 7746; public static final int WIZARD_MIZGOG_7747 = 7747; public static final int FAIRY_7748 = 7748; public static final int ARMOURED_FOE = 7750; public static final int WELLARMED_FOE = 7751; public static final int DARK_MAGE_7752 = 7752; public static final int DARK_MAGE_7753 = 7753; public static final int SQUIRREL_7754 = 7754; public static final int SQUIRREL_7755 = 7755; public static final int SQUIRREL_7756 = 7756; public static final int TOOL_LEPRECHAUN_7757 = 7757; public static final int MERNIA = 7758; public static final int HERBI = 7759; public static final int HERBI_7760 = 7760; public static final int LEAD_NAVIGATOR = 7761; public static final int LEAD_NAVIGATOR_7762 = 7762; public static final int JUNIOR_NAVIGATOR = 7763; public static final int JUNIOR_NAVIGATOR_7764 = 7764; public static final int JOHN_7765 = 7765; public static final int DAVID_7766 = 7766; public static final int BARGE_GUARD = 7768; public static final int SHOP_KEEPER_7769 = 7769; public static final int FOSSIL_COLLECTOR = 7770; public static final int DOG_7771 = 7771; public static final int PETER = 7772; public static final int CHARLES_7773 = 7773; public static final int JOHN_7774 = 7774; public static final int DUNCE_7775 = 7775; public static final int PETRIFIED_PETE = 7776; public static final int WEVE = 7777; public static final int IRENE = 7778; public static final int BOBBING_FOSSIL = 7779; public static final int ISLWYN = 7780; public static final int PUFFER_FISH = 7781; public static final int FISH_SHOAL = 7782; public static final int CETO = 7783; public static final int MAIRIN = 7784; public static final int HERBIBOAR = 7785; public static final int HERBIBOAR_7786 = 7786; public static final int MATTIMEO = 7787; public static final int CHARLES_CHARLINGTON = 7788; public static final int HOLGART_7789 = 7789; public static final int JOHN_7790 = 7790; public static final int DAVID_7791 = 7791; public static final int LONGTAILED_WYVERN = 7792; public static final int TALONED_WYVERN = 7793; public static final int SPITTING_WYVERN = 7794; public static final int ANCIENT_WYVERN = 7795; public static final int LOBSTROSITY = 7796; public static final int ANCIENT_ZYGOMITE = 7797; public static final int GAIUS = 7798; public static final int AMMONITE_CRAB = 7799; public static final int FOSSIL_ROCK = 7800; public static final int TAR_BUBBLES = 7801; public static final int HOOP_SNAKE = 7802; public static final int STUNNED_HOOP_SNAKE = 7803; public static final int TAR_MONSTER = 7804; public static final int PASSIVE_TAR_MONSTER = 7805; public static final int DERANGED_ARCHAEOLOGIST = 7806; public static final int GIANT_BOULDER = 7807; public static final int GIANT_BOULDER_7808 = 7808; public static final int GIANT_BOULDER_7809 = 7809; public static final int LARGE_BOULDER = 7810; public static final int LARGE_BOULDER_7811 = 7811; public static final int MEDIUM_BOULDER = 7812; public static final int MEDIUM_BOULDER_7813 = 7813; public static final int SMALL_BOULDER = 7814; public static final int SMALL_BOULDER_7815 = 7815; public static final int SMALL_BOULDER_7816 = 7816; public static final int LAVA_BEAST = 7817; public static final int DAVID_7818 = 7818; public static final int DUSK = 7849; public static final int DAWN = 7850; public static final int DUSK_7851 = 7851; public static final int DAWN_7852 = 7852; public static final int DAWN_7853 = 7853; public static final int DUSK_7854 = 7854; public static final int DUSK_7855 = 7855; public static final int JUSTICIAR_ZACHARIAH_7858 = 7858; public static final int DERWEN_7859 = 7859; public static final int PORAZDIR_7860 = 7860; public static final int BLACK_DRAGON_7861 = 7861; public static final int BLACK_DRAGON_7862 = 7862; public static final int BLACK_DRAGON_7863 = 7863; public static final int ANKOU_7864 = 7864; public static final int LESSER_DEMON_7865 = 7865; public static final int LESSER_DEMON_7866 = 7866; public static final int LESSER_DEMON_7867 = 7867; public static final int GREEN_DRAGON_7868 = 7868; public static final int GREEN_DRAGON_7869 = 7869; public static final int GREEN_DRAGON_7870 = 7870; public static final int GREATER_DEMON_7871 = 7871; public static final int GREATER_DEMON_7872 = 7872; public static final int GREATER_DEMON_7873 = 7873; public static final int BLACK_DEMON_7874 = 7874; public static final int BLACK_DEMON_7875 = 7875; public static final int BLACK_DEMON_7876 = 7876; public static final int HELLHOUND_7877 = 7877; public static final int ICE_GIANT_7878 = 7878; public static final int ICE_GIANT_7879 = 7879; public static final int ICE_GIANT_7880 = 7880; public static final int REVENANT_IMP = 7881; public static final int DUSK_7882 = 7882; public static final int DUSK_7883 = 7883; public static final int DAWN_7884 = 7884; public static final int DAWN_7885 = 7885; public static final int DUSK_7886 = 7886; public static final int DUSK_7887 = 7887; public static final int DUSK_7888 = 7888; public static final int DUSK_7889 = 7889; public static final int MIDNIGHT = 7890; public static final int NOON = 7891; public static final int NOON_7892 = 7892; public static final int MIDNIGHT_7893 = 7893; public static final int SAND_SNAKE_HARD = 7894; public static final int SAND_SNAKE = 7895; public static final int ARTUR_HOSIDIUS = 7898; public static final int ARTUR_HOSIDIUS_7899 = 7899; public static final int BUTLER_JARVIS = 7900; public static final int CHEF_OLIVIA = 7901; public static final int GALANA = 7902; public static final int SAND_SNAKE_7903 = 7903; public static final int TOMAS_LAWRY = 7904; public static final int ROBERT_OREILLY = 7905; public static final int DEVAN_RUTTER = 7906; public static final int CONRAD_KING = 7907; public static final int THE_QUEEN_OF_THIEVES = 7908; public static final int LADY_SHAUNA_PISCARILIUS = 7909; public static final int SOPHIA_HUGHES = 7910; public static final int BARTENDER_7911 = 7911; public static final int FISH_MONGER_7912 = 7912; public static final int SHOP_KEEPER_7913 = 7913; public static final int THIEF_7914 = 7914; public static final int THIEF_7915 = 7915; public static final int THIEF_7916 = 7916; public static final int PIRATE_7917 = 7917; public static final int PIRATE_7918 = 7918; public static final int MAN_7919 = 7919; public static final int MAN_7920 = 7920; public static final int WOMAN_7921 = 7921; public static final int WOMAN_7922 = 7922; public static final int POOR_LOOKING_WOMAN_7923 = 7923; public static final int REVENANT_GOBLIN = 7931; public static final int REVENANT_PYREFIEND = 7932; public static final int REVENANT_HOBGOBLIN = 7933; public static final int REVENANT_CYCLOPS = 7934; public static final int REVENANT_HELLHOUND = 7935; public static final int REVENANT_DEMON = 7936; public static final int REVENANT_ORK = 7937; public static final int REVENANT_DARK_BEAST = 7938; public static final int REVENANT_KNIGHT = 7939; public static final int REVENANT_DRAGON = 7940; public static final int IRON_MAN_TUTOR_7941 = 7941; public static final int EMBLEM_TRADER_7943 = 7943; public static final int FISHING_SPOT_7946 = 7946; public static final int FISHING_SPOT_7947 = 7947; public static final int CORSAIR_TRAITOR_HARD = 7948; public static final int CORSAIR_TRAITOR = 7949; public static final int ALEC_KINCADE = 7950; public static final int PONTS_THE_BRIDGEMASTER = 7951; public static final int ERDAN = 7952; public static final int PRIMULA = 7953; public static final int MYSTERIOUS_ADVENTURER = 7954; public static final int BABY_BLACK_DRAGON_7955 = 7955; public static final int CAPTAIN_TOCK = 7956; public static final int CAPTAIN_TOCK_7957 = 7957; public static final int CAPTAIN_TOCK_7958 = 7958; public static final int ITHOI_THE_NAVIGATOR = 7961; public static final int ITHOI_THE_NAVIGATOR_7963 = 7963; public static final int ITHOI_THE_NAVIGATOR_7964 = 7964; public static final int CABIN_BOY_COLIN = 7965; public static final int CABIN_BOY_COLIN_7966 = 7966; public static final int CABIN_BOY_COLIN_7967 = 7967; public static final int BUGS_7969 = 7969; public static final int GNOCCI_THE_COOK = 7970; public static final int GNOCCI_THE_COOK_7971 = 7971; public static final int GNOCCI_THE_COOK_7972 = 7972; public static final int DOLL = 7975; public static final int ARSEN_THE_THIEF = 7976; public static final int THE_MIMIC = 7979; public static final int YUSUF = 7981; public static final int YUSUF_7982 = 7982; public static final int FRANCOIS = 7983; public static final int MADAME_CALDARIUM = 7984; public static final int HARIS = 7985; public static final int ALTARKIZ = 7986; public static final int LORD_MARSHAL_BROGAN = 7987; public static final int CHIEF_TESS = 7988; public static final int OGRESS_WARRIOR = 7989; public static final int OGRESS_WARRIOR_7990 = 7990; public static final int OGRESS_SHAMAN = 7991; public static final int OGRESS_SHAMAN_7992 = 7992; public static final int ELDER_CHAOS_DRUID_7995 = 7995; public static final int CORRUPT_LIZARDMAN_HARD = 7996; public static final int CORRUPT_LIZARDMAN = 7997; public static final int PHILEAS_RIMOR = 7999; public static final int CORRUPT_LIZARDMAN_8000 = 8000; public static final int CRUNCHY = 8001; public static final int TIM = 8002; public static final int DAVE = 8003; public static final int GENE = 8004; public static final int ART = 8005; public static final int GNOSI = 8006; public static final int HISTORIAN_DUFFY = 8007; public static final int CORPOREAL_CRITTER = 8008; public static final int TZREKZUK = 8009; public static final int CORPOREAL_CRITTER_8010 = 8010; public static final int TZREKZUK_8011 = 8011; public static final int BARGE_GUARD_8012 = 8012; public static final int BARGE_GUARD_8013 = 8013; public static final int KING_NARNODE_SHAREEN = 8019; public static final int KING_NARNODE_SHAREEN_8020 = 8020; public static final int NATURAL_HISTORIAN_8021 = 8021; public static final int MYSTERIOUS_VOICE = 8022; public static final int GNOSI_8023 = 8023; public static final int RIFT_GUARDIAN_8024 = 8024; public static final int VORKI = 8025; public static final int VORKATH = 8026; public static final int RUNE_DRAGON = 8027; public static final int RIFT_GUARDIAN_8028 = 8028; public static final int VORKI_8029 = 8029; public static final int ADAMANT_DRAGON = 8030; public static final int RUNE_DRAGON_8031 = 8031; public static final int ELVARG_8033 = 8033; public static final int BOB_8034 = 8034; public static final int NEITE_8035 = 8035; public static final int DIANA = 8036; public static final int JACK_8037 = 8037; public static final int ELLEN = 8038; public static final int FREJA = 8039; public static final int LUTWIDGE = 8040; public static final int DOG_8041 = 8041; public static final int KING_ROALD_8042 = 8042; public static final int AEONISIG_RAISPHER_8043 = 8043; public static final int SIR_AMIK_VARZE_8044 = 8044; public static final int SIR_TIFFY_CASHIEN_8045 = 8045; public static final int KING_LATHAS = 8046; public static final int KING_ARTHUR_8047 = 8047; public static final int BRUNDT_THE_CHIEFTAIN = 8048; public static final int ONEIROMANCER_8049 = 8049; public static final int DENULTH_8050 = 8050; public static final int DUKE_HORACIO_8051 = 8051; public static final int WISE_OLD_MAN_8052 = 8052; public static final int JARDRIC_8053 = 8053; public static final int ACHIETTIES_8054 = 8054; public static final int BOB_8055 = 8055; public static final int SPAWN_8056 = 8056; public static final int ROBERT_THE_STRONG_8057 = 8057; public static final int VORKATH_8058 = 8058; public static final int VORKATH_8059 = 8059; public static final int VORKATH_8060 = 8060; public static final int VORKATH_8061 = 8061; public static final int ZOMBIFIED_SPAWN = 8062; public static final int ZOMBIFIED_SPAWN_8063 = 8063; public static final int STONE_GUARDIAN = 8064; public static final int STONE_GUARDIAN_8065 = 8065; public static final int STONE_GUARDIAN_8066 = 8066; public static final int ZOMBIE_8067 = 8067; public static final int ZOMBIE_8068 = 8068; public static final int ZOMBIE_8069 = 8069; public static final int SKELETON_8070 = 8070; public static final int SKELETON_8071 = 8071; public static final int SKELETON_8072 = 8072; public static final int GREEN_DRAGON_8073 = 8073; public static final int BLUE_DRAGON_8074 = 8074; public static final int RED_DRAGON_8075 = 8075; public static final int GREEN_DRAGON_8076 = 8076; public static final int BLUE_DRAGON_8077 = 8077; public static final int RED_DRAGON_8078 = 8078; public static final int RED_DRAGON_8079 = 8079; public static final int IRON_DRAGON_8080 = 8080; public static final int BRUTAL_GREEN_DRAGON_8081 = 8081; public static final int GREEN_DRAGON_8082 = 8082; public static final int BLUE_DRAGON_8083 = 8083; public static final int BLACK_DRAGON_8084 = 8084; public static final int BLACK_DRAGON_8085 = 8085; public static final int STEEL_DRAGON_8086 = 8086; public static final int BRUTAL_RED_DRAGON_8087 = 8087; public static final int MITHRIL_DRAGON_8088 = 8088; public static final int MITHRIL_DRAGON_8089 = 8089; public static final int ADAMANT_DRAGON_8090 = 8090; public static final int RUNE_DRAGON_8091 = 8091; public static final int BRUTAL_BLACK_DRAGON_8092 = 8092; public static final int BRUTAL_BLACK_DRAGON_8093 = 8093; public static final int GALVEK = 8094; public static final int GALVEK_8095 = 8095; public static final int GALVEK_8096 = 8096; public static final int GALVEK_8097 = 8097; public static final int GALVEK_8098 = 8098; public static final int TSUNAMI = 8099; public static final int DALLAS_JONES = 8100; public static final int DALLAS_JONES_8101 = 8101; public static final int DALLAS_JONES_8102 = 8102; public static final int DALLAS_JONES_8103 = 8103; public static final int DALLAS_JONES_8104 = 8104; public static final int JARDRIC_8105 = 8105; public static final int JARDRIC_8106 = 8106; public static final int JARDRIC_8107 = 8107; public static final int JARDRIC_8108 = 8108; public static final int BOB_8111 = 8111; public static final int BOB_8112 = 8112; public static final int BOB_8113 = 8113; public static final int BOB_8114 = 8114; public static final int BOB_8115 = 8115; public static final int NOT_BOB = 8116; public static final int NOT_BOB_8117 = 8117; public static final int NEITE_8118 = 8118; public static final int UNFERTH_8119 = 8119; public static final int DRAGONKIN_8120 = 8120; public static final int CAMORRA = 8121; public static final int TRISTAN = 8122; public static final int AIVAS = 8123; public static final int ROBERT_THE_STRONG_8124 = 8124; public static final int DRAGONKIN_8125 = 8125; public static final int CAMORRA_8126 = 8126; public static final int TRISTAN_8127 = 8127; public static final int AIVAS_8128 = 8128; public static final int ROBERT_THE_STRONG_8129 = 8129; public static final int ODYSSEUS_8130 = 8130; public static final int TORFINN = 8131; public static final int ENIOLA = 8132; public static final int ODOVACAR = 8133; public static final int SARAH_8134 = 8134; public static final int DRAGONKIN_8135 = 8135; public static final int ZORGOTH = 8136; public static final int SPIDER_8137 = 8137; public static final int SPIDER_8138 = 8138; public static final int SKELETON_8139 = 8139; public static final int SKELETON_8140 = 8140; public static final int STRANGE_EGG = 8142; public static final int DRAGON_HEAD = 8143; public static final int DRAGON_HEAD_8144 = 8144; public static final int BRUNDT_THE_CHIEFTAIN_8145 = 8145; public static final int THORVALD_THE_WARRIOR_8146 = 8146; public static final int PEER_THE_SEER_8147 = 8147; public static final int SWENSEN_THE_NAVIGATOR_8148 = 8148; public static final int WHITE_KNIGHT_8149 = 8149; public static final int PALADIN_8150 = 8150; public static final int KOSCHEI_THE_DEATHLESS_8151 = 8151; public static final int KOSCHEI_THE_DEATHLESS_8152 = 8152; public static final int BRUNDT_THE_CHIEFTAIN_8153 = 8153; public static final int WISE_OLD_MAN_8154 = 8154; public static final int JARDRIC_8155 = 8155; public static final int ACHIETTIES_8156 = 8156; public static final int SIR_TIFFY_CASHIEN_8157 = 8157; public static final int ONEIROMANCER_8158 = 8158; public static final int BOB_8159 = 8159; public static final int SOLDIER_8160 = 8160; public static final int BRUNDT_THE_CHIEFTAIN_8161 = 8161; public static final int WISE_OLD_MAN_8162 = 8162; public static final int HISTORIAN_DUFFY_8163 = 8163; public static final int ACHIETTIES_8164 = 8164; public static final int SIR_TIFFY_CASHIEN_8165 = 8165; public static final int ONEIROMANCER_8166 = 8166; public static final int ZORGOTH_8167 = 8167; public static final int SOLDIER_8168 = 8168; public static final int BRUNDT_THE_CHIEFTAIN_8169 = 8169; public static final int WISE_OLD_MAN_8170 = 8170; public static final int JARDRIC_8171 = 8171; public static final int ACHIETTIES_8172 = 8172; public static final int SIR_TIFFY_CASHIEN_8173 = 8173; public static final int ONEIROMANCER_8174 = 8174; public static final int ZORGOTH_8175 = 8175; public static final int ZORGOTH_8176 = 8176; public static final int GALVEK_8177 = 8177; public static final int GALVEK_8178 = 8178; public static final int GALVEK_8179 = 8179; public static final int AMELIA = 8180; public static final int JONATHAN = 8181; public static final int NATURAL_HISTORIAN_8182 = 8182; public static final int LITTLE_PARASITE = 8183; public static final int BOULDER_8188 = 8188; public static final int GRAVE_DIGGER = 8189; public static final int JAMES = 8193; public static final int GROWTHLING = 8194; public static final int BRYOPHYTA = 8195; public static final int PUPPADILE = 8196; public static final int TEKTINY = 8197; public static final int VANGUARD_8198 = 8198; public static final int VASA_MINIRIO = 8199; public static final int VESPINA = 8200; public static final int PUPPADILE_8201 = 8201; public static final int TEKTINY_8202 = 8202; public static final int VANGUARD_8203 = 8203; public static final int VASA_MINIRIO_8204 = 8204; public static final int VESPINA_8205 = 8205; public static final int GARTH_8206 = 8206; public static final int GARTH_8207 = 8207; public static final int MYSTERIOUS_STRANGER = 8208; public static final int VYRELORD = 8209; public static final int VYRELADY = 8210; public static final int MEIYERDITCH_CITIZEN_8211 = 8211; public static final int HARPERT = 8212; public static final int MERCENARY_8213 = 8213; public static final int MERCENARY_8214 = 8214; public static final int MERCENARY_8215 = 8215; public static final int SAFALAAN_HALLOW_8216 = 8216; public static final int SAFALAAN_HALLOW_8217 = 8217; public static final int SAFALAAN_HALLOW_8218 = 8218; public static final int SAFALAAN_HALLOW_8219 = 8219; public static final int VERTIDA_SEFALATIS = 8220; public static final int VERTIDA_SEFALATIS_8221 = 8221; public static final int VERTIDA_SEFALATIS_8222 = 8222; public static final int VERTIDA_SEFALATIS_8223 = 8223; public static final int FLAYGIAN_SCREWTE = 8224; public static final int FLAYGIAN_SCREWTE_8225 = 8225; public static final int MEKRITUS_AHARA = 8226; public static final int MEKRITUS_AHARA_8227 = 8227; public static final int ANDIESS_JUIP = 8228; public static final int ANDIESS_JUIP_8229 = 8229; public static final int KAEL_FORSHAW = 8230; public static final int KAEL_FORSHAW_8231 = 8231; public static final int KAEL_FORSHAW_8232 = 8232; public static final int KAEL_FORSHAW_8233 = 8233; public static final int MEIYERDITCH_CITIZEN_8235 = 8235; public static final int MEIYERDITCH_CITIZEN_8236 = 8236; public static final int MEIYERDITCH_CITIZEN_8237 = 8237; public static final int VANSTROM_KLAUSE_8238 = 8238; public static final int VANSTROM_KLAUSE_8239 = 8239; public static final int VANSTROM_KLAUSE_8240 = 8240; public static final int RANIS_DRAKAN_8241 = 8241; public static final int RANIS_DRAKAN_8242 = 8242; public static final int RANIS_DRAKAN_8243 = 8243; public static final int RANIS_DRAKAN_8244 = 8244; public static final int RANIS_DRAKAN_8245 = 8245; public static final int RANIS_DRAKAN_8246 = 8246; public static final int RANIS_DRAKAN_8247 = 8247; public static final int RANIS_DRAKAN_8248 = 8248; public static final int VANESCULA_DRAKAN_8249 = 8249; public static final int VERZIK_VITUR = 8250; public static final int VYREWATCH_8251 = 8251; public static final int VYREWATCH_8252 = 8252; public static final int VYREWATCH_8253 = 8253; public static final int VYREWATCH_8254 = 8254; public static final int VYREWATCH_8255 = 8255; public static final int VYREWATCH_8256 = 8256; public static final int VYREWATCH_8257 = 8257; public static final int VYREWATCH_8258 = 8258; public static final int VYREWATCH_8259 = 8259; public static final int ABOMINATION = 8260; public static final int ABOMINATION_8261 = 8261; public static final int ABOMINATION_8262 = 8262; public static final int NYLOCAS_ISCHYROS = 8263; public static final int NYLOCAS_TOXOBOLOS = 8264; public static final int ANDRAS = 8267; public static final int ANDRAS_8268 = 8268; public static final int YENRAB = 8269; public static final int LAHSRAM = 8270; public static final int ERODOEHT = 8271; public static final int LECTOR_GURA = 8273; public static final int SISTER_SEVI = 8274; public static final int SISTER_TOEN = 8275; public static final int SISTER_YRAM = 8276; public static final int LADY_CROMBWICK = 8287; public static final int NEMISHKA = 8288; public static final int SWAMP_CRAB = 8297; public static final int SWAMP_CRAB_8298 = 8298; public static final int SWAMPY_LOG = 8299; public static final int VYREWATCH_8300 = 8300; public static final int VYREWATCH_8301 = 8301; public static final int VYREWATCH_8302 = 8302; public static final int VYREWATCH_8303 = 8303; public static final int VYREWATCH_8304 = 8304; public static final int VYREWATCH_8305 = 8305; public static final int VYREWATCH_8306 = 8306; public static final int VYREWATCH_8307 = 8307; public static final int MEIYERDITCH_CITIZEN_8320 = 8320; public static final int BANKER_8321 = 8321; public static final int BANKER_8322 = 8322; public static final int VYRE_ORATOR = 8323; public static final int VYRE_ORATOR_8324 = 8324; public static final int VAMPYRE_JUVENILE_8326 = 8326; public static final int VAMPYRE_JUVENILE_8327 = 8327; public static final int MEIYERDITCH_CITIZEN_8328 = 8328; public static final int MEIYERDITCH_CITIZEN_8329 = 8329; public static final int MEIYERDITCH_CITIZEN_8330 = 8330; public static final int MEIYERDITCH_CITIZEN_8331 = 8331; public static final int VYRELORD_8332 = 8332; public static final int VYRELADY_8333 = 8333; public static final int VYRELORD_8334 = 8334; public static final int VYRELADY_8335 = 8335; public static final int LIL_ZIK = 8336; public static final int LIL_ZIK_8337 = 8337; public static final int XARPUS = 8338; public static final int XARPUS_8339 = 8339; public static final int XARPUS_8340 = 8340; public static final int XARPUS_8341 = 8341; public static final int NYLOCAS_ISCHYROS_8342 = 8342; public static final int NYLOCAS_TOXOBOLOS_8343 = 8343; public static final int NYLOCAS_HAGIOS = 8344; public static final int NYLOCAS_ISCHYROS_8345 = 8345; public static final int NYLOCAS_TOXOBOLOS_8346 = 8346; public static final int NYLOCAS_HAGIOS_8347 = 8347; public static final int NYLOCAS_ISCHYROS_8348 = 8348; public static final int NYLOCAS_TOXOBOLOS_8349 = 8349; public static final int NYLOCAS_HAGIOS_8350 = 8350; public static final int NYLOCAS_ISCHYROS_8351 = 8351; public static final int NYLOCAS_TOXOBOLOS_8352 = 8352; public static final int NYLOCAS_HAGIOS_8353 = 8353; public static final int NYLOCAS_VASILIAS = 8354; public static final int NYLOCAS_VASILIAS_8355 = 8355; public static final int NYLOCAS_VASILIAS_8356 = 8356; public static final int NYLOCAS_VASILIAS_8357 = 8357; public static final int PESTILENT_BLOAT = 8359; public static final int THE_MAIDEN_OF_SUGADINTI = 8360; public static final int THE_MAIDEN_OF_SUGADINTI_8361 = 8361; public static final int THE_MAIDEN_OF_SUGADINTI_8362 = 8362; public static final int THE_MAIDEN_OF_SUGADINTI_8363 = 8363; public static final int THE_MAIDEN_OF_SUGADINTI_8364 = 8364; public static final int THE_MAIDEN_OF_SUGADINTI_8365 = 8365; public static final int NYLOCAS_MATOMENOS = 8366; public static final int BLOOD_SPAWN = 8367; public static final int ABIGAILA = 8368; public static final int VERZIK_VITUR_8369 = 8369; public static final int VERZIK_VITUR_8370 = 8370; public static final int VERZIK_VITUR_8371 = 8371; public static final int VERZIK_VITUR_8372 = 8372; public static final int VERZIK_VITUR_8373 = 8373; public static final int VERZIK_VITUR_8374 = 8374; public static final int VERZIK_VITUR_8375 = 8375; public static final int WEB = 8376; public static final int COLLAPSING_PILLAR = 8377; public static final int COLLAPSING_PILLAR_8378 = 8378; public static final int SUPPORTING_PILLAR = 8379; public static final int NYLOCAS_ISCHYROS_8381 = 8381; public static final int NYLOCAS_TOXOBOLOS_8382 = 8382; public static final int NYLOCAS_HAGIOS_8383 = 8383; public static final int NYLOCAS_ATHANATOS = 8384; public static final int NYLOCAS_MATOMENOS_8385 = 8385; public static final int SOTETSEG = 8387; public static final int SOTETSEG_8388 = 8388; public static final int NIGEL = 8390; public static final int NIGEL_8391 = 8391; public static final int MONK_OF_ZAMORAK_8400 = 8400; public static final int MONK_OF_ZAMORAK_8401 = 8401; public static final int ASKELADDEN = 8402; public static final int ASKELADDEN_8403 = 8403; public static final int ASKELADDEN_8404 = 8404; public static final int ASKELADDEN_8405 = 8405; public static final int WISE_OLD_MAN_8407 = 8407; public static final int WISE_OLD_MAN_8409 = 8409; public static final int WISE_YOUNG_MAN = 8410; public static final int MY_ARM_8411 = 8411; public static final int DRUNKEN_DWARFS_LEG_8419 = 8419; public static final int SQUIRREL_8422 = 8422; public static final int WOLFBONE = 8424; public static final int MOTHER = 8425; public static final int MOTHER_8426 = 8426; public static final int MOTHER_8428 = 8428; public static final int MOTHER_8429 = 8429; public static final int MOTHER_8430 = 8430; public static final int SNOWFLAKE = 8431; public static final int ODD_MUSHROOM = 8434; public static final int ODD_MUSHROOM_8435 = 8435; public static final int DONT_KNOW_WHAT = 8438; public static final int DONT_KNOW_WHAT_8439 = 8439; public static final int DONT_KNOW_WHAT_8440 = 8440; public static final int BOULDER_8442 = 8442; public static final int ROOT = 8444; public static final int ROOT_8445 = 8445; public static final int ICICLE = 8446; public static final int ICICLE_8447 = 8447; public static final int DRIFTWOOD = 8448; public static final int DRIFTWOOD_8449 = 8449; public static final int PEBBLE = 8450; public static final int PEBBLE_8451 = 8451; public static final int GOAT_POO = 8452; public static final int GOAT_POO_8453 = 8453; public static final int YELLOW_SNOW = 8454; public static final int YELLOW_SNOW_8455 = 8455; public static final int BUTTERFLY_8456 = 8456; public static final int BUTTERFLY_8459 = 8459; public static final int ODD_STONE = 8460; public static final int ODD_STONE_8463 = 8463; public static final int SQUIRREL_8464 = 8464; public static final int SQUIRREL_8467 = 8467; public static final int TROLL_8470 = 8470; public static final int TROLL_8471 = 8471; public static final int TROLL_8472 = 8472; public static final int TROLL_8473 = 8473; public static final int BLACK_GUARD_8474 = 8474; public static final int BLACK_GUARD_8475 = 8475; public static final int BLACK_GUARD_8476 = 8476; public static final int COMBAT_TEST_MAXHIT = 8479; public static final int WIZARD_CROMPERTY = 8480; public static final int WIZARD_CROMPERTY_8481 = 8481; public static final int SMOKE_DEVIL_8482 = 8482; public static final int SMOKE_DEVIL_8483 = 8483; public static final int VEOS_8484 = 8484; public static final int EEK = 8485; public static final int MAKEOVER_MAGE_8487 = 8487; public static final int THE_COLLECTOR = 8491; public static final int IKKLE_HYDRA = 8492; public static final int IKKLE_HYDRA_8493 = 8493; public static final int IKKLE_HYDRA_8494 = 8494; public static final int IKKLE_HYDRA_8495 = 8495; public static final int DWARF_8496 = 8496; public static final int OLD_DWARF = 8500; public static final int MORI = 8501; public static final int MORI_8502 = 8502; public static final int SURVIVAL_EXPERT = 8503; public static final int LORD_TROBIN_ARCEUUS = 8504; public static final int LORD_TROBIN_ARCEUUS_8505 = 8505; public static final int TOWER_MAGE_8507 = 8507; public static final int TOWER_MAGE_8508 = 8508; public static final int TOWER_MAGE_8509 = 8509; public static final int TOWER_MAGE_8510 = 8510; public static final int TOWER_MAGE_8511 = 8511; public static final int TORMENTED_SOUL = 8512; public static final int TORMENTED_SOUL_8513 = 8513; public static final int TRAPPED_SOUL = 8514; public static final int ALYSSA = 8515; public static final int IKKLE_HYDRA_8517 = 8517; public static final int IKKLE_HYDRA_8518 = 8518; public static final int IKKLE_HYDRA_8519 = 8519; public static final int IKKLE_HYDRA_8520 = 8520; public static final int ALRY_THE_ANGLER = 8521; public static final int CORMORANT_8522 = 8522; public static final int FISHING_SPOT_8523 = 8523; public static final int ROD_FISHING_SPOT_8524 = 8524; public static final int FISHING_SPOT_8525 = 8525; public static final int FISHING_SPOT_8526 = 8526; public static final int FISHING_SPOT_8527 = 8527; public static final int TRAPPED_SOUL_8528 = 8528; public static final int TRAPPED_SOUL_HARD = 8529; public static final int AMELIA_8530 = 8530; public static final int ALLANNA = 8531; public static final int JATIX = 8532; public static final int NIKKIE = 8533; public static final int ROSIE = 8534; public static final int ALAN = 8535; public static final int ALEXANDRA = 8536; public static final int LATLINK_FASTBELL = 8537; public static final int ELISE = 8538; public static final int ARC_TEST_01 = 8539; public static final int ARC_TEST_02 = 8540; public static final int LITTLE_PARASITE_8541 = 8541; public static final int ROYAL_GUARD = 8542; public static final int ROYAL_GUARD_8543 = 8543; public static final int UNDOR = 8544; public static final int UNDOR_8545 = 8545; public static final int THIRUS = 8546; public static final int THIRUS_8547 = 8547; public static final int DARCOR_QUO_NARGA = 8548; public static final int UURRAK_QUO_NARGA = 8549; public static final int MARMOR_QUO_NARGA = 8550; public static final int LORNOR_QUO_NARGA = 8551; public static final int GORHAK_QUO_NARGA = 8552; public static final int FORNEK_QUO_MATEN = 8553; public static final int VORNAS_QUO_MATEN = 8554; public static final int XORRAH_QUO_SIHAR = 8555; public static final int CORKAT_QUO_SIHAR = 8556; public static final int LOKRAA_QUO_SIHAR = 8557; public static final int WENGRA_QUO_SIHAR = 8558; public static final int HALDOR_QUO_KERAN = 8559; public static final int VORTAS_QUO_KERAN = 8560; public static final int MALLAK_QUO_KERAN = 8561; public static final int RICHARD_FLINTMAUL = 8562; public static final int LIZARDMAN_8563 = 8563; public static final int LIZARDMAN_BRUTE_8564 = 8564; public static final int LIZARDMAN_SHAMAN_8565 = 8565; public static final int RANGER_8566 = 8566; public static final int SOLDIER_8567 = 8567; public static final int SOLDIER_8568 = 8568; public static final int DOYEN = 8569; public static final int DOYEN_8570 = 8570; public static final int NURSE_EMMA_GENTSY = 8571; public static final int WOUNDED_SOLDIER_8572 = 8572; public static final int WOUNDED_SOLDIER_8573 = 8573; public static final int WOUNDED_SOLDIER_8574 = 8574; public static final int SOLDIER_8575 = 8575; public static final int LOVAKENGJ_ENGINEER = 8576; public static final int GENERAL_VIR = 8577; public static final int SWAMP_FROG = 8578; public static final int SHAYZIEN_INFILTRATOR = 8579; public static final int KETSAL_KUK = 8581; public static final int EKANS_CHAN = 8582; public static final int HESPORI = 8583; public static final int FLOWER = 8584; public static final int FLOWER_8585 = 8585; public static final int GUILDMASTER_JANE = 8586; public static final int GUILDMASTER_JANE_8587 = 8587; public static final int ARNO = 8588; public static final int BANKER_8589 = 8589; public static final int BANKER_8590 = 8590; public static final int RABBIT_8591 = 8591; public static final int RABBIT_8592 = 8592; public static final int RABBIT_8593 = 8593; public static final int CAT_8594 = 8594; public static final int FELFIZ_YARYUS = 8595; public static final int KEITH = 8596; public static final int ORNATE_COMBAT_DUMMY = 8598; public static final int SOLDIER_8599 = 8599; public static final int SERGEANT_8600 = 8600; public static final int RANGER_8601 = 8601; public static final int KAALKETJOR = 8602; public static final int KAALMEJSAN = 8603; public static final int KAALXILDAR = 8604; public static final int TARFOL_QUO_MATEN = 8605; public static final int KORMAR_QUO_MATEN = 8606; public static final int GARBEK_QUO_MATEN = 8607; public static final int ORRVOR_QUO_MATEN = 8608; public static final int HYDRA = 8609; public static final int WYRM = 8610; public static final int WYRM_8611 = 8611; public static final int DRAKE_8612 = 8612; public static final int DRAKE_8613 = 8613; public static final int SULPHUR_LIZARD = 8614; public static final int ALCHEMICAL_HYDRA = 8615; public static final int ALCHEMICAL_HYDRA_8616 = 8616; public static final int ALCHEMICAL_HYDRA_8617 = 8617; public static final int ALCHEMICAL_HYDRA_8618 = 8618; public static final int ALCHEMICAL_HYDRA_8619 = 8619; public static final int ALCHEMICAL_HYDRA_8620 = 8620; public static final int ALCHEMICAL_HYDRA_8621 = 8621; public static final int ALCHEMICAL_HYDRA_8622 = 8622; public static final int KONAR_QUO_MATEN = 8623; public static final int TAYLOR = 8629; public static final int VEOS_8630 = 8630; public static final int SEAMAN_MORRIS = 8631; public static final int THE_MIMIC_8633 = 8633; public static final int ALCHEMICAL_HYDRA_8634 = 8634; public static final int THIRD_AGE_WARRIOR = 8635; public static final int THIRD_AGE_RANGER = 8636; public static final int THIRD_AGE_MAGE = 8637; public static final int URI_8638 = 8638; public static final int FIRE_8643 = 8643; public static final int SARADOMINIST_RECRUITER = 8644; public static final int ARTHUR_THE_CLUE_HUNTER = 8665; public static final int BANKER_8666 = 8666; public static final int PUFFER_FISH_8667 = 8667; public static final int ISLWYN_8675 = 8675; public static final int ILFEEN = 8676; public static final int FERAL_VAMPYRE_8678 = 8678; public static final int ABIDOR_CRANK_8679 = 8679; public static final int DAVON = 8680; public static final int ZENESHA_8681 = 8681; public static final int AEMAD = 8682; public static final int KORTAN = 8683; public static final int ROACHEY = 8684; public static final int FRENITA = 8685; public static final int NURMOF = 8686; public static final int TEA_SELLER = 8687; public static final int FAT_TONY = 8688; public static final int ANCIENT_FUNGI = 8690; public static final int ANCIENT_FUNGI_8691 = 8691; public static final int NOTERAZZO = 8692; public static final int DIANGO = 8693; public static final int BRIAN_8694 = 8694; public static final int MOSOL_REI_8696 = 8696; public static final int LEKE_QUO_KERAN = 8697; public static final int MONK_OF_ZAMORAK_8698 = 8698; public static final int LARRAN = 8699; public static final int GIANT_FROG_8700 = 8700; public static final int BIG_FROG_8701 = 8701; public static final int FROG_8702 = 8702; public static final int TEMPLE_SPIDER = 8703; public static final int BROTHER_AIMERI = 8704; public static final int BROTHER_AIMERI_8705 = 8705; public static final int OLBERTUS = 8706; public static final int OLBERTUS_8707 = 8707; public static final int OLBERTUS_8708 = 8708; public static final int SHAEDED_BEAST = 8709; public static final int SHAEDED_BEAST_8710 = 8710; public static final int EODAN = 8711; public static final int KNIGHT_OF_VARLAMORE_8712 = 8712; public static final int SARACHNIS = 8713; public static final int SPAWN_OF_SARACHNIS = 8714; public static final int SPAWN_OF_SARACHNIS_8715 = 8715; public static final int JUSTINE = 8721; public static final int SILVER_MERCHANT_8722 = 8722; public static final int GEM_MERCHANT_8723 = 8723; public static final int BAKER_8724 = 8724; public static final int BAKER_8725 = 8725; public static final int SPICE_SELLER_8726 = 8726; public static final int FUR_TRADER_8727 = 8727; public static final int SILK_MERCHANT_8728 = 8728; public static final int YOUNGLLEF = 8729; public static final int CORRUPTED_YOUNGLLEF = 8730; public static final int SMOLCANO = 8731; public static final int MUGGER_8732 = 8732; public static final int CRAB_8733 = 8733; public static final int MOSS_GIANT_8736 = 8736; public static final int YOUNGLLEF_8737 = 8737; public static final int CORRUPTED_YOUNGLLEF_8738 = 8738; public static final int SMOLCANO_8739 = 8739; public static final int CRYSTAL_IMPLING = 8741; public static final int CRYSTAL_IMPLING_8742 = 8742; public static final int CRYSTAL_IMPLING_8743 = 8743; public static final int CRYSTAL_IMPLING_8744 = 8744; public static final int CRYSTAL_IMPLING_8745 = 8745; public static final int CRYSTAL_IMPLING_8746 = 8746; public static final int CRYSTAL_IMPLING_8747 = 8747; public static final int CRYSTAL_IMPLING_8748 = 8748; public static final int CRYSTAL_IMPLING_8749 = 8749; public static final int CRYSTAL_IMPLING_8750 = 8750; public static final int CRYSTAL_IMPLING_8751 = 8751; public static final int CRYSTAL_IMPLING_8752 = 8752; public static final int CRYSTAL_IMPLING_8753 = 8753; public static final int CRYSTAL_IMPLING_8754 = 8754; public static final int CRYSTAL_IMPLING_8755 = 8755; public static final int CRYSTAL_IMPLING_8756 = 8756; public static final int CRYSTAL_IMPLING_8757 = 8757; public static final int LORD_IORWERTH = 8758; public static final int IORWERTH_WARRIOR_8759 = 8759; public static final int IORWERTH_ARCHER_8760 = 8760; public static final int ELF_TRACKER = 8761; public static final int TYRAS_GUARD_8762 = 8762; public static final int CAPTAIN_BARNABY_8763 = 8763; public static final int CAPTAIN_BARNABY_8764 = 8764; public static final int COUNCILLOR_HALGRIVE_8765 = 8765; public static final int ELUNED_8766 = 8766; public static final int ELUNED_8767 = 8767; public static final int ELVEN_SCOUT = 8768; public static final int ILFEEN_8769 = 8769; public static final int ELVEN_SCOUT_8770 = 8770; public static final int MOURNER = 8771; public static final int SLAVE = 8772; public static final int SLAVE_8773 = 8773; public static final int SLAVE_8774 = 8774; public static final int SEREN = 8775; public static final int MEMORY_OF_SEREN = 8776; public static final int MEMORY_OF_SEREN_8777 = 8777; public static final int MEMORY_OF_SEREN_8778 = 8778; public static final int MEMORY_OF_SEREN_8779 = 8779; public static final int MEMORY_OF_SEREN_8780 = 8780; public static final int MEMORY_OF_SEREN_8781 = 8781; public static final int MEMORY_OF_SEREN_8782 = 8782; public static final int MEMORY_OF_SEREN_8783 = 8783; public static final int MEMORY_OF_SEREN_8784 = 8784; public static final int ELENA_8791 = 8791; public static final int ELENA_8792 = 8792; public static final int ELENA_8793 = 8793; public static final int ELENA_8794 = 8794; public static final int ELENA_8795 = 8795; public static final int ELENA_8797 = 8797; public static final int ELENA_8798 = 8798; public static final int KNIGHT_OF_ARDOUGNE_8799 = 8799; public static final int KNIGHT_OF_ARDOUGNE_8800 = 8800; public static final int KNIGHT_OF_ARDOUGNE_8801 = 8801; public static final int COUNCILLOR_HALGRIVE_8802 = 8802; public static final int COUNCILLOR_HALGRIVE_8803 = 8803; public static final int OMART = 8804; public static final int KILRON = 8805; public static final int JETHICK = 8806; public static final int CARLA = 8807; public static final int BAXTORIAN = 8808; public static final int BAXTORIAN_8809 = 8809; public static final int BAXTORIAN_8810 = 8810; public static final int BAXTORIAN_8811 = 8811; public static final int BAXTORIAN_8812 = 8812; public static final int BAXTORIAN_8813 = 8813; public static final int YSGAWYN = 8814; public static final int YSGAWYN_8815 = 8815; public static final int YSGAWYN_8816 = 8816; public static final int ISLWYN_8818 = 8818; public static final int ISLWYN_8819 = 8819; public static final int ISLWYN_8821 = 8821; public static final int ISLWYN_8822 = 8822; public static final int ISLWYN_8823 = 8823; public static final int ILFEEN_8825 = 8825; public static final int ILFEEN_8827 = 8827; public static final int ELUNED_8829 = 8829; public static final int ELUNED_8830 = 8830; public static final int RESISTANCE_FIGHTER = 8831; public static final int RESISTANCE_FIGHTER_8832 = 8832; public static final int RESISTANCE_FIGHTER_8833 = 8833; public static final int RESISTANCE_FIGHTER_8834 = 8834; public static final int RESISTANCE_FIGHTER_8835 = 8835; public static final int OMART_8836 = 8836; public static final int KILRON_8837 = 8837; public static final int ELENA_8838 = 8838; public static final int JETHICK_8839 = 8839; public static final int OMART_8840 = 8840; public static final int KILRON_8841 = 8841; public static final int KING_LATHAS_8842 = 8842; public static final int LATHAS = 8843; public static final int MOURNER_8844 = 8844; public static final int MOURNER_8845 = 8845; public static final int MOURNER_8846 = 8846; public static final int ESSYLLT_8847 = 8847; public static final int GNOME_8848 = 8848; public static final int PALADIN_8849 = 8849; public static final int PALADIN_8850 = 8850; public static final int KNIGHT_OF_ARDOUGNE_8851 = 8851; public static final int KNIGHT_OF_ARDOUGNE_8852 = 8852; public static final int PALADIN_8853 = 8853; public static final int KNIGHT_OF_ARDOUGNE_8854 = 8854; public static final int KNIGHT_OF_ARDOUGNE_8855 = 8855; public static final int EXECUTIONER = 8856; public static final int HOODED_FIGURE = 8857; public static final int MAN_8858 = 8858; public static final int MAN_8859 = 8859; public static final int MAN_8860 = 8860; public static final int MAN_8861 = 8861; public static final int MAN_8862 = 8862; public static final int WOMAN_8863 = 8863; public static final int WOMAN_8864 = 8864; public static final int ARIANWYN_8865 = 8865; public static final int ARIANWYN_8866 = 8866; public static final int ARIANWYN_8867 = 8867; public static final int ARIANWYN_8868 = 8868; public static final int MORVRAN_8869 = 8869; public static final int MORVRAN_8870 = 8870; public static final int ESSYLLT_8871 = 8871; public static final int ESSYLLT_8872 = 8872; public static final int LORD_IORWERTH_8873 = 8873; public static final int LORD_IORWERTH_8874 = 8874; public static final int LORD_IORWERTH_8875 = 8875; public static final int LORD_IORWERTH_8876 = 8876; public static final int IORWERTH_WARRIOR_8877 = 8877; public static final int IORWERTH_ARCHER_8878 = 8878; public static final int IORWERTH_WARRIOR_8879 = 8879; public static final int IORWERTH_ARCHER_8880 = 8880; public static final int IORWERTH_WARRIOR_8881 = 8881; public static final int IORWERTH_WARRIOR_8882 = 8882; public static final int IORWERTH_WARRIOR_8883 = 8883; public static final int IORWERTH_WARRIOR_8884 = 8884; public static final int IORWERTH_ARCHER_8885 = 8885; public static final int IORWERTH_ARCHER_8886 = 8886; public static final int REBEL_ARCHER = 8887; public static final int REBEL_ARCHER_8888 = 8888; public static final int REBEL_ARCHER_8889 = 8889; public static final int REBEL_WARRIOR = 8890; public static final int REBEL_WARRIOR_8891 = 8891; public static final int LADY_TANGWEN_TRAHAEARN = 8892; public static final int ELDERLY_ELF = 8893; public static final int ELDERLY_ELF_8894 = 8894; public static final int LADY_TANGWEN_TRAHAEARN_8895 = 8895; public static final int MYSTERIOUS_FIGURE = 8897; public static final int LORD_IEUAN_AMLODD = 8898; public static final int LORD_IEUAN_AMLODD_8899 = 8899; public static final int TREE_8901 = 8901; public static final int TREE_8902 = 8902; public static final int LORD_PIQUAN_CRWYS = 8903; public static final int LORD_PIQUAN_CRWYS_8904 = 8904; public static final int ELF_HERMIT = 8906; public static final int LADY_CARYS_HEFIN = 8907; public static final int LADY_CARYS_HEFIN_8908 = 8908; public static final int LADY_FFION_MEILYR = 8910; public static final int LADY_FFION_MEILYR_8911 = 8911; public static final int LADY_KELYN_ITHELL = 8913; public static final int KELYN = 8914; public static final int LADY_KELYN_ITHELL_8915 = 8915; public static final int FRAGMENT_OF_SEREN = 8917; public static final int FRAGMENT_OF_SEREN_8918 = 8918; public static final int FRAGMENT_OF_SEREN_8919 = 8919; public static final int FRAGMENT_OF_SEREN_8920 = 8920; public static final int CRYSTAL_WHIRLWIND = 8921; public static final int IORWERTH_WARRIOR_8922 = 8922; public static final int IORWERTH_ARCHER_8923 = 8923; public static final int IESTIN = 8924; public static final int IESTIN_8925 = 8925; public static final int IESTIN_8926 = 8926; public static final int MAWRTH_8927 = 8927; public static final int MAWRTH_8928 = 8928; public static final int IONA_8929 = 8929; public static final int EOIN_8930 = 8930; public static final int EOIN_8931 = 8931; public static final int REBEL_ARCHER_8932 = 8932; public static final int REBEL_ARCHER_8933 = 8933; public static final int REBEL_WARRIOR_8934 = 8934; public static final int REBEL_WARRIOR_8935 = 8935; public static final int IORWERTH_ARCHER_8936 = 8936; public static final int IORWERTH_ARCHER_8937 = 8937; public static final int IORWERTH_WARRIOR_8938 = 8938; public static final int IORWERTH_WARRIOR_8939 = 8939; public static final int KLANK_8940 = 8940; public static final int NILOOF_8941 = 8941; public static final int KAMEN_8942 = 8942; public static final int THORGEL_8943 = 8943; public static final int GENERAL_HINING_8944 = 8944; public static final int TYRAS_GUARD_8945 = 8945; public static final int REBEL_ARCHER_8946 = 8946; public static final int REBEL_ARCHER_8947 = 8947; public static final int REBEL_WARRIOR_8948 = 8948; public static final int REBEL_WARRIOR_8949 = 8949; public static final int ESSYLLT_8950 = 8950; public static final int BARRIER = 8951; public static final int BARRIER_8952 = 8952; public static final int IORWERTH_ARCHER_8953 = 8953; public static final int IORWERTH_ARCHER_8954 = 8954; public static final int IORWERTH_WARRIOR_8955 = 8955; public static final int IORWERTH_WARRIOR_8956 = 8956; public static final int REBEL_ARCHER_8957 = 8957; public static final int REBEL_ARCHER_8958 = 8958; public static final int REBEL_WARRIOR_8959 = 8959; public static final int REBEL_WARRIOR_8960 = 8960; public static final int TYRAS_GUARD_8961 = 8961; public static final int TYRAS_GUARD_8962 = 8962; public static final int TYRAS_GUARD_8963 = 8963; public static final int TYRAS_GUARD_8964 = 8964; public static final int REBEL_SCOUT = 8965; public static final int REBEL_SCOUT_8966 = 8966; public static final int CARLA_8967 = 8967; public static final int CLERK_8968 = 8968; public static final int HEAD_MOURNER = 8969; public static final int MOURNER_8970 = 8970; public static final int MOURNER_8971 = 8971; public static final int MOURNER_8972 = 8972; public static final int RECRUITER_8973 = 8973; public static final int JETHICK_8974 = 8974; public static final int MOURNER_8975 = 8975; public static final int KOFTIK_8976 = 8976; public static final int BLESSED_SPIDER_8978 = 8978; public static final int SLAVE_8979 = 8979; public static final int SLAVE_8980 = 8980; public static final int SLAVE_8981 = 8981; public static final int SLAVE_8982 = 8982; public static final int SLAVE_8983 = 8983; public static final int SLAVE_8984 = 8984; public static final int SLAVE_8985 = 8985; public static final int UNICORN_8986 = 8986; public static final int SIR_JERRO = 8987; public static final int SIR_CARL = 8988; public static final int SIR_HARRY = 8989; public static final int HALFSOULLESS = 8990; public static final int KARDIA = 8991; public static final int WITCHS_CAT = 8992; public static final int KALRAG = 8993; public static final int OTHAINIAN = 8994; public static final int DOOMION = 8995; public static final int HOLTHION = 8996; public static final int DISCIPLE_OF_IBAN = 8997; public static final int IBAN = 8998; public static final int MOURNER_8999 = 8999; public static final int MOURNER_9000 = 9000; public static final int KILRON_9001 = 9001; public static final int OMART_9002 = 9002; public static final int MOURNER_9003 = 9003; public static final int MOURNER_9004 = 9004; public static final int KING_LATHAS_9005 = 9005; public static final int KING_THOROS = 9006; public static final int MOURNER_9007 = 9007; public static final int MOURNER_9008 = 9008; public static final int MOURNER_9009 = 9009; public static final int MOURNER_9010 = 9010; public static final int KING_THOROS_9011 = 9011; public static final int MOURNER_9013 = 9013; public static final int ARIANWYN_9014 = 9014; public static final int KELYN_9015 = 9015; public static final int ESSYLLT_9016 = 9016; public static final int MOURNER_9017 = 9017; public static final int MOURNER_9018 = 9018; public static final int ED = 9019; public static final int BRYN = 9020; public static final int CRYSTALLINE_HUNLLEF = 9021; public static final int CRYSTALLINE_HUNLLEF_9022 = 9022; public static final int CRYSTALLINE_HUNLLEF_9023 = 9023; public static final int CRYSTALLINE_HUNLLEF_9024 = 9024; public static final int CRYSTALLINE_RAT = 9026; public static final int CRYSTALLINE_SPIDER = 9027; public static final int CRYSTALLINE_BAT = 9028; public static final int CRYSTALLINE_UNICORN = 9029; public static final int CRYSTALLINE_SCORPION = 9030; public static final int CRYSTALLINE_WOLF = 9031; public static final int CRYSTALLINE_BEAR = 9032; public static final int CRYSTALLINE_DRAGON = 9033; public static final int CRYSTALLINE_DARK_BEAST = 9034; public static final int CORRUPTED_HUNLLEF = 9035; public static final int CORRUPTED_HUNLLEF_9036 = 9036; public static final int CORRUPTED_HUNLLEF_9037 = 9037; public static final int CORRUPTED_HUNLLEF_9038 = 9038; public static final int CORRUPTED_RAT = 9040; public static final int CORRUPTED_SPIDER = 9041; public static final int CORRUPTED_BAT = 9042; public static final int CORRUPTED_UNICORN = 9043; public static final int CORRUPTED_SCORPION = 9044; public static final int CORRUPTED_WOLF = 9045; public static final int CORRUPTED_BEAR = 9046; public static final int CORRUPTED_DRAGON = 9047; public static final int CORRUPTED_DARK_BEAST = 9048; public static final int ZALCANO = 9049; public static final int ZALCANO_9050 = 9050; public static final int GOLEM_9051 = 9051; public static final int RHIANNON = 9052; public static final int AMROD = 9053; public static final int MIRIEL = 9054; public static final int CURUFIN = 9055; public static final int ENERDHIL = 9056; public static final int TATIE = 9057; public static final int FINDUILAS = 9058; public static final int GELMIR = 9059; public static final int MITHRELLAS = 9060; public static final int ERESTOR = 9061; public static final int LINDIR = 9062; public static final int IDRIL = 9063; public static final int INGWION = 9064; public static final int THINGOL = 9065; public static final int ELENWE = 9066; public static final int OROPHIN = 9067; public static final int VAIRE = 9068; public static final int ELLADAN = 9069; public static final int GUILIN = 9070; public static final int INGWE = 9071; public static final int CIRDAN = 9072; public static final int GLORFINDEL = 9073; public static final int AREDHEL = 9074; public static final int CELEGORM = 9075; public static final int ANAIRE = 9076; public static final int MAEGLIN = 9077; public static final int EDRAHIL = 9078; public static final int FINGON = 9079; public static final int SALGANT = 9080; public static final int CELEBRIAN = 9081; public static final int IMIN = 9082; public static final int OROPHER = 9083; public static final int FINGOLFIN = 9084; public static final int MAHTAN = 9085; public static final int INDIS = 9086; public static final int IMINYE = 9087; public static final int FEANOR = 9088; public static final int SAEROS = 9089; public static final int NELLAS = 9090; public static final int RHYFEL = 9091; public static final int GWYL = 9092; public static final int ENILLY = 9093; public static final int FFONI = 9094; public static final int YMLADD = 9095; public static final int SADWRN = 9096; public static final int DIOL = 9097; public static final int YSBEID = 9098; public static final int CLEDDYF = 9099; public static final int SAETH = 9100; public static final int NIMRODEL = 9101; public static final int MAEDHROS = 9102; public static final int FINARFIN = 9103; public static final int GWINDOR = 9104; public static final int ELDALOTE = 9105; public static final int ENELYE = 9106; public static final int NERDANEL = 9107; public static final int NIMLOTH = 9108; public static final int FINDIS = 9109; public static final int EARWEN = 9110; public static final int CARANTHIR = 9111; public static final int ENEL = 9112; public static final int HENDOR_9113 = 9113; public static final int GALATHIL = 9114; public static final int TURGON = 9115; public static final int LENWE = 9116; public static final int ARANWE = 9117; public static final int RABBIT_9118 = 9118; public static final int LORD_IEUAN_AMLODD_9119 = 9119; public static final int LORD_BAXTORIAN_CADARN = 9120; public static final int LADY_KELYN_ITHELL_9121 = 9121; public static final int LADY_TANGWEN_TRAHAEARN_9122 = 9122; public static final int LORD_PIQUAN_CRWYS_9123 = 9123; public static final int LADY_FFION_MEILYR_9124 = 9124; public static final int LADY_CARYS_HEFIN_9125 = 9125; public static final int LORD_IESTIN_IORWERTH = 9126; public static final int BANKER_9127 = 9127; public static final int BANKER_9128 = 9128; public static final int BANKER_9129 = 9129; public static final int BANKER_9130 = 9130; public static final int BANKER_9131 = 9131; public static final int BANKER_9132 = 9132; public static final int REESE = 9133; public static final int REESE_9134 = 9134; public static final int CONWENNA = 9135; public static final int CONWENNA_9136 = 9136; public static final int ALWYN = 9137; public static final int OSWALLT = 9138; public static final int EIRA = 9139; public static final int SAWMILL_OPERATOR_9140 = 9140; public static final int PENNANT = 9141; public static final int PENNANT_9142 = 9142; public static final int GLADIATOR = 9143; public static final int GLADIATOR_9144 = 9144; public static final int ELUNED_9145 = 9145; public static final int ISLWYN_9146 = 9146; public static final int ELENA_9148 = 9148; public static final int MORVRAN_9149 = 9149; public static final int LILIFANG = 9150; public static final int CREFYDD = 9151; public static final int YSTWYTH = 9152; public static final int IWAN = 9153; public static final int DERWEN_9154 = 9154; public static final int ELGAN = 9155; public static final int CELYN = 9156; public static final int ANEIRIN = 9157; public static final int GWALLTER = 9158; public static final int GWYN = 9159; public static final int OSIAN = 9160; public static final int CAERWYN = 9161; public static final int ANWEN = 9162; public static final int GLENDA = 9163; public static final int GUINEVERE = 9164; public static final int NIA = 9165; public static final int SIAN = 9166; public static final int BRANWEN = 9167; public static final int LLIO = 9168; public static final int EFA = 9169; public static final int LLIANN = 9170; public static final int FISHING_SPOT_9171 = 9171; public static final int FISHING_SPOT_9172 = 9172; public static final int FISHING_SPOT_9173 = 9173; public static final int FISHING_SPOT_9174 = 9174; public static final int RHODDWR_TAN = 9175; public static final int MEDDWL_YMLAEN_LLAW = 9176; public static final int LLEIDR_GOLAU = 9177; public static final int GWERIN_HAPUS = 9178; public static final int PRESWYLWYR_DALL = 9179; public static final int MARWOLAETH_DAWNSIO = 9180; public static final int DIRE_WOLF_9181 = 9181; public static final int GUARD_9182 = 9182; public static final int GUARD_9183 = 9183; public static final int GUARD_9184 = 9184; public static final int GUARD_9185 = 9185; public static final int GUARD_9186 = 9186; public static final int GUARD_9187 = 9187; public static final int GUARD_9188 = 9188; public static final int GUARD_9189 = 9189; public static final int GUARD_9190 = 9190; public static final int GUARD_9191 = 9191; public static final int RAVEN = 9192; public static final int LENNY = 9193; public static final int GHOST_9194 = 9194; public static final int FLOKI = 9195; public static final int SURMA = 9196; public static final int SLIPPERS = 9197; public static final int RED_PANDA = 9198; public static final int BEAR_CUB_9199 = 9199; public static final int ED_9200 = 9200; public static final int CRAB_9201 = 9201; public static final int TIDE = 9202; public static final int ADVENTURER_JON_9244 = 9244; public static final int ARIANWYN_HARD = 9246; public static final int ESSYLLT_HARD = 9247; public static final int ARIANWYN_9248 = 9248; public static final int ESSYLLT_9249 = 9249; public static final int CAPTAIN_BARNABY_9250 = 9250; public static final int TOY_SOLDIER_9251 = 9251; public static final int TOY_DOLL = 9252; public static final int TOY_DOLL_9253 = 9253; public static final int TOY_MOUSE = 9254; public static final int TOY_MOUSE_9255 = 9255; public static final int PENGUIN_SUIT_9257 = 9257; public static final int BASILISK_SENTINEL = 9258; public static final int OSPAK_9259 = 9259; public static final int STYRMIR_9260 = 9260; public static final int TORBRUND_9261 = 9261; public static final int FRIDGEIR_9262 = 9262; public static final int BRUNDT_THE_CHIEFTAIN_9263 = 9263; public static final int THORA_THE_BARKEEP_9264 = 9264; public static final int BRUNDT_THE_CHIEFTAIN_9265 = 9265; public static final int BRUNDT_THE_CHIEFTAIN_9266 = 9266; public static final int BRUNDT_THE_CHIEFTAIN_9267 = 9267; public static final int BRUNDT_THE_CHIEFTAIN_9268 = 9268; public static final int HASKELL = 9270; public static final int HASKELL_9271 = 9271; public static final int HASKELL_9272 = 9272; public static final int AGNAR_9273 = 9273; public static final int OLAF_THE_BARD_9274 = 9274; public static final int MANNI_THE_REVELLER_9275 = 9275; public static final int FREMENNIK_WARRIOR = 9276; public static final int FREMENNIK_WARRIOR_9277 = 9277; public static final int BRUNDT_THE_CHIEFTAIN_9278 = 9278; public static final int BRUNDT_THE_CHIEFTAIN_9279 = 9279; public static final int THORVALD_THE_WARRIOR_9280 = 9280; public static final int KOSCHEI_THE_DEATHLESS_9281 = 9281; public static final int BASILISK_YOUNGLING = 9282; public static final int BASILISK_9283 = 9283; public static final int BASILISK_9284 = 9284; public static final int BASILISK_9285 = 9285; public static final int BASILISK_9286 = 9286; public static final int MONSTROUS_BASILISK_9287 = 9287; public static final int MONSTROUS_BASILISK_9288 = 9288; public static final int THE_JORMUNGAND = 9289; public static final int THE_JORMUNGAND_9290 = 9290; public static final int THE_JORMUNGAND_9291 = 9291; public static final int THE_JORMUNGAND_9292 = 9292; public static final int BASILISK_KNIGHT = 9293; public static final int BAKUNA = 9294; public static final int TYPHOR = 9295; public static final int TYPHOR_9296 = 9296; public static final int VRITRA = 9297; public static final int MAZ = 9298; public static final int TRADER_STAN = 9299; public static final int TRADER_STAN_9300 = 9300; public static final int TRADER_STAN_9301 = 9301; public static final int TRADER_STAN_9302 = 9302; public static final int TRADER_STAN_9303 = 9303; public static final int TRADER_STAN_9304 = 9304; public static final int TRADER_STAN_9305 = 9305; public static final int LOKAR_SEARUNNER_9306 = 9306; public static final int TRADER_STAN_9307 = 9307; public static final int TRADER_STAN_9308 = 9308; public static final int TRADER_STAN_9309 = 9309; public static final int TRADER_STAN_9310 = 9310; public static final int TRADER_STAN_9311 = 9311; public static final int TRADER_CREWMEMBER = 9312; public static final int TRADER_CREWMEMBER_9313 = 9313; public static final int TRADER_CREWMEMBER_9314 = 9314; public static final int TRADER_CREWMEMBER_9315 = 9315; public static final int TRADER_CREWMEMBER_9316 = 9316; public static final int TRADER_CREWMEMBER_9317 = 9317; public static final int TRADER_CREWMEMBER_9318 = 9318; public static final int TRADER_CREWMEMBER_9319 = 9319; public static final int TRADER_CREWMEMBER_9320 = 9320; public static final int TRADER_CREWMEMBER_9321 = 9321; public static final int TRADER_CREWMEMBER_9322 = 9322; public static final int TRADER_CREWMEMBER_9323 = 9323; public static final int TRADER_CREWMEMBER_9324 = 9324; public static final int TRADER_CREWMEMBER_9325 = 9325; public static final int TRADER_CREWMEMBER_9326 = 9326; public static final int TRADER_CREWMEMBER_9327 = 9327; public static final int TRADER_CREWMEMBER_9328 = 9328; public static final int TRADER_CREWMEMBER_9329 = 9329; public static final int TRADER_CREWMEMBER_9330 = 9330; public static final int TRADER_CREWMEMBER_9331 = 9331; public static final int TRADER_CREWMEMBER_9332 = 9332; public static final int TRADER_CREWMEMBER_9333 = 9333; public static final int TRADER_CREWMEMBER_9334 = 9334; public static final int TRADER_CREWMEMBER_9335 = 9335; public static final int TRADER_CREWMEMBER_9336 = 9336; public static final int TRADER_CREWMEMBER_9337 = 9337; public static final int TRADER_CREWMEMBER_9338 = 9338; public static final int TRADER_CREWMEMBER_9339 = 9339; public static final int TRADER_CREWMEMBER_9340 = 9340; public static final int TRADER_CREWMEMBER_9341 = 9341; public static final int TRADER_CREWMEMBER_9342 = 9342; public static final int TRADER_CREWMEMBER_9343 = 9343; public static final int TRADER_CREWMEMBER_9344 = 9344; public static final int TRADER_CREWMEMBER_9345 = 9345; public static final int TRADER_CREWMEMBER_9346 = 9346; public static final int TRADER_CREWMEMBER_9347 = 9347; public static final int TRADER_CREWMEMBER_9348 = 9348; public static final int TRADER_CREWMEMBER_9349 = 9349; public static final int TRADER_CREWMEMBER_9350 = 9350; public static final int TRADER_CREWMEMBER_9351 = 9351; public static final int TRADER_CREWMEMBER_9352 = 9352; public static final int TRADER_CREWMEMBER_9353 = 9353; public static final int TRADER_CREWMEMBER_9354 = 9354; public static final int TRADER_CREWMEMBER_9355 = 9355; public static final int TRADER_CREWMEMBER_9356 = 9356; public static final int TRADER_CREWMEMBER_9357 = 9357; public static final int TRADER_CREWMEMBER_9358 = 9358; public static final int TRADER_CREWMEMBER_9359 = 9359; public static final int TRADER_CREWMEMBER_9360 = 9360; public static final int TRADER_CREWMEMBER_9361 = 9361; public static final int TRADER_CREWMEMBER_9362 = 9362; public static final int TRADER_CREWMEMBER_9363 = 9363; public static final int TRADER_CREWMEMBER_9364 = 9364; public static final int TRADER_CREWMEMBER_9365 = 9365; public static final int TRADER_CREWMEMBER_9366 = 9366; public static final int TRADER_CREWMEMBER_9367 = 9367; public static final int TRADER_CREWMEMBER_9368 = 9368; public static final int TRADER_CREWMEMBER_9369 = 9369; public static final int TRADER_CREWMEMBER_9370 = 9370; public static final int TRADER_CREWMEMBER_9371 = 9371; public static final int TRADER_CREWMEMBER_9372 = 9372; public static final int TRADER_CREWMEMBER_9373 = 9373; public static final int TRADER_CREWMEMBER_9374 = 9374; public static final int TRADER_CREWMEMBER_9375 = 9375; public static final int TRADER_CREWMEMBER_9376 = 9376; public static final int TRADER_CREWMEMBER_9377 = 9377; public static final int TRADER_CREWMEMBER_9378 = 9378; public static final int TRADER_CREWMEMBER_9379 = 9379; public static final int TRADER_CREWMEMBER_9380 = 9380; public static final int TRADER_CREWMEMBER_9381 = 9381; public static final int TRADER_CREWMEMBER_9382 = 9382; public static final int TRADER_CREWMEMBER_9383 = 9383; public static final int LITTLE_NIGHTMARE = 9398; public static final int LITTLE_NIGHTMARE_9399 = 9399; public static final int OATH_LORD_DROWS = 9400; public static final int OATHBREAKER_MALS = 9401; public static final int OATHBREAKER_EPIWS = 9402; public static final int OATHBREAKER_BATS = 9403; public static final int LITHIL = 9404; public static final int SISTER_ASERET = 9405; public static final int SISTER_NAOJ = 9406; public static final int SISTER_SALOHCIN = 9407; public static final int LUMIERE = 9408; public static final int DAER_KRAND = 9409; public static final int STRONG_RONNY = 9410; public static final int SHURA = 9413; public static final int SHURA_9414 = 9414; public static final int ACORN = 9415; public static final int PHOSANIS_NIGHTMARE_9416 = 9416; public static final int PHOSANIS_NIGHTMARE_9417 = 9417; public static final int PHOSANIS_NIGHTMARE_9418 = 9418; public static final int PHOSANIS_NIGHTMARE_9419 = 9419; public static final int PHOSANIS_NIGHTMARE_9420 = 9420; public static final int PHOSANIS_NIGHTMARE_9421 = 9421; public static final int PHOSANIS_NIGHTMARE_9422 = 9422; public static final int PHOSANIS_NIGHTMARE_9423 = 9423; public static final int PHOSANIS_NIGHTMARE_9424 = 9424; public static final int THE_NIGHTMARE_9425 = 9425; public static final int THE_NIGHTMARE_9426 = 9426; public static final int THE_NIGHTMARE_9427 = 9427; public static final int THE_NIGHTMARE_9428 = 9428; public static final int THE_NIGHTMARE_9429 = 9429; public static final int THE_NIGHTMARE_9430 = 9430; public static final int THE_NIGHTMARE_9431 = 9431; public static final int THE_NIGHTMARE_9432 = 9432; public static final int THE_NIGHTMARE_9433 = 9433; public static final int TOTEM = 9434; public static final int TOTEM_9435 = 9435; public static final int TOTEM_9436 = 9436; public static final int TOTEM_9437 = 9437; public static final int TOTEM_9438 = 9438; public static final int TOTEM_9439 = 9439; public static final int TOTEM_9440 = 9440; public static final int TOTEM_9441 = 9441; public static final int TOTEM_9442 = 9442; public static final int TOTEM_9443 = 9443; public static final int TOTEM_9444 = 9444; public static final int TOTEM_9445 = 9445; public static final int SLEEPWALKER_9446 = 9446; public static final int SLEEPWALKER_9447 = 9447; public static final int SLEEPWALKER_9448 = 9448; public static final int SLEEPWALKER_9449 = 9449; public static final int SLEEPWALKER_9450 = 9450; public static final int SLEEPWALKER_9451 = 9451; public static final int PARASITE = 9452; public static final int PARASITE_9453 = 9453; public static final int HUSK = 9454; public static final int HUSK_9455 = 9455; public static final int THE_NIGHTMARE_9460 = 9460; public static final int THE_NIGHTMARE_9461 = 9461; public static final int THE_NIGHTMARE_9462 = 9462; public static final int THE_NIGHTMARE_9463 = 9463; public static final int THE_NIGHTMARE_9464 = 9464; public static final int INFERNAL_PYRELORD = 9465; public static final int HUSK_9466 = 9466; public static final int HUSK_9467 = 9467; public static final int PARASITE_9468 = 9468; public static final int PARASITE_9469 = 9469; public static final int SLEEPWALKER_9470 = 9470; public static final int SISTER_SENGA = 9471; public static final int SISTER_SENGA_9472 = 9472; public static final int ENT_TRUNK = 9474; public static final int GIELINOR_GUIDE_9476 = 9476; public static final int SURVIVAL_EXPERT_9477 = 9477; public static final int FISHING_SPOT_9478 = 9478; public static final int MASTER_NAVIGATOR = 9479; public static final int QUEST_GUIDE_9480 = 9480; public static final int MINING_INSTRUCTOR_9481 = 9481; public static final int COMBAT_INSTRUCTOR_9482 = 9482; public static final int GIANT_RAT_9483 = 9483; public static final int BANKER_9484 = 9484; public static final int BROTHER_BRACE_9485 = 9485; public static final int IRON_MAN_TUTOR_9486 = 9486; public static final int MAGIC_INSTRUCTOR_9487 = 9487; public static final int CHICKEN_9488 = 9488; public static final int VELIAF_HURTZ_9489 = 9489; public static final int HAMELN_THE_JESTER = 9490; public static final int HANCHEN_THE_HOUND = 9491; public static final int TANGLEROOT_9492 = 9492; public static final int TANGLEROOT_9493 = 9493; public static final int TANGLEROOT_9494 = 9494; public static final int TANGLEROOT_9495 = 9495; public static final int TANGLEROOT_9496 = 9496; public static final int TANGLEROOT_9497 = 9497; public static final int TANGLEROOT_9498 = 9498; public static final int TANGLEROOT_9499 = 9499; public static final int TANGLEROOT_9500 = 9500; public static final int TANGLEROOT_9501 = 9501; public static final int IORWERTH_WARRIOR_9502 = 9502; public static final int IORWERTH_WARRIOR_9503 = 9503; public static final int ACCOUNT_SECURITY_TUTOR = 9504; public static final int HAMELN_THE_JESTER_9505 = 9505; public static final int HANCHEN_THE_HOUND_9506 = 9506; public static final int ENRAGED_TEKTINY = 9511; public static final int FLYING_VESPINA = 9512; public static final int ENRAGED_TEKTINY_9513 = 9513; public static final int FLYING_VESPINA_9514 = 9514; public static final int VELIAF_HURTZ_9521 = 9521; public static final int VELIAF_HURTZ_9522 = 9522; public static final int VELIAF_HURTZ_9523 = 9523; public static final int VELIAF_HURTZ_9524 = 9524; public static final int VELIAF_HURTZ_9525 = 9525; public static final int VELIAF_HURTZ_9526 = 9526; public static final int VELIAF_HURTZ_9527 = 9527; public static final int VELIAF_HURTZ_9528 = 9528; public static final int VELIAF_HURTZ_9529 = 9529; public static final int IVAN_STROM_9530 = 9530; public static final int IVAN_STROM_9531 = 9531; public static final int IVAN_STROM_9532 = 9532; public static final int IVAN_STROM_9533 = 9533; public static final int IVAN_STROM_9534 = 9534; public static final int IVAN_STROM_9535 = 9535; public static final int IVAN_STROM_9536 = 9536; public static final int SAFALAAN_HALLOW_9537 = 9537; public static final int SAFALAAN_HALLOW_9538 = 9538; public static final int SAFALAAN_HALLOW_9539 = 9539; public static final int SAFALAAN_HALLOW_9540 = 9540; public static final int SAFALAAN_HALLOW_9541 = 9541; public static final int SAFALAAN_HALLOW_9542 = 9542; public static final int KAEL_FORSHAW_9543 = 9543; public static final int KAEL_FORSHAW_9544 = 9544; public static final int KAEL_FORSHAW_9545 = 9545; public static final int KAEL_FORSHAW_9546 = 9546; public static final int VERTIDA_SEFALATIS_9547 = 9547; public static final int VERTIDA_SEFALATIS_9548 = 9548; public static final int VERTIDA_SEFALATIS_9549 = 9549; public static final int VERTIDA_SEFALATIS_9550 = 9550; public static final int RADIGAD_PONFIT_9551 = 9551; public static final int RADIGAD_PONFIT_9552 = 9552; public static final int RADIGAD_PONFIT_9553 = 9553; public static final int POLMAFI_FERDYGRIS_9554 = 9554; public static final int POLMAFI_FERDYGRIS_9555 = 9555; public static final int POLMAFI_FERDYGRIS_9556 = 9556; public static final int CARL = 9557; public static final int CARL_9558 = 9558; public static final int KROY = 9559; public static final int KROY_9560 = 9560; public static final int DAMIEN_LEUCURTE = 9561; public static final int DAMIEN_LEUCURTE_9562 = 9562; public static final int DAMIEN_LEUCURTE_9563 = 9563; public static final int DAMIEN_LEUCURTE_9564 = 9564; public static final int LORD_CROMBWICK = 9565; public static final int VANSTROM_KLAUSE_9566 = 9566; public static final int VANSTROM_KLAUSE_9567 = 9567; public static final int VANSTROM_KLAUSE_9568 = 9568; public static final int VANSTROM_KLAUSE_9569 = 9569; public static final int VANSTROM_KLAUSE_9570 = 9570; public static final int VANSTROM_KLAUSE_9571 = 9571; public static final int MIST_9572 = 9572; public static final int ACIDIC_BLOODVELD = 9573; public static final int VANESCULA_DRAKAN_9574 = 9574; public static final int VANESCULA_DRAKAN_9575 = 9575; public static final int VANESCULA_DRAKAN_9576 = 9576; public static final int VANESCULA_DRAKAN_9577 = 9577; public static final int LORD_ALEXEI_JOVKAI = 9578; public static final int LOWERNIEL_DRAKAN = 9579; public static final int WEREWOLF_9580 = 9580; public static final int WEREWOLF_9581 = 9581; public static final int WEREWOLF_9582 = 9582; public static final int PRISONER = 9583; public static final int PRISONER_9584 = 9584; public static final int PRISONER_9585 = 9585; public static final int VAMPYRE_JUVINATE_9586 = 9586; public static final int VAMPYRE_JUVINATE_9587 = 9587; public static final int DESMODUS_LASIURUS = 9588; public static final int MORDAN_NIKAZSI = 9589; public static final int VYREWATCH_9590 = 9590; public static final int VYREWATCH_9591 = 9591; public static final int PRISONER_9592 = 9592; public static final int PRISONER_9593 = 9593; public static final int MARIA_GADDERANKS = 9594; public static final int MARIA_GADDERANKS_9595 = 9595; public static final int RON_GADDERANKS = 9596; public static final int RON_GADDERANKS_9597 = 9597; public static final int SARIUS_GUILE_9598 = 9598; public static final int VYREWATCH_SENTINEL = 9599; public static final int VYREWATCH_SENTINEL_9600 = 9600; public static final int VYREWATCH_SENTINEL_9601 = 9601; public static final int VYREWATCH_SENTINEL_9602 = 9602; public static final int VYREWATCH_SENTINEL_9603 = 9603; public static final int VYREWATCH_SENTINEL_9604 = 9604; public static final int VYREWATCH_9605 = 9605; public static final int VYREWATCH_9606 = 9606; public static final int VYREWATCH_9607 = 9607; public static final int VYREWATCH_9608 = 9608; public static final int SEAGULL_9609 = 9609; public static final int MUTATED_BLOODVELD_9610 = 9610; public static final int MUTATED_BLOODVELD_9611 = 9611; public static final int NAIL_BEAST_9612 = 9612; public static final int NAIL_BEAST_9613 = 9613; public static final int VAMPYRE_JUVINATE_9614 = 9614; public static final int VAMPYRE_JUVINATE_9615 = 9615; public static final int VAMPYRE_JUVINATE_9616 = 9616; public static final int VAMPYRE_JUVINATE_9617 = 9617; public static final int CURPILE_FYOD = 9619; public static final int VELIAF_HURTZ_9621 = 9621; public static final int SANI_PILIU = 9622; public static final int SANI_PILIU_9623 = 9623; public static final int HAROLD_EVANS = 9624; public static final int HAROLD_EVANS_9625 = 9625; public static final int RADIGAD_PONFIT_9627 = 9627; public static final int POLMAFI_FERDYGRIS_9629 = 9629; public static final int IVAN_STROM_9631 = 9631; public static final int VANSTROM_KLAUSE_9632 = 9632; public static final int VELIAF_HURTZ_9633 = 9633; public static final int WISKIT_9634 = 9634; public static final int GADDERANKS_9635 = 9635; public static final int DREZEL = 9636; public static final int DARK_SQUIRREL = 9637; public static final int DARK_SQUIRREL_9638 = 9638; public static final int MYSTERIOUS_STRANGER_9639 = 9639; public static final int MYSTERIOUS_STRANGER_9640 = 9640; public static final int BAT_9641 = 9641; public static final int BAT_9642 = 9642; public static final int SPIDER_9643 = 9643; public static final int SPIDER_9644 = 9644; public static final int FISH_9645 = 9645; public static final int FISH_9646 = 9646; public static final int KNIGHT_OF_THE_OWL = 9648; public static final int KNIGHT_OF_THE_UNICORN = 9650; public static final int KNIGHT_OF_THE_WOLF = 9652; public static final int KNIGHT_OF_THE_LION = 9654; public static final int ARCHPRIEST_OF_THE_UNICORN = 9656; public static final int DARKMEYER_SLAVE = 9657; public static final int DARKMEYER_SLAVE_9658 = 9658; public static final int MAD_MELVIN96 = 9659; public static final int R2T2PNSH0TY = 9660; public static final int JYN = 9661; public static final int C4SSI4N = 9662; public static final int FISHRUNNER82 = 9663; public static final int WEAST_SIDE49 = 9664; public static final int C0LECT0R890 = 9665; public static final int GIANT_SQUIRREL_9666 = 9666; public static final int OWL = 9667; public static final int OWL_9668 = 9668; public static final int NORANNA_TYTANIN = 9675; public static final int NORANNA_TYTANIN_9676 = 9676; public static final int SLAVE_9677 = 9677; public static final int SLAVE_9678 = 9678; public static final int SLAVE_9679 = 9679; public static final int SLAVE_9680 = 9680; public static final int SLAVE_9681 = 9681; public static final int SLAVE_9682 = 9682; public static final int VAMPYRE_JUVINATE_9683 = 9683; public static final int VAMPYRE_JUVINATE_9684 = 9684; public static final int VALENTIN_RASPUTIN = 9685; public static final int VON_VAN_VON = 9686; public static final int VLAD_BECHSTEIN = 9687; public static final int DRACONIS_SANGUINE = 9688; public static final int MORT_NIGHTSHADE = 9689; public static final int VAMPYRUS_DIAEMUS = 9690; public static final int CARNIVUS_BELAMORTA = 9691; public static final int VORMAR_VAKAN = 9692; public static final int MISDRIEVUS_SHADUM = 9693; public static final int VLAD_DIAEMUS = 9694; public static final int NOCTILLION_LUGOSI = 9695; public static final int ALEK_CONSTANTINE = 9696; public static final int GRIGOR_RASPUTIN = 9697; public static final int HAEMAS_LAMESCUS = 9698; public static final int REMUS_KANINUS = 9699; public static final int VALLESSIA_DRACYULA = 9700; public static final int VIOLETTA_SANGUINE = 9701; public static final int DIPHYLLA_BECHSTEIN = 9702; public static final int EPISCULA_HELSING = 9703; public static final int VAMPYRESSA_VAN_VON = 9704; public static final int VALLESSIA_VON_PITT = 9705; public static final int VONNETTA_VARNIS = 9706; public static final int NATALIDAE_SHADUM = 9707; public static final int MORTINA_DAUBENTON = 9708; public static final int LASENNA_RASPUTIN = 9709; public static final int CANINELLE_DRAYNAR = 9710; public static final int VALENTINA_DIAEMUS = 9711; public static final int NAKASA_JOVKAI = 9712; public static final int CRIMSONETTE_VAN_MARR = 9713; public static final int PIPISTRELLE_DRAYNAR = 9714; public static final int LADY_NADEZHDA_SHADUM = 9715; public static final int LORD_MISCHA_MYRMEL = 9716; public static final int LORD_ALEXEI_JOVKAI_9717 = 9717; public static final int BANKER_9718 = 9718; public static final int BANKER_9719 = 9719; public static final int GRINKA_KRAST = 9720; public static final int DRASDAN_RANOR = 9721; public static final int DESPOINA_CALLIDRA = 9722; public static final int LENYIG_KARNA = 9723; public static final int VARRIAN_SOBAK = 9724; public static final int SLAVE_9725 = 9725; public static final int SLAVE_9726 = 9726; public static final int VAMPYRE_JUVINATE_9727 = 9727; public static final int VAMPYRE_JUVINATE_9728 = 9728; public static final int VAMPYRE_JUVINATE_9729 = 9729; public static final int VAMPYRE_JUVINATE_9730 = 9730; public static final int VAMPYRE_JUVENILE_9731 = 9731; public static final int VAMPYRE_JUVENILE_9732 = 9732; public static final int VAMPYRE_JUVENILE_9733 = 9733; public static final int VAMPYRE_JUVENILE_9734 = 9734; public static final int VYREWATCH_9735 = 9735; public static final int VYREWATCH_9736 = 9736; public static final int VYREWATCH_9737 = 9737; public static final int VYREWATCH_9738 = 9738; public static final int VYREWATCH_9739 = 9739; public static final int VYREWATCH_9740 = 9740; public static final int VYREWATCH_9741 = 9741; public static final int VYREWATCH_9742 = 9742; public static final int WEREWOLF_9743 = 9743; public static final int WEREWOLF_9744 = 9744; public static final int WEREWOLF_9745 = 9745; public static final int AUCTIONEER = 9746; public static final int FRANK_9749 = 9749; public static final int SPECTATOR = 9750; public static final int SPECTATOR_9751 = 9751; public static final int SPECTATOR_9752 = 9752; public static final int SPECTATOR_9753 = 9753; public static final int SPECTATOR_9754 = 9754; public static final int SPECTATOR_9755 = 9755; public static final int VYREWATCH_SENTINEL_9756 = 9756; public static final int VYREWATCH_SENTINEL_9757 = 9757; public static final int VYREWATCH_SENTINEL_9758 = 9758; public static final int VYREWATCH_SENTINEL_9759 = 9759; public static final int VYREWATCH_SENTINEL_9760 = 9760; public static final int VYREWATCH_SENTINEL_9761 = 9761; public static final int VYREWATCH_SENTINEL_9762 = 9762; public static final int VYREWATCH_SENTINEL_9763 = 9763; public static final int YENRAB_9764 = 9764; public static final int LAHSRAM_9765 = 9765; public static final int ERODOEHT_9766 = 9766; public static final int CARL_9767 = 9767; public static final int ROY = 9768; public static final int LECTOR_GURA_9769 = 9769; public static final int SISTER_SEVI_9770 = 9770; public static final int SISTER_TOEN_9771 = 9771; public static final int SISTER_YRAM_9772 = 9772; public static final int KROY_9773 = 9773; public static final int DAMIEN_LEUCURTE_9774 = 9774; public static final int LORD_CROMBWICK_9775 = 9775; public static final int PAINTED_ONE = 9776; public static final int PAINTED_ONE_9777 = 9777; public static final int KURT = 9778; public static final int DON = 9779; public static final int DEBRA = 9780; public static final int TANYA_9781 = 9781; public static final int KURT_9782 = 9782; public static final int DON_9783 = 9783; public static final int DEBRA_9784 = 9784; public static final int TANYA_9785 = 9785; public static final int CHILD_9786 = 9786; public static final int CHILD_9787 = 9787; public static final int CHILD_9788 = 9788; public static final int CHILD_9789 = 9789; public static final int CHILD_9790 = 9790; public static final int CHILD_9791 = 9791; public static final int CHILD_9792 = 9792; public static final int CHILD_9793 = 9793; public static final int CHILD_9794 = 9794; public static final int CHILD_9795 = 9795; public static final int CHILD_9796 = 9796; public static final int CHILD_9797 = 9797; public static final int CHILD_9798 = 9798; public static final int CHILD_9799 = 9799; public static final int SLEEPWALKER_9801 = 9801; public static final int SLEEPWALKER_9802 = 9802; public static final int RED = 9850; public static final int ZIGGY = 9851; public static final int RED_9852 = 9852; public static final int ZIGGY_9853 = 9853; public static final int DEATH_9855 = 9855; public static final int GRAVE = 9856; public static final int GRAVE_9857 = 9857; public static final int SQUIRE_10368 = 10368; public static final int BOBAWU = 10369; public static final int MARTEN = 10370; public static final int WIZARD_10371 = 10371; public static final int WIZARD_10372 = 10372; public static final int WIZARD_10373 = 10373; public static final int HILL_GIANT_10374 = 10374; public static final int HILL_GIANT_10375 = 10375; public static final int HILL_GIANT_10376 = 10376; public static final int FEROX = 10377; public static final int SIGISMUND = 10378; public static final int ZAMORAKIAN_ACOLYTE = 10379; public static final int ZAMORAKIAN_ACOLYTE_10380 = 10380; public static final int ZAMORAKIAN_ACOLYTE_10381 = 10381; public static final int SKULLY = 10382; public static final int REFUGEE = 10383; public static final int REFUGEE_10384 = 10384; public static final int REFUGEE_10385 = 10385; public static final int PHABELLE_BILE = 10386; public static final int DERSE_VENATOR = 10387; public static final int ANDROS_MAI = 10388; public static final int BANKER_10389 = 10389; public static final int MERCENARY_10390 = 10390; public static final int FINANCIAL_WIZARD_10391 = 10391; public static final int CAMARST = 10392; public static final int WARRIOR_OF_MURAHS = 10393; public static final int WARRIOR_OF_MURAHS_10394 = 10394; public static final int WARRIOR_OF_MURAHS_10395 = 10395; public static final int SPIKED_TUROTH = 10397; public static final int SHADOW_WYRM = 10398; public static final int SHADOW_WYRM_10399 = 10399; public static final int GUARDIAN_DRAKE = 10400; public static final int GUARDIAN_DRAKE_10401 = 10401; public static final int COLOSSAL_HYDRA = 10402; public static final int TORFINN_10403 = 10403; public static final int TORFINN_10404 = 10404; public static final int TORFINN_10405 = 10405; public static final int TORFINN_10406 = 10406; public static final int JARVALD_10407 = 10407; public static final int MARLO = 10408; public static final int MARLO_10409 = 10409; public static final int ELLIE = 10410; public static final int ELLIE_10411 = 10411; public static final int ANGELO = 10412; public static final int ANGELO_10413 = 10413; public static final int BOB_10414 = 10414; public static final int JEFF_10415 = 10415; public static final int SARAH_10416 = 10416; public static final int TAU = 10417; public static final int LARRY_10418 = 10418; public static final int NOELLA = 10419; public static final int ROSS = 10420; public static final int JESS = 10421; public static final int MARIAH = 10422; public static final int LEELA_10423 = 10423; public static final int BARBARA = 10424; public static final int OLD_MAN_YARLO = 10425; public static final int OLD_MAN_YARLO_10426 = 10426; public static final int OLD_MAN_YARLO_10427 = 10427; public static final int SPRIA = 10432; public static final int SPRIA_10433 = 10433; public static final int SPRIA_10434 = 10434; public static final int SOURHOG = 10435; public static final int SOURHOG_10436 = 10436; public static final int PIG_THING = 10437; public static final int ROSIE_10438 = 10438; public static final int SHEEPDOG_10439 = 10439; public static final int SPIDER_10442 = 10442; public static final int SPIDER_10443 = 10443; public static final int BEES = 10444; public static final int GNORMADIUM_AVLAFRIM_10445 = 10445; public static final int GNORMADIUM_AVLAFRIM_10446 = 10446; public static final int GNORMADIUM_AVLAFRIM_10447 = 10447; public static final int GNORMADIUM_AVLAFRIM_10448 = 10448; public static final int EVE_10449 = 10449; public static final int GNORMADIUM_AVLAFRIM_10450 = 10450; public static final int GNORMADIUM_AVLAFRIM_10451 = 10451; public static final int CAPTAIN_DALBUR = 10452; public static final int CAPTAIN_DALBUR_10453 = 10453; public static final int CAPTAIN_DALBUR_10454 = 10454; public static final int CAPTAIN_DALBUR_10455 = 10455; public static final int CAPTAIN_DALBUR_10456 = 10456; public static final int CAPTAIN_DALBUR_10457 = 10457; public static final int CAPTAIN_DALBUR_10458 = 10458; public static final int CAPTAIN_BLEEMADGE = 10459; public static final int JACKOLANTERN = 10460; public static final int CAPTAIN_BLEEMADGE_10461 = 10461; public static final int CAPTAIN_BLEEMADGE_10462 = 10462; public static final int CAPTAIN_BLEEMADGE_10463 = 10463; public static final int CAPTAIN_BLEEMADGE_10464 = 10464; public static final int CAPTAIN_BLEEMADGE_10465 = 10465; public static final int CAPTAIN_BLEEMADGE_10466 = 10466; public static final int CAPTAIN_ERRDO_10467 = 10467; public static final int CAPTAIN_ERRDO_10468 = 10468; public static final int CAPTAIN_ERRDO_10469 = 10469; public static final int CAPTAIN_ERRDO_10470 = 10470; public static final int CAPTAIN_ERRDO_10471 = 10471; public static final int CAPTAIN_ERRDO_10472 = 10472; public static final int CAPTAIN_ERRDO_10473 = 10473; public static final int LEAGUES_ASSISTANT = 10476; public static final int THESSALIA = 10477; public static final int THESSALIA_10478 = 10478; public static final int CAPTAIN_KLEMFOODLE = 10479; public static final int CAPTAIN_KLEMFOODLE_10480 = 10480; public static final int CAPTAIN_KLEMFOODLE_10481 = 10481; public static final int CAPTAIN_KLEMFOODLE_10482 = 10482; public static final int CAPTAIN_KLEMFOODLE_10483 = 10483; public static final int CAPTAIN_KLEMFOODLE_10484 = 10484; public static final int CAPTAIN_KLEMFOODLE_10485 = 10485; public static final int CAPTAIN_SHORACKS_10486 = 10486; public static final int CAPTAIN_SHORACKS_10487 = 10487; public static final int CAPTAIN_SHORACKS_10488 = 10488; public static final int CAPTAIN_SHORACKS_10489 = 10489; public static final int CAPTAIN_SHORACKS_10490 = 10490; public static final int CAPTAIN_SHORACKS_10491 = 10491; public static final int HEADLESS_BEAST_HARD = 10492; public static final int HEADLESS_BEAST = 10493; public static final int CHICKEN_10494 = 10494; public static final int CHICKEN_10495 = 10495; public static final int CHICKEN_10496 = 10496; public static final int CHICKEN_10497 = 10497; public static final int CHICKEN_10498 = 10498; public static final int CHICKEN_10499 = 10499; public static final int GORDON = 10500; public static final int GORDON_10501 = 10501; public static final int MARY_10502 = 10502; public static final int MARY_10503 = 10503; public static final int MARY_10504 = 10504; public static final int SERGEANT_10505 = 10505; public static final int HEADLESS_BEAST_10506 = 10506; public static final int ORNATE_UNDEAD_COMBAT_DUMMY = 10507; public static final int ORNATE_WILDERNESS_COMBAT_DUMMY = 10508; public static final int ORNATE_KALPHITE_COMBAT_DUMMY = 10509; public static final int ORNATE_KURASK_COMBAT_DUMMY = 10510; public static final int ORNATE_UNDEAD_COMBAT_DUMMY_10511 = 10511; public static final int ORNATE_UNDEAD_COMBAT_DUMMY_10512 = 10512; public static final int FISHING_SPOT_10513 = 10513; public static final int FISHING_SPOT_10514 = 10514; public static final int FISHING_SPOT_10515 = 10515; public static final int NOMAD = 10516; public static final int ZIMBERFIZZ = 10517; public static final int ZIMBERFIZZ_10518 = 10518; public static final int ZIMBERFIZZ_10519 = 10519; public static final int AVATAR_OF_CREATION = 10520; public static final int AVATAR_OF_DESTRUCTION = 10521; public static final int WOLF_10522 = 10522; public static final int FORGOTTEN_SOUL = 10523; public static final int FORGOTTEN_SOUL_10524 = 10524; public static final int FORGOTTEN_SOUL_10525 = 10525; public static final int FORGOTTEN_SOUL_10526 = 10526; public static final int NOMAD_10528 = 10528; public static final int NOMAD_10529 = 10529; public static final int ZIMBERFIZZ_10530 = 10530; public static final int AVATAR_OF_CREATION_10531 = 10531; public static final int AVATAR_OF_DESTRUCTION_10532 = 10532; public static final int WOLF_10533 = 10533; public static final int FORGOTTEN_SOUL_10534 = 10534; public static final int FORGOTTEN_SOUL_10535 = 10535; public static final int FORGOTTEN_SOUL_10536 = 10536; public static final int FORGOTTEN_SOUL_10537 = 10537; public static final int GHOST_10538 = 10538; public static final int BARRICADE_10539 = 10539; public static final int BARRICADE_10540 = 10540; public static final int BIRD_10541 = 10541; public static final int FORGOTTEN_SOUL_10544 = 10544; public static final int FORGOTTEN_SOUL_10545 = 10545; public static final int DUCK_10546 = 10546; public static final int DUCK_10547 = 10547; public static final int CHICKEN_10556 = 10556; public static final int ANCIENT_GHOST = 10557; public static final int ANCIENT_GHOST_10558 = 10558; public static final int SCRUBFOOT = 10559; public static final int GARL = 10560; public static final int RED_FIREFLIES = 10561; public static final int TINY_TEMPOR = 10562; public static final int CRAB_10563 = 10563; public static final int GREEN_FIREFLIES = 10564; public static final int FISHING_SPOT_10565 = 10565; public static final int GOBLIN_10566 = 10566; public static final int GOBLIN_10567 = 10567; public static final int FISHING_SPOT_10568 = 10568; public static final int FISHING_SPOT_10569 = 10569; public static final int INACTIVE_SPIRIT_POOL = 10570; public static final int SPIRIT_POOL = 10571; public static final int TEMPOROSS = 10572; public static final int TEMPOROSS_10574 = 10574; public static final int TEMPOROSS_10575 = 10575; public static final int AMMUNITION_CRATE = 10576; public static final int AMMUNITION_CRATE_10577 = 10577; public static final int AMMUNITION_CRATE_10578 = 10578; public static final int AMMUNITION_CRATE_10579 = 10579; public static final int LIGHTNING_CLOUD = 10580; public static final int CAPTAIN_PUDI = 10583; public static final int CAPTAIN_DUDI = 10584; public static final int CAPTAIN_PUDI_10585 = 10585; public static final int CAPTAIN_PUDI_10586 = 10586; public static final int CAPTAIN_DUDI_10587 = 10587; public static final int CAPTAIN_DUDI_10588 = 10588; public static final int URIUM_SHADE = 10589; public static final int DAMPE = 10590; public static final int UNDEAD_ZEALOT = 10591; public static final int UNDEAD_ZEALOT_10592 = 10592; public static final int FIRST_MATE_DERI = 10593; public static final int SHEEP_10594 = 10594; public static final int FIRST_MATE_DERI_10595 = 10595; public static final int FIRST_MATE_PERI = 10596; public static final int FIRST_MATE_PERI_10597 = 10597; public static final int COW_10598 = 10598; public static final int CANNONEER = 10599; public static final int CANNONEER_10600 = 10600; public static final int CANNONEER_10601 = 10601; public static final int CANNONEER_10602 = 10602; public static final int MONKEY_ON_UNICORN = 10603; public static final int SAILOR_10604 = 10604; public static final int SPIRIT_ANGLER = 10605; public static final int SPIRIT_ANGLER_10606 = 10606; public static final int SPIRIT_ANGLER_10607 = 10607; public static final int SPIRIT_ANGLER_10608 = 10608; public static final int SPIRIT_ANGLER_10609 = 10609; public static final int FERRYMAN_SATHWOOD = 10610; public static final int FERRYMAN_NATHWOOD = 10611; public static final int RETIRED_SAILOR = 10612; public static final int GITA_PRYMES = 10613; public static final int TAIMAN = 10614; public static final int KOANEE = 10615; public static final int TIMALLUS = 10616; public static final int LAURETTA = 10617; public static final int ISHMAEL = 10618; public static final int BOB_10619 = 10619; public static final int JALREKJAD = 10620; public static final int TZHAARKETRAK = 10621; public static final int TZHAARKETRAK_10622 = 10622; public static final int JALTOKJAD_10623 = 10623; public static final int YTHURKOT_10624 = 10624; public static final int JALREKJAD_10625 = 10625; public static final int SHADOW_10628 = 10628; public static final int DUSURI = 10630; public static final int DUSURI_10631 = 10631; public static final int STAR_SPRITE = 10632; public static final int SHANTAY_GUARD_10634 = 10634; public static final int FISHING_SPOT_10635 = 10635; public static final int GREAT_BLUE_HERON_10636 = 10636; public static final int TINY_TEMPOR_10637 = 10637; public static final int BABY_MOLERAT = 10650; public static final int BABY_MOLERAT_10651 = 10651; public static final int SPIDER_10652 = 10652; public static final int FISHING_SPOT_10653 = 10653; public static final int ANCIENT_GUARDIAN = 10654; public static final int WILLOW = 10655; public static final int MARLEY = 10656; public static final int CHECKAL = 10657; public static final int ATLAS = 10658; public static final int BURNTOF = 10659; public static final int BURNTOF_10660 = 10660; public static final int WILLOW_10661 = 10661; public static final int MARLEY_10662 = 10662; public static final int CHECKAL_10663 = 10663; public static final int BURNTOF_10664 = 10664; public static final int ANCIENT_GUARDIAN_10665 = 10665; public static final int RUBBLE = 10666; public static final int FUSE = 10667; public static final int TINA_10668 = 10668; public static final int ATLAS_10669 = 10669; public static final int RAMARNO = 10670; public static final int TRAMP_10671 = 10671; public static final int MAN_10672 = 10672; public static final int MAN_10673 = 10673; public static final int WOMAN_10674 = 10674; public static final int STRAY_DOG_10675 = 10675; public static final int BARBARIAN_10676 = 10676; public static final int BARBARIAN_10677 = 10677; public static final int BARBARIAN_10678 = 10678; public static final int BARBARIAN_10679 = 10679; public static final int GUARD_10680 = 10680; public static final int AUBURY = 10681; public static final int RAT_10682 = 10682; public static final int BARAEK_10683 = 10683; public static final int RAMARNO_10684 = 10684; public static final int RAMARNO_10685 = 10685; public static final int FISHING_SPOT_10686 = 10686; public static final int FISHING_SPOT_10687 = 10687; public static final int FISHING_SPOT_10688 = 10688; public static final int CHAOS_GOLEM = 10689; public static final int RUBBLE_10690 = 10690; public static final int BODY_GOLEM = 10691; public static final int RUBBLE_10692 = 10692; public static final int MIND_GOLEM = 10693; public static final int RUBBLE_10694 = 10694; public static final int FLAWED_GOLEM = 10695; public static final int RUBBLE_10696 = 10696; public static final int GHOST_10697 = 10697; public static final int GHOST_10698 = 10698; public static final int GHOST_10699 = 10699; public static final int FROG_10700 = 10700; public static final int MURPHY_10707 = 10707; public static final int ENORMOUS_TENTACLE_10708 = 10708; public static final int ENORMOUS_TENTACLE_10709 = 10709; public static final int SKELETON_10717 = 10717; public static final int SKELETON_10718 = 10718; public static final int SKELETON_10719 = 10719; public static final int SKELETON_10720 = 10720; public static final int SKELETON_10721 = 10721; public static final int ICE_SPIDER_10722 = 10722; public static final int VEOS_10723 = 10723; public static final int VEOS_10724 = 10724; public static final int SERGEANT_10725 = 10725; public static final int VEOS_10726 = 10726; public static final int VEOS_10727 = 10727; public static final int WOMAN_10728 = 10728; public static final int RANGER_10731 = 10731; public static final int ZAMORAKIAN_RECRUITER = 10732; public static final int MEREDITH = 10733; public static final int BANKER_10734 = 10734; public static final int BANKER_10735 = 10735; public static final int BANKER_10736 = 10736; public static final int BANKER_10737 = 10737; public static final int RAQUEEL = 10739; public static final int RAQUEEL_10740 = 10740; public static final int RAQUEEL_10741 = 10741; public static final int RAQUEEL_10742 = 10742; public static final int RAQUEEL_10743 = 10743; public static final int RAQUEEL_10744 = 10744; public static final int RAQUEEL_10745 = 10745; public static final int RAQUEEL_10746 = 10746; public static final int GEM = 10748; public static final int GEM_10749 = 10749; public static final int GEM_10750 = 10750; public static final int GEM_10751 = 10751; public static final int GEM_10752 = 10752; public static final int GEM_10753 = 10753; public static final int GEM_10754 = 10754; public static final int GEM_10755 = 10755; public static final int GARDENER_JAY_JR = 10756; public static final int GARDENER_JAY_JR_10757 = 10757; public static final int GARDENER_JAY_JR_10758 = 10758; public static final int CLERK_10759 = 10759; public static final int STRAY_DOG_10760 = 10760; public static final int LIL_MAIDEN = 10761; public static final int LIL_BLOAT = 10762; public static final int LIL_NYLO = 10763; public static final int LIL_SOT = 10764; public static final int LIL_XARP = 10765; public static final int XARPUS_10766 = 10766; public static final int XARPUS_10767 = 10767; public static final int XARPUS_10768 = 10768; public static final int XARPUS_10769 = 10769; public static final int XARPUS_10770 = 10770; public static final int XARPUS_10771 = 10771; public static final int XARPUS_10772 = 10772; public static final int XARPUS_10773 = 10773; public static final int NYLOCAS_ISCHYROS_10774 = 10774; public static final int NYLOCAS_TOXOBOLOS_10775 = 10775; public static final int NYLOCAS_HAGIOS_10776 = 10776; public static final int NYLOCAS_ISCHYROS_10777 = 10777; public static final int NYLOCAS_TOXOBOLOS_10778 = 10778; public static final int NYLOCAS_HAGIOS_10779 = 10779; public static final int NYLOCAS_ISCHYROS_10780 = 10780; public static final int NYLOCAS_TOXOBOLOS_10781 = 10781; public static final int NYLOCAS_HAGIOS_10782 = 10782; public static final int NYLOCAS_ISCHYROS_10783 = 10783; public static final int NYLOCAS_TOXOBOLOS_10784 = 10784; public static final int NYLOCAS_HAGIOS_10785 = 10785; public static final int NYLOCAS_VASILIAS_10786 = 10786; public static final int NYLOCAS_VASILIAS_10787 = 10787; public static final int NYLOCAS_VASILIAS_10788 = 10788; public static final int NYLOCAS_VASILIAS_10789 = 10789; public static final int NYLOCAS_ISCHYROS_10791 = 10791; public static final int NYLOCAS_TOXOBOLOS_10792 = 10792; public static final int NYLOCAS_HAGIOS_10793 = 10793; public static final int NYLOCAS_ISCHYROS_10794 = 10794; public static final int NYLOCAS_TOXOBOLOS_10795 = 10795; public static final int NYLOCAS_HAGIOS_10796 = 10796; public static final int NYLOCAS_ISCHYROS_10797 = 10797; public static final int NYLOCAS_TOXOBOLOS_10798 = 10798; public static final int NYLOCAS_HAGIOS_10799 = 10799; public static final int NYLOCAS_ISCHYROS_10800 = 10800; public static final int NYLOCAS_TOXOBOLOS_10801 = 10801; public static final int NYLOCAS_HAGIOS_10802 = 10802; public static final int NYLOCAS_PRINKIPAS = 10803; public static final int NYLOCAS_PRINKIPAS_10804 = 10804; public static final int NYLOCAS_PRINKIPAS_10805 = 10805; public static final int NYLOCAS_PRINKIPAS_10806 = 10806; public static final int NYLOCAS_VASILIAS_10807 = 10807; public static final int NYLOCAS_VASILIAS_10808 = 10808; public static final int NYLOCAS_VASILIAS_10809 = 10809; public static final int NYLOCAS_VASILIAS_10810 = 10810; public static final int PESTILENT_BLOAT_10812 = 10812; public static final int PESTILENT_BLOAT_10813 = 10813; public static final int THE_MAIDEN_OF_SUGADINTI_10814 = 10814; public static final int THE_MAIDEN_OF_SUGADINTI_10815 = 10815; public static final int THE_MAIDEN_OF_SUGADINTI_10816 = 10816; public static final int THE_MAIDEN_OF_SUGADINTI_10817 = 10817; public static final int THE_MAIDEN_OF_SUGADINTI_10818 = 10818; public static final int THE_MAIDEN_OF_SUGADINTI_10819 = 10819; public static final int NYLOCAS_MATOMENOS_10820 = 10820; public static final int BLOOD_SPAWN_10821 = 10821; public static final int THE_MAIDEN_OF_SUGADINTI_10822 = 10822; public static final int THE_MAIDEN_OF_SUGADINTI_10823 = 10823; public static final int THE_MAIDEN_OF_SUGADINTI_10824 = 10824; public static final int THE_MAIDEN_OF_SUGADINTI_10825 = 10825; public static final int THE_MAIDEN_OF_SUGADINTI_10826 = 10826; public static final int THE_MAIDEN_OF_SUGADINTI_10827 = 10827; public static final int NYLOCAS_MATOMENOS_10828 = 10828; public static final int BLOOD_SPAWN_10829 = 10829; public static final int VERZIK_VITUR_10830 = 10830; public static final int VERZIK_VITUR_10831 = 10831; public static final int VERZIK_VITUR_10832 = 10832; public static final int VERZIK_VITUR_10833 = 10833; public static final int VERZIK_VITUR_10834 = 10834; public static final int VERZIK_VITUR_10835 = 10835; public static final int VERZIK_VITUR_10836 = 10836; public static final int WEB_10837 = 10837; public static final int COLLAPSING_PILLAR_10838 = 10838; public static final int COLLAPSING_PILLAR_10839 = 10839; public static final int SUPPORTING_PILLAR_10840 = 10840; public static final int NYLOCAS_ISCHYROS_10841 = 10841; public static final int NYLOCAS_TOXOBOLOS_10842 = 10842; public static final int NYLOCAS_HAGIOS_10843 = 10843; public static final int NYLOCAS_ATHANATOS_10844 = 10844; public static final int NYLOCAS_MATOMENOS_10845 = 10845; public static final int VERZIK_VITUR_10847 = 10847; public static final int VERZIK_VITUR_10848 = 10848; public static final int VERZIK_VITUR_10849 = 10849; public static final int VERZIK_VITUR_10850 = 10850; public static final int VERZIK_VITUR_10851 = 10851; public static final int VERZIK_VITUR_10852 = 10852; public static final int VERZIK_VITUR_10853 = 10853; public static final int WEB_10854 = 10854; public static final int COLLAPSING_PILLAR_10855 = 10855; public static final int COLLAPSING_PILLAR_10856 = 10856; public static final int SUPPORTING_PILLAR_10857 = 10857; public static final int NYLOCAS_ISCHYROS_10858 = 10858; public static final int NYLOCAS_TOXOBOLOS_10859 = 10859; public static final int NYLOCAS_HAGIOS_10860 = 10860; public static final int NYLOCAS_ATHANATOS_10861 = 10861; public static final int NYLOCAS_MATOMENOS_10862 = 10862; public static final int SOTETSEG_10864 = 10864; public static final int SOTETSEG_10865 = 10865; public static final int SOTETSEG_10867 = 10867; public static final int SOTETSEG_10868 = 10868; public static final int LIL_MAIDEN_10870 = 10870; public static final int LIL_BLOAT_10871 = 10871; public static final int LIL_NYLO_10872 = 10872; public static final int LIL_SOT_10873 = 10873; public static final int LIL_XARP_10874 = 10874; public static final int MYSTERIOUS_STRANGER_10875 = 10875; public static final int MYSTERIOUS_STRANGER_10876 = 10876; public static final int MYSTERIOUS_STRANGER_10877 = 10877; public static final int TOWN_CRIER_10887 = 10887; public static final int BAT_10888 = 10888; public static final int ASTEROS_ARCEUUS = 10889; public static final int MARTIN_HOLT = 10890; public static final int MARTIN_HOLT_10891 = 10891; public static final int MARTIN_HOLT_10892 = 10892; public static final int MARTIN_HOLT_10893 = 10893; public static final int MARTIN_HOLT_10894 = 10894; public static final int MARTIN_HOLT_10895 = 10895; public static final int PROTEST_LEADER = 10896; public static final int PROTESTER = 10897; public static final int PROTESTER_10898 = 10898; public static final int PROTESTER_10899 = 10899; public static final int PROTESTER_10900 = 10900; public static final int PROTESTER_10901 = 10901; public static final int PROTESTER_10902 = 10902; public static final int PROTESTER_10903 = 10903; public static final int PROTESTER_10904 = 10904; public static final int PROTESTER_10905 = 10905; public static final int PROTESTER_10906 = 10906; public static final int PROTESTER_10907 = 10907; public static final int PROTESTER_10908 = 10908; public static final int GUARD_10909 = 10909; public static final int GUARD_10910 = 10910; public static final int GUARD_10911 = 10911; public static final int GUARD_10912 = 10912; public static final int GUARD_10913 = 10913; public static final int GUARD_10914 = 10914; public static final int GUARD_10915 = 10915; public static final int GUARD_10916 = 10916; public static final int GUARD_10917 = 10917; public static final int GUARD_10918 = 10918; public static final int GUARD_10919 = 10919; public static final int GUARD_10920 = 10920; public static final int GUARD_10921 = 10921; public static final int COMMANDER_FULLORE = 10922; public static final int COMMANDER_FULLORE_10923 = 10923; public static final int ROYAL_GUARD_10924 = 10924; public static final int ROYAL_GUARD_10925 = 10925; public static final int COUNCILLOR_ANDREWS = 10926; public static final int DAVID_ANDREWS = 10927; public static final int TOMAS_LAWRY_10928 = 10928; public static final int TOMAS_LAWRY_10929 = 10929; public static final int CAPTAIN_GINEA_10931 = 10931; public static final int CABIN_BOY_HERBERT = 10932; public static final int CABIN_BOY_HERBERT_10933 = 10933; public static final int CABIN_BOY_HERBERT_10934 = 10934; public static final int SOPHIA_HUGHES_10935 = 10935; public static final int JUDGE_OF_YAMA = 10936; public static final int MYSTERIOUS_VOICE_10937 = 10937; public static final int JUDGE_OF_YAMA_10938 = 10938; public static final int FIRE_WAVE = 10939; public static final int ASSASSIN_10940 = 10940; public static final int ASSASSIN_10941 = 10941; public static final int ASSASSIN_10942 = 10942; public static final int COUNCILLOR_ORSON = 10943; public static final int COUNCILLOR_ORSON_10944 = 10944; public static final int MAN_10945 = 10945; public static final int COUNCILLOR_ORSON_10946 = 10946; public static final int LIZARDMAN_BRUTE_10947 = 10947; public static final int LIZARDMAN_10948 = 10948; public static final int VEOS_10949 = 10949; public static final int MYSTERIOUS_VOICE_10950 = 10950; public static final int XAMPHUR = 10951; public static final int MYSTERIOUS_VOICE_10952 = 10952; public static final int XAMPHUR_10953 = 10953; public static final int XAMPHUR_10954 = 10954; public static final int XAMPHUR_10955 = 10955; public static final int XAMPHUR_10956 = 10956; public static final int PHANTOM_HAND = 10957; public static final int PHANTOM_HAND_10958 = 10958; public static final int KUBEC_UNKAR = 10959; public static final int COUNCILLOR_UNKAR = 10960; public static final int LORD_TROBIN_ARCEUUS_10961 = 10961; public static final int LORD_TROBIN_ARCEUUS_10962 = 10962; public static final int LORD_SHIRO_SHAYZIEN = 10963; public static final int LORD_SHIRO_SHAYZIEN_10964 = 10964; public static final int LORD_SHIRO_SHAYZIEN_10965 = 10965; public static final int LORD_KANDUR_HOSIDIUS = 10966; public static final int KING_KANDUR_HOSIDIUS = 10967; public static final int KING_KANDUR_HOSIDIUS_10968 = 10968; public static final int KING_KANDUR_HOSIDIUS_10969 = 10969; public static final int LORD_KANDUR_HOSIDIUS_10970 = 10970; public static final int LORD_KANDUR_HOSIDIUS_10971 = 10971; public static final int LADY_VULCANA_LOVAKENGJ = 10972; public static final int LADY_VULCANA_LOVAKENGJ_10973 = 10973; public static final int LADY_SHAUNA_PISCARILIUS_10974 = 10974; public static final int LADY_SHAUNA_PISCARILIUS_10975 = 10975; public static final int ARTUR_HOSIDIUS_10976 = 10976; public static final int KING_ARTUR_HOSIDIUS = 10977; public static final int ASTEROS_ARCEUUS_10978 = 10978; public static final int ASTEROS_ARCEUUS_10979 = 10979; public static final int LORD_PANDUR_HOSIDIUS = 10980; public static final int PANDUR_HOSIDIUS = 10981; public static final int ELENA_HOSIDIUS = 10982; public static final int ELENA_HOSIDIUS_10983 = 10983; public static final int BARBARIAN_10984 = 10984; public static final int BARBARIAN_10985 = 10985; public static final int BARBARIAN_10986 = 10986; public static final int BARBARIAN_10987 = 10987; public static final int BARBARIAN_10988 = 10988; public static final int BARBARIAN_WARLORD = 10989; public static final int PHILEAS_RIMOR_10991 = 10991; public static final int CAPTAIN_RACHELLE_10992 = 10992; public static final int PROTESTER_10993 = 10993; public static final int PROTESTER_10994 = 10994; public static final int PROTESTER_10995 = 10995; public static final int PROTESTER_10996 = 10996; public static final int PROTESTER_10997 = 10997; public static final int PROTESTER_10998 = 10998; public static final int PROTESTER_10999 = 10999; public static final int PROTESTER_11000 = 11000; public static final int PROTESTER_11001 = 11001; public static final int PROTESTER_11002 = 11002; public static final int PROTESTER_11003 = 11003; public static final int PROTESTER_11004 = 11004; public static final int PROTESTER_11005 = 11005; public static final int PROTESTER_11006 = 11006; public static final int PROTESTER_11007 = 11007; public static final int PROTESTER_11008 = 11008; public static final int PROTESTER_11009 = 11009; public static final int PROTESTER_11010 = 11010; public static final int PROTESTER_11011 = 11011; public static final int QUEEN_ZYANYI_ARKAN = 11012; public static final int KUALTI = 11013; public static final int KUALTI_11014 = 11014; public static final int KUALTI_11015 = 11015; public static final int KUALTI_11016 = 11016; public static final int KUALTI_11017 = 11017; public static final int KUALTI_11018 = 11018; public static final int KING_ROALD_11019 = 11019; public static final int SIR_AMIK_VARZE_11020 = 11020; public static final int SIR_TIFFY_CASHIEN_11021 = 11021; public static final int KING_LATHAS_11022 = 11022; public static final int KING_THOROS_11023 = 11023; public static final int DUKE_HORACIO_11024 = 11024; public static final int QUEEN_ELLAMARIA_11025 = 11025; public static final int SEAGULL_11026 = 11026; public static final int SPIDER_11027 = 11027; public static final int ICE_CHUNKS = 11028; public static final int ICE_CHUNKS_11029 = 11029; public static final int ICE_CHUNKS_11030 = 11030; public static final int ICE_CHUNKS_11031 = 11031; public static final int MAN_11032 = 11032; public static final int LORD_KANDUR_HOSIDIUS_11033 = 11033; public static final int ELENA_HOSIDIUS_11034 = 11034; public static final int LADY_VULCANA_LOVAKENGJ_11035 = 11035; public static final int COUNCILLOR_UNKAR_11036 = 11036; public static final int JORRA = 11037; public static final int LORD_SHIRO_SHAYZIEN_11038 = 11038; public static final int KAHT_BALAM = 11039; public static final int BLAIR = 11040; public static final int DARYL = 11041; public static final int ROBYN = 11042; public static final int OSWALD = 11043; public static final int SHERYL = 11044; public static final int FARMER_11045 = 11045; public static final int SOLDIER_11046 = 11046; public static final int SOLDIER_11047 = 11047; public static final int DRUNKEN_SOLDIER = 11048; public static final int SOLDIER_11049 = 11049; public static final int FATHER_EYSSERIC = 11050; public static final int MIA = 11051; public static final int ELIJAH = 11052; public static final int WOMAN_11053 = 11053; public static final int WOMAN_11054 = 11054; public static final int KASTON = 11055; public static final int OLD_MAN_11056 = 11056; public static final int MAN_11057 = 11057; public static final int MAN_11058 = 11058; public static final int COMMISSIONER_ANWAR = 11059; public static final int CAPTAIN_BRUCE = 11060; public static final int SERGEANT_RICARDO = 11061; public static final int JESSIE = 11062; public static final int BANDIT_11063 = 11063; public static final int BANDIT_11064 = 11064; public static final int BANDIT_11065 = 11065; public static final int BOAR = 11066; public static final int BOAR_11067 = 11067; public static final int LYNX = 11068; public static final int LYNX_11069 = 11069; public static final int LYNX_11070 = 11070; public static final int LYNX_TAMER = 11071; public static final int SOLDIER_11072 = 11072; public static final int SERGEANT_11073 = 11073; public static final int SOLDIER_11074 = 11074; public static final int SERGEANT_11075 = 11075; public static final int SOLDIER_11076 = 11076; public static final int SERGEANT_11077 = 11077; public static final int SOLDIER_11078 = 11078; public static final int SERGEANT_11079 = 11079; public static final int SOLDIER_11080 = 11080; public static final int SERGEANT_11081 = 11081; public static final int SOLDIER_11082 = 11082; public static final int SERGEANT_11083 = 11083; public static final int SOLDIER_11084 = 11084; public static final int SERGEANT_11085 = 11085; public static final int SOLDIER_11086 = 11086; public static final int SERGEANT_11087 = 11087; public static final int NECROMANCER_11088 = 11088; public static final int RANGER_11089 = 11089; public static final int FAROLT = 11090; public static final int PANDUR_HOSIDIUS_11091 = 11091; public static final int GUARD_11092 = 11092; public static final int HEAD_GUARD = 11093; public static final int GUARD_11094 = 11094; public static final int HEAD_GUARD_11095 = 11095; public static final int GUARD_11096 = 11096; public static final int HEAD_GUARD_11097 = 11097; public static final int GUARD_11098 = 11098; public static final int HEAD_GUARD_11099 = 11099; public static final int GUARD_11100 = 11100; public static final int HEAD_GUARD_11101 = 11101; public static final int GUARD_11102 = 11102; public static final int HEAD_GUARD_11103 = 11103; public static final int GUARD_11104 = 11104; public static final int HEAD_GUARD_11105 = 11105; public static final int GUARD_11106 = 11106; public static final int HEAD_GUARD_11107 = 11107; public static final int DARK_WARRIOR_11109 = 11109; public static final int DARK_WARRIOR_11110 = 11110; public static final int DARK_WARRIOR_11111 = 11111; public static final int ISTORIA = 11112; public static final int ISTORIA_11113 = 11113; public static final int COUNCILLOR_ANDREWS_11152 = 11152; public static final int PHOSANIS_NIGHTMARE_11153 = 11153; public static final int PHOSANIS_NIGHTMARE_11154 = 11154; public static final int PHOSANIS_NIGHTMARE_11155 = 11155; public static final int SWARM_11156 = 11156; public static final int SRARACHA_11157 = 11157; public static final int SRARACHA_11158 = 11158; public static final int SRARACHA_11159 = 11159; public static final int SRARACHA_11160 = 11160; public static final int DUSTY_ALIV = 11161; public static final int MYSTERIOUS_STRANGER_11162 = 11162; public static final int VYREWATCH_11169 = 11169; public static final int VYREWATCH_11170 = 11170; public static final int VYREWATCH_11171 = 11171; public static final int VYREWATCH_11172 = 11172; public static final int VYREWATCH_11173 = 11173; public static final int SPIDER_11174 = 11174; public static final int SPIDER_11175 = 11175; public static final int SPIDER_11176 = 11176; public static final int RANIS_DRAKAN_11177 = 11177; public static final int VERZIK_VITUR_11178 = 11178; public static final int VERZIK_VITUR_11179 = 11179; public static final int VULCAN_ORVOROS = 11180; public static final int NYLOCAS_QUEEN = 11181; public static final int NYLOCAS = 11182; public static final int THE_MAIDEN_OF_SUGADINTI_11183 = 11183; public static final int PESTILENT_BLOAT_11184 = 11184; public static final int NYLOCAS_VASILIAS_11185 = 11185; public static final int SOTETSEG_11186 = 11186; public static final int XARPUS_11187 = 11187; public static final int NYLOCAS_ATHANATOS_11188 = 11188; public static final int NYLOCAS_ISCHYROS_11189 = 11189; public static final int NYLOCAS_TOXOBOLOS_11190 = 11190; public static final int NYLOCAS_HAGIOS_11191 = 11191; public static final int HESPORI_11192 = 11192; public static final int FLOWER_11193 = 11193; public static final int FLOWER_11194 = 11194; public static final int HILL_GIANT_11195 = 11195; public static final int LYNX_TAMER_11196 = 11196; public static final int LYNX_11197 = 11197; public static final int SERGEANT_11198 = 11198; public static final int GNOME_GUARD_11199 = 11199; public static final int GUARD_11200 = 11200; public static final int GUARD_11201 = 11201; public static final int GUARD_11202 = 11202; public static final int GUARD_11203 = 11203; public static final int GUARD_11204 = 11204; public static final int GHOST_GUARD_11205 = 11205; public static final int GUARD_11206 = 11206; public static final int GUARD_11207 = 11207; public static final int GUARD_11208 = 11208; public static final int GUARD_11209 = 11209; public static final int GUARD_11210 = 11210; public static final int PRIFDDINAS_GUARD_11211 = 11211; public static final int D3AD1I_F15HER = 11225; public static final int BOAR31337KILLER = 11226; public static final int ENRAGED_BOAR = 11227; public static final int R0CK_5MASHER = 11228; public static final int REGENT = 11229; public static final int GROUP_STORAGE_TUTOR = 11230; public static final int GROUP_IRON_TUTOR = 11231; public static final int THE_SAGE = 11232; public static final int LEAGUE_TUTOR = 11233; public static final int LEAGUES_ASSISTANT_11234 = 11234; public static final int DUST_DEVIL_11238 = 11238; public static final int ABYSSAL_DEMON_11239 = 11239; public static final int GREATER_NECHRYAEL_11240 = 11240; public static final int JELLY_11241 = 11241; public static final int JELLY_11242 = 11242; public static final int JELLY_11243 = 11243; public static final int JELLY_11244 = 11244; public static final int JELLY_11245 = 11245; public static final int REVENANT_MALEDICTUS = 11246; public static final int TZHAARKETKEH = 11247; public static final int TZHAARKETKEH_11248 = 11248; public static final int GENERAL_BENTNOZE_11249 = 11249; public static final int GENERAL_WARTFACE_11250 = 11250; public static final int GRUBFOOT_11251 = 11251; public static final int GRUBFOOT_11252 = 11252; public static final int GRUBFOOT_11254 = 11254; public static final int GRUBFOOT_11255 = 11255; public static final int GRUBFOOT_11259 = 11259; public static final int ZANIK_11260 = 11260; public static final int ZANIK_11261 = 11261; public static final int ZANIK_11262 = 11262; public static final int ZANIK_11263 = 11263; public static final int ZANIK_11264 = 11264; public static final int OLDAK = 11265; public static final int OLDAK_11266 = 11266; public static final int HIGH_PRIEST_BIGHEAD = 11267; public static final int SKOBLIN = 11268; public static final int SNOTHEAD = 11269; public static final int SNAILFEET = 11270; public static final int MOSSCHIN = 11271; public static final int REDEYES = 11272; public static final int STRONGBONES = 11273; public static final int SNOTHEAD_11274 = 11274; public static final int SNAILFEET_11275 = 11275; public static final int NEXLING = 11276; public static final int NEXLING_11277 = 11277; public static final int NEX = 11278; public static final int NEX_11279 = 11279; public static final int NEX_11280 = 11280; public static final int NEX_11281 = 11281; public static final int NEX_11282 = 11282; public static final int FUMUS = 11283; public static final int UMBRA = 11284; public static final int CRUOR = 11285; public static final int GLACIES = 11286; public static final int MESSENGER = 11287; public static final int ASHUELOT_REIS = 11288; public static final int ASHUELOT_REIS_11289 = 11289; public static final int SPIRITUAL_WARRIOR_11290 = 11290; public static final int SPIRITUAL_RANGER_11291 = 11291; public static final int SPIRITUAL_MAGE_11292 = 11292; public static final int BLOOD_REAVER = 11293; public static final int BLOOD_REAVER_11294 = 11294; public static final int GULL_11297 = 11297; public static final int MOSSCHIN_11298 = 11298; public static final int REDEYES_11299 = 11299; public static final int STRONGBONES_11300 = 11300; public static final int GHOST_11301 = 11301; public static final int PRIEST_11302 = 11302; public static final int PRIEST_11303 = 11303; public static final int PRIEST_11304 = 11304; public static final int PRIEST_11305 = 11305; public static final int PRIEST_11306 = 11306; public static final int PRIEST_11307 = 11307; public static final int PRIEST_11308 = 11308; public static final int PRIEST_11309 = 11309; public static final int PRIEST_11310 = 11310; public static final int PRIEST_11311 = 11311; public static final int PRIEST_11312 = 11312; public static final int PRIEST_11313 = 11313; public static final int GOBLIN_GUARD_11314 = 11314; public static final int GOBLIN_GUARD_11315 = 11315; public static final int GUARD_11316 = 11316; public static final int GUARD_11317 = 11317; public static final int GUARD_11318 = 11318; public static final int GUARD_11319 = 11319; public static final int GUARD_11320 = 11320; public static final int GUARD_11321 = 11321; public static final int GOBLIN_11322 = 11322; public static final int GOBLIN_11323 = 11323; public static final int GOBLIN_11324 = 11324; public static final int GOBLIN_11325 = 11325; public static final int GOBLIN_11326 = 11326; public static final int GOBLIN_11327 = 11327; public static final int GOBLIN_11328 = 11328; public static final int GOBLIN_11329 = 11329; public static final int GOBLIN_11330 = 11330; public static final int GOBLIN_11331 = 11331; public static final int GOBLIN_11332 = 11332; public static final int GOBLIN_11333 = 11333; public static final int GOBLIN_11334 = 11334; public static final int GOBLIN_11335 = 11335; public static final int GOBLIN_11336 = 11336; public static final int GOBLIN_11337 = 11337; public static final int GOBLIN_11338 = 11338; public static final int GOBLIN_11339 = 11339; public static final int GOBLIN_11340 = 11340; public static final int GOBLIN_11341 = 11341; public static final int GOBLIN_11342 = 11342; public static final int GOBLIN_11343 = 11343; public static final int GOBLIN_11344 = 11344; public static final int GOBLIN_11345 = 11345; public static final int GOBLIN_11346 = 11346; public static final int GOBLIN_11347 = 11347; public static final int GOBLIN_11348 = 11348; public static final int GOBLIN_11349 = 11349; public static final int GOBLIN_11350 = 11350; public static final int GOBLIN_11351 = 11351; public static final int GOBLIN_11352 = 11352; public static final int GOBLIN_11353 = 11353; public static final int GOBLIN_11354 = 11354; public static final int GOBLIN_11355 = 11355; public static final int GOBLIN_11356 = 11356; public static final int GOBLIN_11357 = 11357; public static final int GOBLIN_11358 = 11358; public static final int GOBLIN_11359 = 11359; public static final int GOBLIN_11360 = 11360; public static final int GOBLIN_11361 = 11361; public static final int GOBLIN_11362 = 11362; public static final int GOBLIN_11363 = 11363; public static final int GOBLIN_11364 = 11364; public static final int GOBLIN_11365 = 11365; public static final int GOBLIN_11366 = 11366; public static final int GOBLIN_11367 = 11367; public static final int GOBLIN_11368 = 11368; public static final int GOBLIN_11369 = 11369; public static final int GOBLIN_11370 = 11370; public static final int GOBLIN_11371 = 11371; public static final int GOBLIN_11372 = 11372; public static final int GOBLIN_11373 = 11373; public static final int GOBLIN_11374 = 11374; public static final int GOBLIN_11375 = 11375; public static final int GOBLIN_11376 = 11376; public static final int GOBLIN_11377 = 11377; public static final int GOBLIN_11378 = 11378; public static final int GOBLIN_11379 = 11379; public static final int GOBLIN_11380 = 11380; public static final int GOBLIN_11381 = 11381; public static final int PREACHER = 11382; public static final int DIPFLIP = 11383; public static final int OLDAK_11384 = 11384; public static final int OLDAK_11385 = 11385; public static final int WIZARD_DISTENTOR = 11399; public static final int WIZARD_DISTENTOR_11400 = 11400; public static final int GREATISH_GUARDIAN = 11401; public static final int ABYSSAL_PROTECTOR = 11402; public static final int THE_GREAT_GUARDIAN = 11403; public static final int APPRENTICE_FELIX = 11404; public static final int ABYSSAL_GUARDIAN_11405 = 11405; public static final int ABYSSAL_WALKER_11406 = 11406; public static final int ABYSSAL_LEECH_11407 = 11407; public static final int WEAK_CATALYTIC_GUARDIAN = 11408; public static final int RICK_11409 = 11409; public static final int RICK_11410 = 11410; public static final int MEDIUM_CATALYTIC_GUARDIAN = 11411; public static final int STRONG_CATALYTIC_GUARDIAN = 11412; public static final int OVERCHARGED_CATALYTIC_GUARDIAN = 11413; public static final int WEAK_ELEMENTAL_GUARDIAN = 11414; public static final int MEDIUM_ELEMENTAL_GUARDIAN = 11415; public static final int STRONG_ELEMENTAL_GUARDIAN = 11416; public static final int OVERCHARGED_ELEMENTAL_GUARDIAN = 11417; public static final int APPRENTICE_CORDELIA = 11427; public static final int GREATISH_GUARDIAN_11428 = 11428; public static final int ABYSSAL_PROTECTOR_11429 = 11429; public static final int BRIMSTAIL_11430 = 11430; public static final int BRIMSTAIL_11431 = 11431; public static final int ARCHMAGE_SEDRIDOR = 11432; public static final int ARCHMAGE_SEDRIDOR_11433 = 11433; public static final int AUBURY_11434 = 11434; public static final int AUBURY_11435 = 11435; public static final int WIZARD_PERSTEN = 11436; public static final int WIZARD_PERSTEN_11437 = 11437; public static final int WIZARD_PERSTEN_11438 = 11438; public static final int WIZARD_PERSTEN_11439 = 11439; public static final int APPRENTICE_TAMARA = 11440; public static final int APPRENTICE_TAMARA_11441 = 11441; public static final int APPRENTICE_TAMARA_11442 = 11442; public static final int APPRENTICE_CORDELIA_11443 = 11443; public static final int APPRENTICE_CORDELIA_11444 = 11444; public static final int APPRENTICE_CORDELIA_11445 = 11445; public static final int APPRENTICE_FELIX_11446 = 11446; public static final int APPRENTICE_FELIX_11447 = 11447; public static final int APPRENTICE_FELIX_11448 = 11448; public static final int WIZARD_TRAIBORN_11449 = 11449; public static final int ARCHMAGE_SEDRIDOR_11450 = 11450; public static final int MYSTERIOUS_VOICE_11451 = 11451; public static final int MYSTERIOUS_VOICE_11452 = 11452; public static final int ABYSSAL_GUARDIAN_11453 = 11453; public static final int ABYSSAL_WALKER_11454 = 11454; public static final int THE_GREAT_GUARDIAN_11455 = 11455; public static final int THE_GREAT_GUARDIAN_11456 = 11456; public static final int MENAPHITE_SHADOW = 11462; public static final int REANIMATED_HELLHOUND = 11463; public static final int APPRENTICE_TAMARA_11464 = 11464; public static final int APPRENTICE_TAMARA_11465 = 11465; public static final int SMITHING_CATALYST = 11466; public static final int HILL_GIANT_11467 = 11467; public static final int KOVAC = 11468; public static final int KOVAC_11469 = 11469; public static final int KOVAC_11470 = 11470; public static final int KOVAC_11472 = 11472; public static final int TARIK_11473 = 11473; public static final int MAISA_11474 = 11474; public static final int MAISA_11475 = 11475; public static final int MAISA_11476 = 11476; public static final int MAISA_11477 = 11477; public static final int SPIRIT = 11478; public static final int MEHHAR = 11479; public static final int HIGH_PRIEST_OF_SCABARAS = 11480; public static final int HIGH_PRIEST_OF_SCABARAS_11481 = 11481; public static final int CHAMPION_OF_SCABARAS = 11482; public static final int CHAMPION_OF_SCABARAS_11483 = 11483; public static final int SCARAB_SWARM_11484 = 11484; public static final int SHADOW_RIFT = 11485; public static final int OSMAN_11486 = 11486; public static final int OSMAN_11487 = 11487; public static final int SELIM = 11489; public static final int MENAPHITE_AKH = 11490; public static final int MENAPHITE_AKH_11491 = 11491; public static final int MENAPHITE_AKH_11492 = 11492; public static final int MENAPHITE_AKH_11493 = 11493; public static final int MENAPHITE_AKH_11495 = 11495; public static final int MENAPHITE_AKH_11496 = 11496; public static final int MENAPHITE_AKH_11497 = 11497; public static final int MENAPHITE_AKH_11498 = 11498; public static final int COENUS = 11499; public static final int JABARI = 11500; public static final int PHARAOH_KEMESIS = 11501; public static final int HIGH_PRIEST_11502 = 11502; public static final int PRIEST_11503 = 11503; public static final int MENAPHITE_GUARD = 11504; public static final int MENAPHITE_GUARD_11505 = 11505; public static final int MENAPHITE_GUARD_11506 = 11506; public static final int MENAPHITE_GUARD_11507 = 11507; public static final int SCARAB_MAGE_11508 = 11508; public static final int SCARAB_SWARM_11509 = 11509; public static final int SCARAB_MAGE_11510 = 11510; public static final int SCARAB_MAGE_11511 = 11511; public static final int CROCODILE_11513 = 11513; public static final int ROGER = 11514; public static final int MENAPHITE_GUARD_11515 = 11515; public static final int MENAPHITE_GUARD_11516 = 11516; public static final int MENAPHITE_GUARD_11517 = 11517; public static final int MENAPHITE_GUARD_11518 = 11518; public static final int MENAPHITE_GUARD_11519 = 11519; public static final int MENAPHITE_GUARD_11520 = 11520; public static final int MENAPHITE_GUARD_11521 = 11521; public static final int MENAPHITE_GUARD_11522 = 11522; public static final int MENAPHITE_GUARD_11523 = 11523; public static final int MENAPHITE_GUARD_11524 = 11524; public static final int MENAPHITE_GUARD_11525 = 11525; public static final int MENAPHITE_GUARD_11526 = 11526; public static final int MENAPHITE_GUARD_11527 = 11527; public static final int HEAD_MENAPHITE_GUARD = 11528; public static final int HEAD_MENAPHITE_GUARD_11529 = 11529; public static final int HEAD_MENAPHITE_GUARD_11530 = 11530; public static final int HEAD_MENAPHITE_GUARD_11531 = 11531; public static final int HEAD_MENAPHITE_GUARD_11532 = 11532; public static final int CITIZEN = 11533; public static final int CITIZEN_11534 = 11534; public static final int CITIZEN_11535 = 11535; public static final int CITIZEN_11536 = 11536; public static final int CITIZEN_11537 = 11537; public static final int CITIZEN_11538 = 11538; public static final int CITIZEN_11539 = 11539; public static final int CITIZEN_11540 = 11540; public static final int CITIZEN_11541 = 11541; public static final int CITIZEN_11542 = 11542; public static final int CITIZEN_11543 = 11543; public static final int CITIZEN_11544 = 11544; public static final int CITIZEN_11545 = 11545; public static final int CITIZEN_11546 = 11546; public static final int CITIZEN_11547 = 11547; public static final int CITIZEN_11548 = 11548; public static final int CITIZEN_11549 = 11549; public static final int CITIZEN_11550 = 11550; public static final int CITIZEN_11551 = 11551; public static final int CITIZEN_11552 = 11552; public static final int CITIZEN_11553 = 11553; public static final int CITIZEN_11554 = 11554; public static final int CITIZEN_11555 = 11555; public static final int CITIZEN_11556 = 11556; public static final int CITIZEN_11557 = 11557; public static final int CITIZEN_11558 = 11558; public static final int SELIM_11561 = 11561; public static final int JEX_11562 = 11562; public static final int JEX_11563 = 11563; public static final int MAISA_11564 = 11564; public static final int OSMAN_11565 = 11565; public static final int OSMAN_11566 = 11566; public static final int SCARAB_SWARM_11569 = 11569; public static final int MENAPHITE_GUARD_11570 = 11570; public static final int MENAPHITE_GUARD_11571 = 11571; public static final int MENAPHITE_GUARD_11572 = 11572; public static final int MENAPHITE_GUARD_11573 = 11573; public static final int MENAPHITE_GUARD_11574 = 11574; public static final int MENAPHITE_GUARD_11575 = 11575; public static final int COENUS_11576 = 11576; public static final int JOE_11577 = 11577; public static final int LADY_KELI = 11578; public static final int PRINCE_ALI = 11579; public static final int PRINCE_ALI_11580 = 11580; public static final int CROCODILE_11581 = 11581; public static final int CROCODILE_11582 = 11582; public static final int JACKAL_11583 = 11583; public static final int LOCUST = 11584; public static final int LOCUST_11585 = 11585; public static final int PLAGUE_FROG = 11586; public static final int PLAGUE_COW = 11587; public static final int PLAGUE_COW_11588 = 11588; public static final int PLAGUE_COW_11589 = 11589; public static final int WANDERER_11590 = 11590; public static final int AMASCUT = 11591; public static final int WORKER = 11592; public static final int WORKER_11593 = 11593; public static final int WORKER_11594 = 11594; public static final int WORKER_11595 = 11595; public static final int EMBALMER_11596 = 11596; public static final int CARPENTER_11597 = 11597; public static final int RAETUL = 11598; public static final int RAETUL_11599 = 11599; public static final int RAETUL_11600 = 11600; public static final int SIAMUN_11601 = 11601; public static final int HIGH_PRIEST_11602 = 11602; public static final int HIGH_PRIEST_11603 = 11603; public static final int HIGH_PRIEST_11604 = 11604; public static final int HIGH_PRIEST_11605 = 11605; public static final int PRIEST_11606 = 11606; public static final int PRIEST_11607 = 11607; public static final int POSSESSED_PRIEST_11608 = 11608; public static final int PRIEST_11609 = 11609; public static final int PRIEST_11610 = 11610; public static final int LANTHUS = 11650; public static final int HANNIBAL = 11651; public static final int TUMEKENS_GUARDIAN = 11652; public static final int ELIDINIS_GUARDIAN = 11653; public static final int APMEKEN = 11654; public static final int APMEKEN_11655 = 11655; public static final int APMEKEN_11656 = 11656; public static final int CRONDIS = 11657; public static final int GILBERT = 11658; public static final int CRONDIS_11659 = 11659; public static final int CRONDIS_11660 = 11660; public static final int SCABARAS = 11661; public static final int SCABARAS_11662 = 11662; public static final int SCABARAS_11663 = 11663; public static final int ARENA_GUARD_FRONK = 11664; public static final int ARENA_GUARD_NIKKOLAS = 11665; public static final int ARENA_GUARD_FAWRY = 11666; public static final int ARENA_GUARD_YON = 11667; public static final int ARENA_GUARD_DRAKNO = 11668; public static final int ARENA_GUARD_RACHI = 11669; public static final int ARENA_GUARD_JOBY = 11670; public static final int ARENA_GUARD_BENI = 11671; public static final int _1V1_TOURNAMENT_GUIDE = 11672; public static final int DUEL_GUIDE = 11673; public static final int CHRIS = 11674; public static final int FIGHTER = 11675; public static final int FIGHTER_11676 = 11676; public static final int FIGHTER_11677 = 11677; public static final int FIGHTER_11678 = 11678; public static final int FIGHTER_11679 = 11679; public static final int FIGHTER_11680 = 11680; public static final int FIGHTER_11681 = 11681; public static final int FIGHTER_11682 = 11682; public static final int FIGHTER_11683 = 11683; public static final int HET = 11686; public static final int HET_11687 = 11687; public static final int HET_11688 = 11688; public static final int OSMUMTEN = 11689; public static final int OSMUMTEN_11690 = 11690; public static final int SPIRIT_11691 = 11691; public static final int OSMUMTEN_11692 = 11692; public static final int OSMUMTEN_11693 = 11693; public static final int HELPFUL_SPIRIT = 11694; public static final int GHOST_11695 = 11695; public static final int AMASCUT_11696 = 11696; public static final int SCARAB = 11697; public static final int OBELISK = 11698; public static final int OBELISK_11699 = 11699; public static final int PALM_OF_RESOURCEFULNESS = 11700; public static final int PALM_OF_RESOURCEFULNESS_11701 = 11701; public static final int PALM_OF_RESOURCEFULNESS_11702 = 11702; public static final int PALM_OF_RESOURCEFULNESS_11703 = 11703; public static final int PALM_OF_RESOURCEFULNESS_11704 = 11704; public static final int CROCODILE_11705 = 11705; public static final int HETS_SEAL_PROTECTED = 11706; public static final int HETS_SEAL_WEAKENED = 11707; public static final int ORB_OF_DARKNESS = 11708; public static final int BABOON_BRAWLER = 11709; public static final int BABOON_THROWER = 11710; public static final int BABOON_MAGE = 11711; public static final int BABOON_BRAWLER_11712 = 11712; public static final int BABOON_THROWER_11713 = 11713; public static final int BABOON_MAGE_11714 = 11714; public static final int BABOON_SHAMAN = 11715; public static final int VOLATILE_BABOON = 11716; public static final int CURSED_BABOON = 11717; public static final int BABOON_THRALL = 11718; public static final int KEPHRI = 11719; public static final int KEPHRI_11720 = 11720; public static final int KEPHRI_11721 = 11721; public static final int KEPHRI_11722 = 11722; public static final int SCARAB_SWARM_11723 = 11723; public static final int SOLDIER_SCARAB = 11724; public static final int SPITTING_SCARAB = 11725; public static final int ARCANE_SCARAB = 11726; public static final int AGILE_SCARAB = 11727; public static final int EGG_11728 = 11728; public static final int EGG_11729 = 11729; public static final int ZEBAK = 11730; public static final int ZEBAKS_TAIL = 11731; public static final int ZEBAK_11732 = 11732; public static final int ZEBAK_11733 = 11733; public static final int ZEBAKS_TAIL_11734 = 11734; public static final int JUG = 11735; public static final int JUG_11736 = 11736; public static final int BOULDER_11737 = 11737; public static final int WAVE = 11738; public static final int BLOODY_WAVE = 11739; public static final int CROCODILE_11740 = 11740; public static final int CROCODILE_11741 = 11741; public static final int BLOOD_CLOUD = 11742; public static final int BLOOD_CLOUD_11743 = 11743; public static final int ELIDINIS_WARDEN = 11746; public static final int TUMEKENS_WARDEN = 11747; public static final int ELIDINIS_WARDEN_11748 = 11748; public static final int TUMEKENS_WARDEN_11749 = 11749; public static final int OBELISK_11750 = 11750; public static final int OBELISK_11751 = 11751; public static final int OBELISK_11752 = 11752; public static final int ELIDINIS_WARDEN_11753 = 11753; public static final int ELIDINIS_WARDEN_11754 = 11754; public static final int ELIDINIS_WARDEN_11755 = 11755; public static final int TUMEKENS_WARDEN_11756 = 11756; public static final int TUMEKENS_WARDEN_11757 = 11757; public static final int TUMEKENS_WARDEN_11758 = 11758; public static final int ELIDINIS_WARDEN_11759 = 11759; public static final int TUMEKENS_WARDEN_11760 = 11760; public static final int ELIDINIS_WARDEN_11761 = 11761; public static final int TUMEKENS_WARDEN_11762 = 11762; public static final int ELIDINIS_WARDEN_11763 = 11763; public static final int TUMEKENS_WARDEN_11764 = 11764; public static final int PHANTOM = 11767; public static final int PHANTOM_11768 = 11768; public static final int CORE = 11770; public static final int CORE_11771 = 11771; public static final int ENERGY_SIPHON = 11772; public static final int ZEBAKS_PHANTOM = 11774; public static final int BABAS_PHANTOM = 11775; public static final int KEPHRIS_PHANTOM = 11776; public static final int AKKHAS_PHANTOM = 11777; public static final int BABA = 11778; public static final int BABA_11779 = 11779; public static final int BABA_11780 = 11780; public static final int BABOON = 11781; public static final int BOULDER_11782 = 11782; public static final int BOULDER_11783 = 11783; public static final int RUBBLE_11784 = 11784; public static final int RUBBLE_11785 = 11785; public static final int RUBBLE_11786 = 11786; public static final int RUBBLE_11787 = 11787; public static final int AKKHA = 11789; public static final int AKKHA_11790 = 11790; public static final int AKKHA_11791 = 11791; public static final int AKKHA_11792 = 11792; public static final int AKKHA_11793 = 11793; public static final int AKKHA_11794 = 11794; public static final int AKKHA_11795 = 11795; public static final int AKKHA_11796 = 11796; public static final int AKKHAS_SHADOW = 11797; public static final int AKKHAS_SHADOW_11798 = 11798; public static final int AKKHAS_SHADOW_11799 = 11799; public static final int ORB_OF_LIGHTNING = 11800; public static final int ORB_OF_DARKNESS_11801 = 11801; public static final int BURNING_ORB = 11802; public static final int FROZEN_ORB = 11803; public static final int UNSTABLE_ORB = 11804; public static final int BANK_CAMEL = 11806; public static final int MAISA_11807 = 11807; public static final int MAISA_11808 = 11808; public static final int APMEKEN_11809 = 11809; public static final int CRONDIS_11810 = 11810; public static final int HET_11811 = 11811; public static final int TUMEKENS_GUARDIAN_11812 = 11812; public static final int ELIDINIS_GUARDIAN_11813 = 11813; public static final int MESSENGER_11814 = 11814; public static final int MESSENGER_11815 = 11815; public static final int MESSENGER_11816 = 11816; public static final int MESSENGER_11817 = 11817; public static final int AKKHITO = 11840; public static final int BABI = 11841; public static final int KEPHRITI = 11842; public static final int ZEBO = 11843; public static final int TUMEKENS_DAMAGED_GUARDIAN = 11844; public static final int ELIDINIS_DAMAGED_GUARDIAN = 11845; public static final int AKKHITO_11846 = 11846; public static final int BABI_11847 = 11847; public static final int KEPHRITI_11848 = 11848; public static final int ZEBO_11849 = 11849; public static final int TUMEKENS_DAMAGED_GUARDIAN_11850 = 11850; public static final int ELIDINIS_DAMAGED_GUARDIAN_11851 = 11851; /* This file is automatically generated. Do not edit. */ }
package com.jgoodies.uif_lite.panel; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Font; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.LayoutManager; import java.awt.Paint; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.JToolBar; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.border.AbstractBorder; import org.apache.log4j.Logger; /** * A <code>JPanel</code> subclass that has a drop shadow border and * that provides a header with icon, title and tool bar.<p> * * This class can be used to replace the <code>JInternalFrame</code>, * for use outside of a <code>JDesktopPane</code>. * The <code>SimpleInternalFrame</code> is less flexible but often * more usable; it avoids overlapping windows and scales well * up to IDE size. * Several customers have reported that they and their clients feel * much better with both the appearance and the UI feel.<p> * * The SimpleInternalFrame provides the following bound properties: * <i>frameIcon, title, toolBar, content, selected.</i><p> * * By default the SimpleInternalFrame is in <i>selected</i> state. * If you don't do anything, multiple simple internal frames will * be displayed as selected. * * @author Karsten Lentzsch * @version $Revision: 1.11 $ * * @see javax.swing.JInternalFrame * @see javax.swing.JDesktopPane */ public class SimpleInternalFrame extends JPanel implements MouseListener { /** * Logger for this class */ private static final Logger logger = Logger.getLogger(SimpleInternalFrame.class); private final int SPLIT_MARGIN = 6; private JLabel titleLabel; private JPanel gradientPanel; private JPanel headerPanel; private boolean selected; private boolean paintGradient; private boolean paintTitleBorder; /** * Constructs a SimpleInternalFrame with the specified title. * The title is intended to be non-blank, or in other words * should contain non-space characters. * * @param title the initial title */ public SimpleInternalFrame(String title) { this(null, title, null, null); } /** * Constructs a SimpleInternalFrame with the specified * icon, and title. * * @param icon the initial icon * @param title the initial title */ public SimpleInternalFrame(Icon icon, String title) { this(icon, title, null, null); } /** * Constructs a SimpleInternalFrame with the specified * title, tool bar, and content panel. * * @param title the initial title * @param bar the initial tool bar * @param content the initial content pane */ public SimpleInternalFrame(String title, JToolBar bar, JComponent content) { this(null, title, bar, content); } /** * Constructs a SimpleInternalFrame with the specified * icon, title, tool bar, and content panel. * * @param icon the initial icon * @param title the initial title * @param bar the initial tool bar * @param content the initial content pane */ public SimpleInternalFrame( Icon icon, String title, JToolBar bar, JComponent content) { super(new BorderLayout()); this.selected = false; this.titleLabel = new JLabel(title, icon, SwingConstants.LEADING); titleLabel.setFont(getTittleFont()); // Minimizing by double clicking this.addMouseListener(this); this.paintGradient = true; this.paintTitleBorder = false; JPanel top = buildHeader(titleLabel, bar); add(top, BorderLayout.NORTH); if (content != null) { setContent(content); } setBorder(new ShadowBorder()); setSelected(true); updateHeader(); } /** * Returns the frame's icon. * * @return the frame's icon */ public Icon getFrameIcon() { return titleLabel.getIcon(); } /** * Sets a new frame icon. * * @param newIcon the icon to be set */ public void setFrameIcon(Icon newIcon) { Icon oldIcon = getFrameIcon(); titleLabel.setIcon(newIcon); firePropertyChange("frameIcon", oldIcon, newIcon); } /** * Returns the frame's title text. * * @return String the current title text */ public String getTitle() { return titleLabel.getText(); } /** * Sets a new title text. * * @param newText the title text tp be set */ public void setTitle(String newText) { String oldText = getTitle(); titleLabel.setText(newText); firePropertyChange("title", oldText, newText); } /** * Returns the current toolbar, null if none has been set before. * * @return the current toolbar - if any */ public JToolBar getToolBar() { return headerPanel.getComponentCount() > 1 ? (JToolBar) headerPanel.getComponent(1) : null; } /** * Sets a new tool bar in the header. * * @param newToolBar the tool bar to be set in the header */ public void setToolBar(JToolBar newToolBar) { JToolBar oldToolBar = getToolBar(); if (oldToolBar == newToolBar) { return; } if (oldToolBar != null) { headerPanel.remove(oldToolBar); } if (newToolBar != null) { newToolBar.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); headerPanel.add(newToolBar, BorderLayout.SOUTH); } updateHeader(); firePropertyChange("toolBar", oldToolBar, newToolBar); } /** * Returns the content - null, if none has been set. * * @return the current content */ public Component getContent() { return hasContent() ? getComponent(1) : null; } /** * Sets a new panel content; replaces any existing content, if existing. * * @param newContent the panel's new content */ public void setContent(Component newContent) { Component oldContent = getContent(); if (hasContent()) { remove(oldContent); } add(newContent, BorderLayout.CENTER); firePropertyChange("content", oldContent, newContent); } /** * Answers if the panel is currently selected (or in other words active) * or not. In the selected state, the header background will be * rendered differently. * * @return boolean a boolean, where true means the frame is selected * (currently active) and false means it is not */ public boolean isSelected() { return selected; } /** * Returns true if the frame is maximized * @return */ public boolean isMaximized(){ if(this.getParent() instanceof JSplitPane){ JSplitPane split = ((JSplitPane)this.getParent()); if(split.getTopComponent() == this){ if(split.getDividerLocation() == split.getHeight() - (gradientPanel.getHeight() + split.getDividerSize() + SPLIT_MARGIN)){ logger.debug("is a maximized top component"); return true; } else { logger.debug("is not a maximized component, but it is a top component"); return false; } } else { if(split.getDividerLocation() == gradientPanel.getHeight()){ logger.debug("is a maximized bottom component"); return true; } else { logger.debug("is not a maximized component, but is is a bottom component"); return false; } } } else { throw new IllegalStateException("SimpleInternalFrame is not on a split pane"); } } /** * This panel draws its title bar differently if it is selected, * which may be used to indicate to the user that this panel * has the focus, or should get more attention than other * simple internal frames. * * @param newValue a boolean, where true means the frame is selected * (currently active) and false means it is not */ public void setSelected(boolean newValue) { boolean oldValue = isSelected(); selected = newValue; updateHeader(); firePropertyChange("selected", oldValue, newValue); } /** * Creates and answers the header panel, that consists of: * an icon, a title label, a tool bar, and a gradient background. * * @param label the label to paint the icon and text * @param bar the panel's tool bar * @return the panel's built header area */ private JPanel buildHeader(JLabel label, JToolBar bar) { if(paintGradient){ gradientPanel = new GradientPanel(new BorderLayout(), getHeaderBackground()); } else { gradientPanel = new JPanel(new BorderLayout()); } label.setOpaque(false); gradientPanel.add(label, BorderLayout.WEST); gradientPanel.setBorder(BorderFactory.createEmptyBorder(3, 4, 3, 1)); headerPanel = new JPanel(new BorderLayout()); headerPanel.add(gradientPanel, BorderLayout.CENTER); setToolBar(bar); if(paintTitleBorder){ headerPanel.setBorder(new RaisedHeaderBorder()); } headerPanel.setOpaque(false); return headerPanel; } /** * Updates the header. */ private void updateHeader() { gradientPanel.setBackground(getHeaderBackground()); //gradientPanel.setOpaque(isSelected()); titleLabel.setFont(getTittleFont()); titleLabel.setForeground(getTextForeground(isSelected())); headerPanel.repaint(); } /** * Updates the UI. In addition to the superclass behavior, we need * to update the header component. */ public void updateUI() { super.updateUI(); if (titleLabel != null) { updateHeader(); } } /** * Checks and answers if the panel has a content component set. * * @return true if the panel has a content, false if it's empty */ private boolean hasContent() { return getComponentCount() > 1; } /** * Determines and answers the header's text foreground color. * Tries to lookup a special color from the L&amp;F. * In case it is absent, it uses the standard internal frame forground. * * @param isSelected true to lookup the active color, false for the inactive * @return the color of the foreground text */ protected Color getTextForeground(boolean isSelected) { Color c = UIManager.getColor( isSelected ? "SimpleInternalFrame.activeTitleForeground" : "SimpleInternalFrame.inactiveTitleForeground"); if (c != null) { return c; } return UIManager.getColor( isSelected ? "InternalFrame.activeTitleForeground" : "Label.foreground"); } protected Font getTittleFont() { return UIManager.getFont("Label.font").deriveFont(Font.BOLD); } /** * Determines and answers the header's background color. * Tries to lookup a special color from the L&amp;F. * In case it is absent, it uses the standard internal frame background. * * @return the color of the header's background */ protected static Color getHeaderBackground() { Color c = UIManager.getColor("SimpleInternalFrame.activeTitleBackground"); return c != null ? c : UIManager.getColor("InternalFrame.activeTitleBackground"); } // A custom border for the raised header pseudo 3D effect. private static class RaisedHeaderBorder extends AbstractBorder { private static Insets INSETS = new Insets(1, 1, 1, 0); public Insets getBorderInsets(Component c) { return INSETS; } public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) { g.translate(x, y); g.setColor(UIManager.getColor("controlLtHighlight")); g.fillRect(0, 0, w, 1); g.fillRect(0, 1, 1, h-1); g.setColor(UIManager.getColor("controlShadow")); g.fillRect(0, h-1, w, 1); g.translate(-x, -y); } } // A custom border that has a shadow on the right and lower sides. private static class ShadowBorder extends AbstractBorder { private static final Insets INSETS = new Insets(1, 1, 3, 3); public Insets getBorderInsets(Component c) { return INSETS; } public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) { Color shadow = UIManager.getColor("controlShadow"); if (shadow == null) { shadow = Color.GRAY; } Color lightShadow = new Color(shadow.getRed(), shadow.getGreen(), shadow.getBlue(), 170); Color lighterShadow = new Color(shadow.getRed(), shadow.getGreen(), shadow.getBlue(), 70); g.translate(x, y); g.setColor(shadow); g.fillRect(0, 0, w - 3, 1); g.fillRect(0, 0, 1, h - 3); g.fillRect(w - 3, 1, 1, h - 3); g.fillRect(1, h - 3, w - 3, 1); // Shadow line 1 g.setColor(lightShadow); g.fillRect(w - 3, 0, 1, 1); g.fillRect(0, h - 3, 1, 1); g.fillRect(w - 2, 1, 1, h - 3); g.fillRect(1, h - 2, w - 3, 1); // Shadow line2 g.setColor(lighterShadow); g.fillRect(w - 2, 0, 1, 1); g.fillRect(0, h - 2, 1, 1); g.fillRect(w-2, h-2, 1, 1); g.fillRect(w - 1, 1, 1, h - 2); g.fillRect(1, h - 1, w - 2, 1); g.translate(-x, -y); } } /** * A panel with a horizontal gradient background. */ private static final class GradientPanel extends JPanel { private GradientPanel(LayoutManager lm, Color background) { super(lm); setBackground(background); } public void paintComponent(Graphics g) { super.paintComponent(g); if (!isOpaque()) { return; } //Color control = UIManager.getColor("control"); //Color end = new Color((getBackground().getRed() + control.getRed()) / 2, (getBackground().getGreen() + control.getGreen()) / 2, (getBackground().getBlue() + control.getBlue()) / 2); int width = getWidth(); int height = getHeight(); Graphics2D g2 = (Graphics2D) g; Paint storedPaint = g2.getPaint(); /* g2.setPaint( new GradientPaint(0, 0, getBackground(), width, 0, end)); //new GradientPaint(0, height/2, getBackground(), 0, height, VisualConstants.TITLECOLOR_BLUE.darker())); //new GradientPaint(0, height/2, getBackground(), 0, height, getBackground().darker())); g2.fillRect(0, 0, width, height);*/ multipleGradients(g2,width,height, getHeaderBackground()); g2.setPaint(storedPaint); } } public static void multipleGradients(Graphics2D g2, int width, int height, Color background){ Color startColor; Color endColor; int startHeight; int endHeight; startColor = brighten(brighten(brighten(background))); endColor = background; startHeight = (int)(height*0.0/4.0); endHeight = (int)(height*1.0/4.0); g2.setPaint(new GradientPaint(0, startHeight, startColor, 0, endHeight, endColor)); g2.fillRect(0, startHeight, width, endHeight); startColor = background; endColor = background; startHeight = (int)(height*1.0/4.0); endHeight = (int)(height*2.0/4.0); g2.setPaint(new GradientPaint(0, startHeight, startColor, 0, endHeight, endColor)); g2.fillRect(0, startHeight, width, endHeight); startColor = background; endColor = brighten(background); startHeight = (int)(height*2.0/4.0); endHeight = (int)(height*3.0/4.0); g2.setPaint(new GradientPaint(0, startHeight, startColor, 0, endHeight, endColor)); g2.fillRect(0, startHeight, width, endHeight); startColor = brighten(background); endColor = darken(darken(background)); startHeight = (int)(height*3.0/4.0); endHeight = (int)(height*4.0/4.0); g2.setPaint(new GradientPaint(0, startHeight, startColor, 0, endHeight, endColor)); g2.fillRect(0, startHeight, width, endHeight); } private static final double FACTOR = 0.9; public static Color darken(Color c) { return new Color(Math.max((int)(c.getRed() *FACTOR), 0), Math.max((int)(c.getGreen()*FACTOR), 0), Math.max((int)(c.getBlue() *FACTOR), 0)); } public static Color brighten(Color c) { int r = c.getRed(); int g = c.getGreen(); int b = c.getBlue(); int i = (int)(1.0/(1.0-FACTOR)); if ( r == 0 && g == 0 && b == 0) { return new Color(i, i, i); } if ( r > 0 && r < i ) r = i; if ( g > 0 && g < i ) g = i; if ( b > 0 && b < i ) b = i; return new Color(Math.min((int)(r/FACTOR), 255), Math.min((int)(g/FACTOR), 255), Math.min((int)(b/FACTOR), 255)); } /** * Maximizes the frame if it is on a split pane and user double clicks * to the title panel */ public void mouseClicked(MouseEvent e) { if(SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 2){ if(this.getParent() instanceof JSplitPane){ JSplitPane split = (JSplitPane)this.getParent(); int maximizedDividerLocation = 0; if(split.getTopComponent() == this) { maximizedDividerLocation = split.getHeight() - (gradientPanel.getHeight() + split.getDividerSize() + SPLIT_MARGIN); } else { maximizedDividerLocation = gradientPanel.getHeight(); } if (isMaximized()) { split.setDividerLocation(split.getLastDividerLocation()); } else { split.setDividerLocation(maximizedDividerLocation); } } } } public void mouseEntered(MouseEvent e) { // Do nothing } public void mouseExited(MouseEvent e) { // Do nothing } public void mousePressed(MouseEvent e) { // Do nothing } public void mouseReleased(MouseEvent e) { // Do nothing } }
package com.db.stream; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.util.zip.Deflater; /** * A DeflaterInputStream is used to "deflate" (compress) data as it * is read. * * @author Dave Longley */ public class DeflaterInputStream extends FilterInputStream { /** * The deflater (compressor) for this stream. */ protected Deflater mDeflater; /** * A buffer for storing inflated (compressed) bytes from the * underlying input stream. */ protected byte[] mInflatedBytes; /** * A buffer for storing deflated bytes. */ protected byte[] mDeflatedBytes; /** * The read position in the deflated bytes buffer. */ protected int mDeflatedBytesReadPosition; /** * The total number of valid bytes left in the deflated bytes buffer. */ protected int mValidDeflatedBytes; /** * A single byte buffer to use when reading one byte via read(). */ protected byte[] mSingleByteBuffer; /** * Set to true when the end of the underlying stream has been reached. */ protected boolean mEndOfUnderlyingStream; /** * Creates a new DeflaterInputStream with a default Deflater and * a default buffer size of 2048 bytes. * * @param is the input stream to read uncompressed data from. */ public DeflaterInputStream(InputStream is) { this(is, new Deflater()); } /** * Creates a new DeflaterInputStream with a default buffer size of * 2048 bytes. * * @param is the input stream to read uncompressed data from. * @param deflater the deflater to use. */ public DeflaterInputStream(InputStream is, Deflater deflater) { this(is, deflater, 2048); } public DeflaterInputStream(InputStream is, Deflater deflater, int bufferSize) throws IllegalArgumentException { // store underlying input stream super(is); // throw exception is buffer size is < 1 if(bufferSize < 1) { throw new IllegalArgumentException("bufferSize must be >= 1"); } // store deflater mDeflater = deflater; // create the internal read buffer for read inflated bytes mInflatedBytes = new byte[2048]; // create the deflated bytes buffer mDeflatedBytes = new byte[bufferSize]; // read position is 0 mDeflatedBytesReadPosition = 0; // valid bytes is 0 mValidDeflatedBytes = 0; // create the single byte buffer mSingleByteBuffer = new byte[1]; // end of underlying stream not reached mEndOfUnderlyingStream = false; } /** * Fills the deflater with uncompressed data from the underlying * input stream. * * @throws IOException */ protected void fillDeflater() throws IOException { // keep reading while not end of underlying stream, and // deflater is not finished and needs input int count = 0; while(!mEndOfUnderlyingStream && !getDeflater().finished() && getDeflater().needsInput()) { int b = in.read(); if(b != -1) { if(count == mInflatedBytes.length) { // increase the read buffer size as necessary byte[] newBuffer = new byte[count * 2]; System.arraycopy(mInflatedBytes, 0, newBuffer, 0, count); mInflatedBytes = newBuffer; } // add inflated byte to buffer, increment count afterwards mInflatedBytes[count++] = (byte)(b & 0xff); // set deflater input getDeflater().setInput(mInflatedBytes, 0, count); } else { // end of underlying input stream reached mEndOfUnderlyingStream = true; } } // if the end of the underlying stream has been reached then // finish the deflater if(mEndOfUnderlyingStream) { // end of input stream, so finish the deflater getDeflater().finish(); } } /** * Fills the deflated bytes buffer. * * @throws IOException */ protected void fillDeflatedBytesBuffer() throws IOException { // if the deflated bytes buffer is used up, reset the read position if(mValidDeflatedBytes == 0) { mDeflatedBytesReadPosition = 0; } // target is to fill up the deflated bytes buffer int target = mDeflatedBytes.length - mValidDeflatedBytes; // keep reading while target is not reached or deflater is not finished while(target > 0 && !getDeflater().finished()) { // fill the deflater fillDeflater(); // deflate data if the deflater isn't finished if(!getDeflater().finished()) { // deflate data into deflated bytes buffer int count = mDeflater.deflate( mDeflatedBytes, mValidDeflatedBytes, target); // set the deflated bytes read position and valid byte count mValidDeflatedBytes += count; // decrement target target -= count; } } } /** * Reads the next byte of this input stream. If the end of the * stream has been reached, -1 is returned. This method blocks * until some data is available, the end of the stream is * reached, or an exception is thrown. * * @return the next byte of data or -1 if the end of the stream has * been reached. * * @throws IOException */ public int read() throws IOException { int rval = -1; if(read(mSingleByteBuffer) != -1) { rval = mSingleByteBuffer[0] & 0xff; } return rval; } /** * Reads up to <code>len</code> bytes of data from this input stream * into an array of bytes. This method blocks until some input is * available. * * The data that is read from the underlying stream is deflated * (compressed) as it is read. * * @param b the buffer to read the data into. * @param off the offset in the buffer to start the read data at. * @param len the maximum number of bytes read into the buffer. * * @return the number of bytes read into the buffer or -1 if the * end of the stream has been reached. * * @throws IOException */ public int read(byte b[], int off, int len) throws IOException { int rval = -1; if(!isEndOfStreamReached()) { // return 0 if length is 0 if(len == 0) { rval = 0; } else { // read while no data has been read and the end of the stream // has not been reached rval = 0; while(rval == 0 && !isEndOfStreamReached()) { // if data is needed, get it if(mValidDeflatedBytes == 0) { // fill the read deflated bytes buffer fillDeflatedBytesBuffer(); } else { // read from the deflated bytes buffer rval = Math.min(len, mValidDeflatedBytes); // copy deflated bytes into passed buffer System.arraycopy(mDeflatedBytes, mDeflatedBytesReadPosition, b, off, rval); // update read position and valid bytes mDeflatedBytesReadPosition += rval; mValidDeflatedBytes -= rval; } } } } return rval; } /** * Skips over and discards <code>n</code> bytes of data from the * input stream. The <code>skip</code> method may, for a variety of * reasons, end up skipping over some smaller number of bytes, * possibly <code>0</code>. The actual number of bytes skipped is * returned. * * @param n the number of bytes to be skipped. * * @return the actual number of bytes skipped. * * @throws IOException */ public long skip(long n) throws IOException { long rval = 0; if(n != 0) { int numBytes = 0; int bufferSize = 2048; byte[] buffer = new byte[bufferSize]; // read through stream until n reached, discarding data while(numBytes != -1 && rval != n) { // get the number of bytes to read int readSize = Math.min((int)(n - rval), bufferSize); numBytes = read(buffer, 0, readSize); if(numBytes > 0) { rval += numBytes; } } } return rval; } /** * Returns how many bytes are available from this input stream. * * @return how many bytes are available from this input stream. * * @throws IOException */ public int available() throws IOException { int rval = 0; // return 1 if the end of the stream hasn't been reached if(!isEndOfStreamReached()) { rval = 1; } return rval; } /** * Finishes the deflater. This method should be called if the input * stream is in a chain and should not be closed to finish the * deflater. * * The read() methods for this stream will continue to read until the * deflater is empty. */ public void finish() { // finish the deflater getDeflater().finish(); } /** * Closes this input stream and the underlying input stream. Ends * the Deflater. * * @throws IOException */ public void close() throws IOException { // close underlying input stream in.close(); // finish finish(); // end the deflater getDeflater().end(); } /** * Gets the deflater used by this input stream. * * @return the deflater used by this input stream. */ public Deflater getDeflater() { return mDeflater; } /** * Returns true if the end of this stream has been reached. * * @return true if the end of this stream has been reached, false if not. */ public boolean isEndOfStreamReached() { boolean rval = false; // first see if the end of the underlying stream has been reached if(mEndOfUnderlyingStream) { // see if there is no more deflater data if(getDeflater().finished()) { // see if there are no more valid deflated bytes to read if(mValidDeflatedBytes == 0) { rval = true; } } } return rval; } }
package com.jvms.i18neditor.editor; import java.util.Enumeration; import java.util.List; import javax.swing.tree.DefaultTreeModel; import com.google.common.collect.Lists; import com.jvms.i18neditor.util.MessageBundle; import com.jvms.i18neditor.util.ResourceKeys; /** * This class represents a model for the translation tree. * * @author Jacob van Mourik */ public class TranslationTreeModel extends DefaultTreeModel { private final static long serialVersionUID = 3261808274177599488L; public TranslationTreeModel() { super(new TranslationTreeNode(MessageBundle.get("tree.root.name"), Lists.newArrayList())); } public TranslationTreeModel(List<String> keys) { super(new TranslationTreeNode(MessageBundle.get("tree.root.name"), keys)); } public Enumeration<TranslationTreeNode> getEnumeration() { return getEnumeration((TranslationTreeNode) getRoot()); } @SuppressWarnings("unchecked") public Enumeration<TranslationTreeNode> getEnumeration(TranslationTreeNode node) { return node.depthFirstEnumeration(); } public TranslationTreeNode getNodeByKey(String key) { Enumeration<TranslationTreeNode> e = getEnumeration(); while (e.hasMoreElements()) { TranslationTreeNode n = e.nextElement(); if (n.getKey().equals(key)) { return n; } } return null; } public boolean hasErrorChildNode(TranslationTreeNode node) { Enumeration<TranslationTreeNode> e = getEnumeration(node); while (e.hasMoreElements()) { TranslationTreeNode n = e.nextElement(); if (n.hasError()) { return true; } } return false; } public TranslationTreeNode getClosestParentNodeByKey(String key) { TranslationTreeNode node = null; int count = ResourceKeys.size(key); while (node == null && count > 0) { key = ResourceKeys.withoutLastPart(key); node = getNodeByKey(key); count } if (node != null) { return node; } else { return (TranslationTreeNode) getRoot(); } } public void insertNodeInto(TranslationTreeNode newChild, TranslationTreeNode parent) { insertNodeInto(newChild, parent, getNewChildIndex(newChild, parent)); } public void insertDescendantsInto(TranslationTreeNode source, TranslationTreeNode target) { source.getChildren().forEach(child -> { TranslationTreeNode existing = target.getChild(child.getName()); if (existing != null) { if (existing.isLeaf()) { removeNodeFromParent(existing); insertNodeInto(child, target); } else { insertDescendantsInto(child, existing); } } else { insertNodeInto(child, target); } }); } public void nodeWithParentsChanged(TranslationTreeNode node) { while (node != null) { nodeChanged(node); node = (TranslationTreeNode) node.getParent(); } } private int getNewChildIndex(TranslationTreeNode newChild, TranslationTreeNode parent) { int result = 0; for (TranslationTreeNode n : parent.getChildren()) { if (n.getName().compareTo(newChild.getName()) < 0) { result++; } } return result; } }
package com.kryptnostic.v2.storage.api; import java.util.Set; import java.util.UUID; import com.kryptnostic.v2.constants.Names; import retrofit.http.GET; import retrofit.http.Path; /** * This API is used for retrieving paged lists of objects for a user. Ordering is not guaranteed across calls. * * @author Matthew Tamayo-Rios &lt;matthew@kryptnostic.com&gt; * */ public interface ObjectListingApi { String CONTROLLER = "/objects"; String TYPE = "type"; String PAGE = Names.PAGE_FIELD; String PAGE_SIZE = Names.SIZE_FIELD; String ID = Names.ID_FIELD; String LATEST_PATH = "/latest"; String USER_ID_PATH = "/{" + ID + "}"; String TYPE_ID_PATH = "/type/{" + TYPE + "}"; String TYPE_NAME_PATH = "/typename/{" + TYPE + "}"; String PAGE_SIZE_PATH = "/{" + PAGE_SIZE + "}"; String PAGE_PATH = "/{" + PAGE + "}"; /** * Retrieves all objects owned by a given a user. This is a slow call / uncached call. * * @param userId The userId for which to return the list of paged objects. * @return The UUID of all objects owned by the user. */ @GET( CONTROLLER + USER_ID_PATH ) Set<UUID> getAllObjectIds( @Path( ID ) UUID userId ); @GET( CONTROLLER + USER_ID_PATH + PAGE_SIZE_PATH + PAGE_PATH ) Set<UUID> getAllObjectIdsPaged( @Path( ID ) UUID userId, @Path( PAGE ) Integer offset, @Path( PAGE_SIZE ) Integer pageSize ); @GET( CONTROLLER + USER_ID_PATH + TYPE_ID_PATH ) Set<UUID> getObjectIdsByType( @Path( ID ) UUID userId, @Path( TYPE ) UUID type ); @GET( CONTROLLER + USER_ID_PATH + TYPE_ID_PATH + PAGE_SIZE_PATH + PAGE_PATH ) Set<UUID> getObjectIdsByTypePaged( @Path( ID ) UUID userId, @Path( TYPE ) UUID typeId, @Path( PAGE ) Integer offset, @Path( PAGE_SIZE ) Integer pageSize ); @GET( CONTROLLER + TYPE_NAME_PATH ) UUID getTypeForName( @Path( TYPE ) String typeName); }
package com.kscs.util.plugins.xjc; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.beans.PropertyVetoException; import java.beans.VetoableChangeListener; import java.beans.VetoableChangeSupport; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import com.kscs.util.jaxb.BoundList; import com.kscs.util.jaxb.BoundListProxy; import com.kscs.util.jaxb.CollectionChangeEvent; import com.kscs.util.jaxb.CollectionChangeEventType; import com.kscs.util.jaxb.CollectionChangeListener; import com.kscs.util.jaxb.VetoableCollectionChangeListener; import com.kscs.util.plugins.xjc.common.AbstractPlugin; import com.kscs.util.plugins.xjc.common.Setter; import com.sun.codemodel.JBlock; import com.sun.codemodel.JCatchBlock; import com.sun.codemodel.JClass; import com.sun.codemodel.JCodeModel; import com.sun.codemodel.JDefinedClass; import com.sun.codemodel.JExpr; import com.sun.codemodel.JFieldRef; import com.sun.codemodel.JFieldVar; import com.sun.codemodel.JInvocation; import com.sun.codemodel.JMethod; import com.sun.codemodel.JMod; import com.sun.codemodel.JTryBlock; import com.sun.codemodel.JType; import com.sun.codemodel.JVar; import com.sun.tools.xjc.Options; import com.sun.tools.xjc.outline.ClassOutline; import com.sun.tools.xjc.outline.FieldOutline; import com.sun.tools.xjc.outline.Outline; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; /** * XJC Plugin generated conatrained and bound JavaBeans properties */ public class BoundPropertiesPlugin extends AbstractPlugin { private boolean constrained = true; private boolean bound = true; private boolean setterThrows = false; private boolean generateTools = true; private final Map<String,Setter<String>> setters = new HashMap<String,Setter<String>>() {{ put("constrained", new Setter<String>() { @Override public void set(final String val) { BoundPropertiesPlugin.this.constrained = parseBoolean(val); } }); put("bound", new Setter<String>() { @Override public void set(final String val) { BoundPropertiesPlugin.this.bound = parseBoolean(val); } }); put("generate-tools", new Setter<String>() { @Override public void set(final String val) { BoundPropertiesPlugin.this.generateTools = parseBoolean(val); } }); put("setter-throws", new Setter<String>() { @Override public void set(final String val) { BoundPropertiesPlugin.this.setterThrows = parseBoolean(val); } }); }}; @Override public String getOptionName() { return "Xconstrained-properties"; } @Override protected Map<String, Setter<String>> getSetters() { return this.setters; } @Override public PluginUsageBuilder buildUsage(final PluginUsageBuilder pluginUsageBuilder) { return pluginUsageBuilder.addMain("constrained-properties") .addOption("constrained", this.constrained) .addOption("bound", this.bound) .addOption("setter-throws", this.setterThrows) .addOption("constrained-properties-generate-tools", this.generateTools); } @Override public boolean run(final Outline outline, final Options opt, final ErrorHandler errorHandler) throws SAXException { if (!this.constrained && !this.bound) { return true; } final ApiConstructs apiConstructs = new ApiConstructs(outline, opt, errorHandler); final JCodeModel m = outline.getCodeModel(); if (this.generateTools) { // generate bound collection helper classes apiConstructs.writeSourceFile(BoundList.class); apiConstructs.writeSourceFile(BoundListProxy.class); apiConstructs.writeSourceFile(CollectionChangeEventType.class); apiConstructs.writeSourceFile(CollectionChangeEvent.class); apiConstructs.writeSourceFile(CollectionChangeListener.class); apiConstructs.writeSourceFile(VetoableCollectionChangeListener.class); } final int setterAccess = apiConstructs.hasPlugin(ImmutablePlugin.class) ? JMod.PROTECTED : JMod.PUBLIC; for (final ClassOutline classOutline : outline.getClasses()) { final JDefinedClass definedClass = classOutline.implClass; // Create bound collection proxies for (final FieldOutline fieldOutline : classOutline.getDeclaredFields()) { if (fieldOutline.getPropertyInfo().isCollection() && !definedClass.fields().get(fieldOutline.getPropertyInfo().getName(false)).type().isArray()) { generateProxyField(classOutline, fieldOutline); generateLazyProxyInitGetter(classOutline, fieldOutline); } } if (this.constrained && this.setterThrows) { for (final JMethod method : definedClass.methods()) { if (method.name().startsWith("with") && !"withVetoableChangeListener".equals(method.name()) && !"withPropertyChangeListener".equals(method.name()) ) { method._throws(PropertyVetoException.class); } } } if (this.constrained) createSupportProperty(outline, classOutline, VetoableChangeSupport.class, VetoableChangeListener.class, "vetoableChange"); if (this.bound) createSupportProperty(outline, classOutline, PropertyChangeSupport.class, PropertyChangeListener.class, "propertyChange"); for (final JFieldVar field : definedClass.fields().values()) { //final JFieldVar field = definedClass.fields().get(fieldOutline.getPropertyInfo().getName(false)); final JMethod oldSetter = definedClass.getMethod("set" + outline.getModel().getNameConverter().toPropertyName(field.name()), new JType[]{field.type()}); if (oldSetter != null && !field.type().isArray()) { definedClass.methods().remove(oldSetter); final JMethod setter = definedClass.method(setterAccess, m.VOID, "set" + outline.getModel().getNameConverter().toPropertyName(field.name())); final JVar setterArg = setter.param(JMod.FINAL, field.type(), "value"); final JBlock body = setter.body(); final JVar oldValueVar = body.decl(JMod.FINAL, field.type(), "oldValue", JExpr._this().ref(field)); if (this.constrained) { final JTryBlock tryBlock; final JBlock block; if (this.setterThrows) { block = body; setter._throws(PropertyVetoException.class); } else { tryBlock = body._try(); block = tryBlock.body(); final JCatchBlock catchBlock = tryBlock._catch(m.ref(PropertyVetoException.class)); final JVar exceptionVar = catchBlock.param("x"); catchBlock.body()._throw(JExpr._new(m.ref(RuntimeException.class)).arg(exceptionVar)); } invokeListener(block, field, oldValueVar, setterArg, "vetoableChange"); } body.assign(JExpr._this().ref(field), setterArg); if (this.bound) { invokeListener(body, field, oldValueVar, setterArg, "propertyChange"); } } } } return true; } private void createSupportProperty(final Outline outline, final ClassOutline classOutline, final Class<?> supportClass, final Class<?> listenerClass, final String aspectName) { final JCodeModel m = outline.getCodeModel(); final JDefinedClass definedClass = classOutline.implClass; final String aspectNameCap = aspectName.substring(0, 1).toUpperCase() + aspectName.substring(1); if (classOutline.getSuperClass() == null) { // only generate fields in topmost classes final JFieldVar supportField = definedClass.field(JMod.PROTECTED | JMod.FINAL | JMod.TRANSIENT, supportClass, aspectName + "Support", JExpr._new(m.ref(supportClass)).arg(JExpr._this())); final JMethod addMethod = definedClass.method(JMod.PUBLIC, m.VOID, "add" + aspectNameCap + "Listener"); final JVar addParam = addMethod.param(JMod.FINAL, listenerClass, aspectName + "Listener"); addMethod.body().invoke(JExpr._this().ref(supportField), "add" + aspectNameCap + "Listener").arg(addParam); } final JMethod withMethod = definedClass.method(JMod.PUBLIC, definedClass, "with" + aspectNameCap + "Listener"); final JVar withParam = withMethod.param(JMod.FINAL, listenerClass, aspectName + "Listener"); withMethod.body().invoke("add" + aspectNameCap + "Listener").arg(withParam); withMethod.body()._return(JExpr._this()); if (classOutline.getSuperClass() != null) { withMethod.annotate(Override.class); } } private JInvocation invokeListener(final JBlock block, final JFieldVar field, final JVar oldValueVar, final JVar setterArg, final String aspectName) { final String aspectNameCap = aspectName.substring(0, 1).toUpperCase() + aspectName.substring(1); final JInvocation fvcInvoke = block.invoke(JExpr._this().ref(aspectName + "Support"), "fire" + aspectNameCap); fvcInvoke.arg(JExpr.lit(field.name())); fvcInvoke.arg(oldValueVar); fvcInvoke.arg(setterArg); return fvcInvoke; } private JFieldVar generateProxyField(final ClassOutline classOutline, final FieldOutline fieldOutline) { final JCodeModel m = classOutline.parent().getCodeModel(); final JDefinedClass definedClass = classOutline.implClass; final JFieldVar collectionField = definedClass.fields().get(fieldOutline.getPropertyInfo().getName(false)); final JClass elementType = ((JClass) collectionField.type()).getTypeParameters().get(0); return definedClass.field(JMod.PRIVATE | JMod.TRANSIENT, m.ref(BoundList.class).narrow(elementType), collectionField.name() + "Proxy", JExpr._null()); } private JMethod generateLazyProxyInitGetter(final ClassOutline classOutline, final FieldOutline fieldOutline) { final JCodeModel m = classOutline.parent().getCodeModel(); final JDefinedClass definedClass = classOutline.implClass; final String fieldName = fieldOutline.getPropertyInfo().getName(false); final String getterName = "get" + fieldOutline.getPropertyInfo().getName(true); final JFieldVar collectionField = definedClass.fields().get(fieldName); final JClass elementType = ((JClass) collectionField.type()).getTypeParameters().get(0); final JClass proxyFieldType = m.ref(BoundList.class).narrow(elementType); final JFieldRef collectionFieldRef = JExpr._this().ref(collectionField); final JFieldRef proxyField = JExpr._this().ref(collectionField.name() + "Proxy"); final JMethod oldGetter = definedClass.getMethod(getterName, new JType[0]); definedClass.methods().remove(oldGetter); final JMethod newGetter = definedClass.method(JMod.PUBLIC, proxyFieldType, getterName); newGetter.body()._if(collectionFieldRef.eq(JExpr._null()))._then().assign(collectionFieldRef, JExpr._new(m.ref(ArrayList.class).narrow(elementType))); final JBlock ifProxyNull = newGetter.body()._if(proxyField.eq(JExpr._null()))._then(); ifProxyNull.assign(proxyField, JExpr._new(m.ref(BoundListProxy.class).narrow(elementType)).arg(collectionFieldRef)); newGetter.body()._return(proxyField); return newGetter; } public boolean isConstrained() { return this.constrained; } public boolean isSetterThrows() { return this.setterThrows; } }
package com.ljs.ifootballmanager.ai.formation; import com.ljs.ifootballmanager.ai.Role; import com.ljs.ifootballmanager.ai.Tactic; import com.ljs.ifootballmanager.ai.formation.score.DefaultScorer; import com.ljs.ifootballmanager.ai.formation.score.FormationScorer; import com.ljs.ifootballmanager.ai.formation.selection.Actions; import com.ljs.ifootballmanager.ai.formation.selection.RandomFormationGenerator; import com.ljs.ifootballmanager.ai.formation.validate.FormationValidator; import com.ljs.ifootballmanager.ai.league.League; import com.ljs.ifootballmanager.ai.player.Player; import com.ljs.ifootballmanager.ai.player.SquadHolder; import com.ljs.ifootballmanager.ai.rating.Rating; import com.ljs.ifootballmanager.ai.report.Report; import com.ljs.ifootballmanager.ai.selection.Substitution; import java.io.PrintWriter; import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.Set; import java.util.stream.Stream; import com.github.lstephen.ai.search.HillClimbing; import com.github.lstephen.ai.search.RepeatedHillClimbing; import com.github.lstephen.ai.search.Validator; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; /** * * @author lstephen */ public final class Formation implements Report { private final FormationValidator validator; private final FormationScorer scorer; private final FormationMap positions; private final Tactic tactic; private Formation(FormationValidator validator, FormationScorer scorer, Tactic tactic, FormationMap in) { this.validator = validator; this.scorer = scorer; this.tactic = tactic; this.positions = in; } public FormationValidator getValidator() { return validator; } public Tactic getTactic() { return tactic; } public FormationScorer getScorer() { return scorer; } public Formation withScorer(FormationScorer scorer) { return new Formation(validator, scorer, tactic, positions); } public Formation withTactic(Tactic tactic) { return new Formation(validator, scorer, tactic, positions); } public Formation withUpdatedPlayers(Iterable<Player> ps) { FormationMap f = FormationMap.create(positions); for (Player p : ps) { Role r = findRole(p); f.remove(r, p); f.put(r, p); } return new Formation(validator, scorer, tactic, f); } public Player getPenaltyKicker() { return Player .bySkill(Rating.SHOOTING) .compound(Player.byTieBreak()) .max(players()); } public ImmutableSet<Role> getRoles() { return ImmutableSet.copyOf(positions.roles()); } public Formation move(Role r, Player p) { FormationMap f = FormationMap.create(positions); if (contains(p)) { Player inFormation = findInFormation(p); f.remove(findRole(inFormation), inFormation); f.put(r, inFormation); } else { f.put(r, p); } return Formation.create(validator, scorer, tactic, f); } public Role findRole(Player p) { return positions.get(p); } private Player findInFormation(Player p) { Role r = findRole(p); for (Player inFormation : positions.get(r)) { if (p.equals(inFormation)) { return inFormation; } } throw new IllegalStateException(); } public boolean contains(Player p) { return positions.contains(p); } public ImmutableSet<Player> players(Role r) { return ImmutableSet.copyOf(positions.get(r)); } public ImmutableList<Player> players() { List<Player> players = Lists.newArrayList(); for (Role r : Ordering.natural().sortedCopy(positions.roles())) { for (Player p : SquadHolder.get().getOrdering().sortedCopy(positions.get(r))) { players.add(p); } } return ImmutableList.copyOf(players); } public Stream<Player> playerStream() { return players().stream(); } public Iterable<Player> unsortedPlayers() { return positions.players(); } private Formation substitute(Substitution s) { return substitute(s.getIn(), s.getRole(), s.getOut()); } public Formation substitute(Player in, Role r, Player out) { FormationMap f = FormationMap.create(positions); f.remove(findRole(out), out); f.put(r, in); return Formation.create(validator, scorer, tactic, f); } public boolean isValid(Substitution s) { if (!contains(s.getOut())) { return false; } if (s.getRole().equals(findRole(s.getOut()))) { return true; } return substitute(s).isValid(); } public Double score() { return scorer.score(this, tactic); } public Double score(Tactic tactic) { return scorer.score(this, tactic); } public Double scoring() { return scoring(tactic); } public Double scoring(Tactic tactic) { return scorer.scoring(this, tactic); } public Double defending() { return defending(tactic); } public Double defending(Tactic tactic) { return scorer.defending(this, tactic); } public Boolean isValid() { if (positions.size() != 11) { return false; } if (ImmutableSet.copyOf(positions.players()).size() != 11) { return false; } return validator.isValid(this); } public Integer count(Role r) { return positions.get(r).size(); } public Integer count(Iterable<Role> rs) { Integer count = 0; for (Role r : rs) { count += count(r); } return count; } public void print(PrintWriter w) { w.format("%s%n", getTactic()); printPlayers(w); scorer.print(this, w); } public void printPlayers(PrintWriter w) { for (Player p : players()) { w.format("%s %s%n", findRole(p), p.getName()); } } public static Formation create(FormationValidator validator, FormationScorer scorer, Tactic tactic, Multimap<Role, Player> players) { return create(validator, scorer, tactic, FormationMap.create(players)); } public static Formation create(FormationValidator validator, FormationScorer scorer, Tactic tactic, FormationMap players) { return new Formation(validator, scorer, tactic, players); } public static Formation create(FormationValidator validator, Tactic tactic, Multimap<Role, Player> players) { return create(validator, DefaultScorer.get(), tactic, players); } public static ImmutableList<Formation> select(League league, Iterable<Player> available, FormationScorer scorer) { return select(league, SelectionCriteria.create(league, available), scorer); } public static Formation select(League league, Tactic tactic, Iterable<Player> available, FormationScorer scorer) { return select(league, tactic, SelectionCriteria.create(league, available), scorer); } public static ImmutableList<Formation> select(League league, SelectionCriteria criteria, FormationScorer scorer) { Set<Formation> formations = Sets.newHashSet(); for (Tactic t : Tactic.values()) { System.out.print(t.toString()); formations.add(select(league, t, criteria, scorer)); } Preconditions.checkState(formations.size() == Tactic.values().length); final Double max = byScore(scorer).max(formations).score(); return byScore(scorer) .reverse() .immutableSortedCopy(formations); } public static Formation selectOne(League league, SelectionCriteria criteria, FormationScorer scorer) { ImmutableList<Formation> candidates = select(league, criteria, scorer); Double base = candidates.get(0).score() * .95 - 1; List<Formation> weighted = Lists.newArrayList(); for (Formation f : candidates) { int weighting = Math.min((int) Math.round(f.score() - base), 1); for (int i = 0; i < weighting; i++) { weighted.add(f); } System.out.print(f.getTactic().getCode() + ":" + weighting + " "); } List<Formation> weightedList = Lists.newArrayList(weighted); Double seed = 0.0; for (Player p : criteria.getAll()) { seed += p.getAbilitiesSum(); seed += p.getGames(); } Random r = new Random(Math.round(seed)); Integer idx = r.nextInt(weightedList.size()); System.out.println("(" + weightedList.size() + ") -> " + weightedList.get(idx).getTactic()); return weightedList.get(idx); } private static Formation select(League league, Tactic tactic, SelectionCriteria criteria, FormationScorer scorer) { HillClimbing<Formation> builder = HillClimbing .<Formation>builder() .validator(Formation::isValid) .heuristic(byScore(scorer).compound(byAge().reverse()).compound(byAbilitySum())) .actionGenerator(Actions.create(criteria)) .build(); return new RepeatedHillClimbing<Formation>( RandomFormationGenerator.create(league.getFormationValidator(), scorer, tactic, criteria), builder) .search(); } private static Ordering<Formation> byScore(final FormationScorer scorer) { return Ordering .natural() .onResultOf((Formation f) -> scorer.score(f, f.getTactic())); } private static Ordering<Formation> byAge() { return Ordering .natural() .onResultOf((Formation f) -> f .players() .stream() .map(Player::getAge) .reduce(0, Integer::sum)); } private static Ordering<Formation> byAbilitySum() { return Ordering .natural() .onResultOf((Formation f) -> f .players() .stream() .flatMap(p -> Arrays.stream(Rating.values()).map(r -> p.getAbilityRating(f.findRole(p), f.getTactic(), r))) .reduce(0.0, Double::sum)); } }
package com.lothrazar.samscontrolblocks; import java.util.ArrayList; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumParticleTypes; import net.minecraft.world.World; import net.minecraftforge.event.entity.player.PlayerInteractEvent; public class UtilPistonSpell { public static ArrayList<Block> ignoreList = new ArrayList<Block>(); private static String ignoreListFromConfig = ""; private static void translateCSV() { //do this on the fly, could be items not around yet during config change if(ignoreList.size() == 0) { ignoreList = ModControlBlocks.getBlockListFromCSV(ignoreListFromConfig); //ignoreList.add(Blocks.bedrock); ignoreList.add(Blocks.end_portal_frame); ignoreList.add(Blocks.end_portal); ignoreList.add(Blocks.portal); ignoreList.add(Blocks.bed); ignoreList.add(Blocks.dark_oak_door); ignoreList.add(Blocks.acacia_door); ignoreList.add(Blocks.birch_door); ignoreList.add(Blocks.oak_door); ignoreList.add(Blocks.spruce_door); ignoreList.add(Blocks.jungle_door); ignoreList.add(Blocks.iron_door); ignoreList.add(Blocks.skull); } } public static void seIgnoreBlocksFromString(String csv) { ignoreListFromConfig = csv; } public static void moveBlockTo(World world, EntityPlayer player,BlockPos pos, BlockPos posMoveToHere) { IBlockState hit = world.getBlockState(pos); translateCSV(); if(hit == null || ignoreList.contains(hit.getBlock())) { return; } if(world.isAirBlock(posMoveToHere) && world.isBlockModifiable(player, pos)) { if(world.isRemote) { ModControlBlocks.spawnParticle(world, EnumParticleTypes.CRIT_MAGIC, pos); } else { ModControlBlocks.playSoundAt(player, "random.wood_click"); //they swap places //world.destroyBlock(posMoveToHere, false); world.destroyBlock(pos, false); world.setBlockState(posMoveToHere, hit);//pulls the block towards the player player.swingItem(); } } } }
package com.mcjty.rftools.blocks.screens; import com.mcjty.rftools.RFTools; import com.mcjty.rftools.blocks.screens.modulesclient.*; import com.mcjty.rftools.blocks.screens.modulesclient.EnergyBarClientScreenModule; import com.mcjty.rftools.blocks.screens.modulesclient.ItemStackClientScreenModule; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.ResourceLocation; import org.lwjgl.opengl.GL11; import java.util.ArrayList; import java.util.List; @SideOnly(Side.CLIENT) public class ScreenRenderer extends TileEntitySpecialRenderer { private static final ResourceLocation texture = new ResourceLocation(RFTools.MODID, "textures/blocks/screenFrame.png"); private final ModelScreen screenModel = new ModelScreen(); private List<ClientScreenModule> modules; public ScreenRenderer() { modules = new ArrayList<ClientScreenModule>(); modules.add(new TextClientScreenModule("Large capacitor:")); modules.add(new EnergyBarClientScreenModule()); modules.add(new TextClientScreenModule("Dimension 'mining':")); modules.add(new TextClientScreenModule("40000000RF").color(0x00ff00)); modules.add(new TextClientScreenModule("")); modules.add(new TextClientScreenModule("Inventory:")); modules.add(new ItemStackClientScreenModule()); } @Override public void renderTileEntityAt(TileEntity tileEntity, double x, double y, double z, float f) { GL11.glPushMatrix(); float f3; int meta = tileEntity.getBlockMetadata(); f3 = 0.0F; if (meta == 2) { f3 = 180.0F; } if (meta == 4) { f3 = 90.0F; } if (meta == 5) { f3 = -90.0F; } GL11.glTranslatef((float) x + 0.5F, (float) y + 0.75F, (float) z + 0.5F); GL11.glRotatef(-f3, 0.0F, 1.0F, 0.0F); GL11.glTranslatef(0.0F, -0.2500F, -0.4375F); renderScreenBoard(); FontRenderer fontrenderer = this.func_147498_b(); ClientScreenModule.TransformMode mode = ClientScreenModule.TransformMode.NONE; GL11.glDepthMask(false); GL11.glDisable(GL11.GL_LIGHTING); int currenty = 7; for (ClientScreenModule module : modules) { if (module.getTransformMode() != mode) { if (mode != ClientScreenModule.TransformMode.NONE) { GL11.glPopMatrix(); } GL11.glPushMatrix(); mode = module.getTransformMode(); switch (mode) { case TEXT: GL11.glTranslatef(-0.5F, 0.5F, 0.07F); f3 = 0.0075F; GL11.glScalef(f3, -f3, f3); GL11.glNormal3f(0.0F, 0.0F, -1.0F); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); break; case ITEM: f3 = 0.0075F; GL11.glTranslatef(-0.5F, 0.5F, 0.07F); GL11.glScalef(f3, -f3, -0.0001f); break; default: break; } } module.render(fontrenderer, currenty); currenty += module.getHeight(); } if (mode != ClientScreenModule.TransformMode.NONE) { GL11.glPopMatrix(); } GL11.glDepthMask(true); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); GL11.glPopMatrix(); } private void renderScreenBoard() { this.bindTexture(texture); GL11.glPushMatrix(); GL11.glScalef(1, -1, -1); this.screenModel.render(); GL11.glDepthMask(false); Tessellator tessellator = Tessellator.instance; tessellator.startDrawingQuads(); tessellator.setBrightness(240); tessellator.setColorOpaque(0, 0, 0); tessellator.addVertex(-.46f, .46f, -0.08f); tessellator.addVertex(.46f, .46f, -0.08f); tessellator.addVertex(.46f, -.46f, -0.08f); tessellator.addVertex(-.46f, -.46f, -0.08f); tessellator.draw(); GL11.glPopMatrix(); } }
package com.minelittlepony.model.ponies; import com.minelittlepony.model.AbstractPonyModel; import com.minelittlepony.model.BodyPart; import com.minelittlepony.model.armour.ModelPonyArmor; import com.minelittlepony.model.armour.PonyArmor; import com.minelittlepony.model.components.PegasusWings; import com.minelittlepony.model.components.PonySnout; import com.minelittlepony.model.components.PonyTail; import com.minelittlepony.model.components.UnicornHorn; import com.minelittlepony.render.PonyRenderer; import com.minelittlepony.render.plane.PlaneRenderer; import net.minecraft.client.model.ModelRenderer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; import net.minecraft.util.EnumHandSide; import net.minecraft.util.math.MathHelper; import static net.minecraft.client.renderer.GlStateManager.popMatrix; import static net.minecraft.client.renderer.GlStateManager.pushMatrix; import static com.minelittlepony.model.PonyModelConstants.*; public class ModelPlayerPony extends AbstractPonyModel { private final boolean smallArms; public ModelRenderer bipedCape; public PlaneRenderer upperTorso; public PlaneRenderer neck; public PonyRenderer unicornArmRight, unicornArmLeft; public PonyTail tail; public PonySnout snout; public UnicornHorn horn; public PegasusWings wings; public ModelPlayerPony(boolean smallArms) { super(smallArms); this.smallArms = smallArms; } @Override public PonyArmor createArmour() { return new PonyArmor(new ModelPonyArmor(), new ModelPonyArmor()); } @Override public void init(float yOffset, float stretch) { super.init(yOffset, stretch); snout = new PonySnout(this, yOffset, stretch); horn = new UnicornHorn(this, yOffset, stretch); wings = new PegasusWings(this, yOffset, stretch); } @Override public void setRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn) { super.setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scaleFactor, entityIn); this.checkRainboom(entityIn, limbSwingAmount); this.rotateHead(netHeadYaw, headPitch); float bodySwingRotation = 0.0F; if (this.swingProgress > -9990.0F && !this.metadata.hasMagic()) { bodySwingRotation = MathHelper.sin(MathHelper.sqrt(this.swingProgress) * 3.1415927F * 2.0F) * 0.2F; } rotateLook(limbSwing, limbSwingAmount, bodySwingRotation, ageInTicks); setLegs(limbSwing, limbSwingAmount, ageInTicks, entityIn); holdItem(limbSwingAmount); swingItem(entityIn, swingProgress); if (isCrouching() && !rainboom) { adjustBody(BODY_ROTATE_ANGLE_X_SNEAK, BODY_RP_Y_SNEAK, BODY_RP_Z_SNEAK); sneakLegs(); setHead(0, 6, -2); } else if (isRiding) { this.adjustBodyRiding(); bipedLeftLeg.rotationPointZ = 15; bipedLeftLeg.rotationPointY = 10; bipedLeftLeg.rotateAngleX = -PI / 4; bipedLeftLeg.rotateAngleY = -PI / 5; bipedRightLeg.rotationPointZ = 15; bipedRightLeg.rotationPointY = 10; bipedRightLeg.rotateAngleX = -PI / 4; bipedRightLeg.rotateAngleY = PI / 5; bipedLeftArm.rotateAngleZ = -PI * 0.06f; bipedRightArm.rotateAngleZ = PI * 0.06f; } else { adjustBody(BODY_ROTATE_ANGLE_X_NOTSNEAK, BODY_RP_Y_NOTSNEAK, BODY_RP_Z_NOTSNEAK); bipedRightLeg.rotationPointY = FRONT_LEG_RP_Y_NOTSNEAK; bipedLeftLeg.rotationPointY = FRONT_LEG_RP_Y_NOTSNEAK; swingArms(ageInTicks); setHead(0, 0, 0); } if (isSleeping) ponySleep(); aimBow(leftArmPose, rightArmPose, ageInTicks); fixSpecialRotationPoints(limbSwing); animateWears(); if (bipedCape != null) { bipedCape.rotationPointY = isSneak ? 2 : isRiding ? -4 : 0; snout.setGender(metadata.getGender()); wings.setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scaleFactor, entityIn); } } protected void adjustBodyRiding() { adjustBodyComponents(BODY_ROTATE_ANGLE_X_RIDING, BODY_RP_Y_RIDING, BODY_RP_Z_RIDING); adjustNeck(BODY_ROTATE_ANGLE_X_NOTSNEAK, BODY_RP_Y_NOTSNEAK, BODY_RP_Z_NOTSNEAK); setHead(0, 0, 0); } protected void rotateLook(float limbSwing, float limbSwingAmount, float bodySwing, float ticks) { tail.setRotationAndAngles(rainboom, limbSwing, limbSwingAmount, bodySwing, ticks); bodySwing /= 5; upperTorso.rotateAngleY = bodySwing; bipedBody.rotateAngleY = bodySwing; neck.rotateAngleY = bodySwing; } private void animateWears() { copyModelAngles(bipedLeftArm, bipedLeftArmwear); copyModelAngles(bipedRightArm, bipedRightArmwear); copyModelAngles(bipedLeftLeg, bipedLeftLegwear); copyModelAngles(bipedRightLeg, bipedRightLegwear); copyModelAngles(bipedBody, bipedBodyWear); } /** * Checks flying and speed conditions and sets rainboom to true if we're a species with wings and is going faaast. */ protected void checkRainboom(Entity entity, float swing) { rainboom = isFlying(entity) && swing >= 0.9999F; } /** * Sets the head rotation angle. */ protected void setHead(float posX, float posY, float posZ) { bipedHead.setRotationPoint(posX, posY, posZ); bipedHeadwear.setRotationPoint(posX, posY, posZ); } /** * Rotates the head within reason. X is clamped to around motionPitch. * Both arguments are also ignored when sleeping. */ private void rotateHead(float horz, float vert) { float headRotateAngleY = isSleeping ? 1.4f : horz / 57.29578F; float headRotateAngleX = isSleeping ? 0.1f : vert / 57.29578F; headRotateAngleX = Math.min(headRotateAngleX, (float) (0.5f - Math.toRadians(motionPitch))); headRotateAngleX = Math.max(headRotateAngleX, (float) (-1.25f - Math.toRadians(motionPitch))); updateHeadRotation(headRotateAngleX, headRotateAngleY); } /** * Called to update the head rotation. * * @param x New rotation X * @param y New rotation Y */ protected void updateHeadRotation(float x, float y) { bipedHeadwear.rotateAngleY = bipedHead.rotateAngleY = y; bipedHeadwear.rotateAngleX = bipedHead.rotateAngleX = x; } protected void setLegs(float move, float swing, float tick, Entity entity) { rotateLegs(move, swing, tick, entity); adjustLegs(); } protected void rotateLegs(float move, float swing, float tick, Entity entity) { float leftArm, rightArm, leftLeg, rightLeg; if (isFlying(entity)) { if (rainboom) { rightArm = leftArm = ROTATE_270; rightLeg = leftLeg = ROTATE_90; } else { rightArm = leftArm = MathHelper.sin(-swing / 2); rightLeg = leftLeg = MathHelper.sin(swing / 2); } bipedRightArm.rotateAngleY = 0.2F; bipedLeftArm.rotateAngleY = bipedRightLeg.rotateAngleY = -0.2F; bipedLeftLeg.rotateAngleY = 0.2F; } else { float pi = PI * (float) Math.pow(swing, 16); float mve = move * 0.6662F; // magic number ahoy float srt = swing / 4; leftArm = MathHelper.cos(mve + pi) * srt; rightArm = MathHelper.cos(mve + PI + pi / 2) * srt; leftLeg = MathHelper.cos(mve + PI - (pi * 0.4f)) * srt; rightLeg = MathHelper.cos(mve + pi * 0.2f) * srt; bipedLeftArm.rotateAngleY = 0; bipedRightArm.rotateAngleY = 0; bipedLeftLeg.rotateAngleY = 0; bipedRightLeg.rotateAngleY = 0; unicornArmRight.rotateAngleY = 0; unicornArmLeft.rotateAngleY = 0; } bipedLeftArm.rotateAngleX = leftArm; bipedRightArm.rotateAngleX = rightArm; bipedLeftLeg.rotateAngleX = leftLeg; bipedRightLeg.rotateAngleX = rightLeg; bipedLeftArm.rotateAngleZ = 0; bipedRightArm.rotateAngleZ = 0; unicornArmLeft.rotateAngleZ = 0; unicornArmRight.rotateAngleZ = 0; unicornArmLeft.rotateAngleX = 0; unicornArmRight.rotateAngleX = 0; } private float getLegOutset() { if (isSleeping) return 2.6f; if (isSneak && !isFlying) return smallArms ? 1 : 0; return 4; } protected void adjustLegs() { float sin = MathHelper.sin(bipedBody.rotateAngleY) * 5; float cos = MathHelper.cos(bipedBody.rotateAngleY) * 5; float spread = rainboom ? 2 : 1; bipedRightArm.rotationPointZ = spread + sin; bipedLeftArm.rotationPointZ = spread - sin; float legOutset = getLegOutset(); float rpxl = cos + 1 - legOutset; float rpxr = legOutset - cos - 1; bipedRightArm.rotationPointX = rpxr; bipedRightLeg.rotationPointX = rpxr; bipedLeftArm.rotationPointX = rpxl; bipedLeftLeg.rotationPointX = rpxl; // Push the front legs back apart if we're a thin pony if (smallArms) { bipedLeftArm.rotationPointX bipedLeftArm.rotationPointX += 2; } bipedRightArm.rotateAngleY += bipedBody.rotateAngleY; bipedLeftArm.rotateAngleY += bipedBody.rotateAngleY; bipedRightArm.rotationPointY = bipedLeftArm.rotationPointY = 8; bipedRightLeg.rotationPointZ = bipedLeftLeg.rotationPointZ = 10; } protected void holdItem(float swing) { boolean both = leftArmPose == ArmPose.ITEM && rightArmPose == ArmPose.ITEM; if (!rainboom && !metadata.hasMagic()) { alignArmForAction(bipedLeftArm, leftArmPose, both, swing); alignArmForAction(bipedRightArm, rightArmPose, both, swing); } else if (metadata.hasMagic()) { alignArmForAction(unicornArmLeft, leftArmPose, both, swing); alignArmForAction(unicornArmRight, rightArmPose, both, swing); } horn.setUsingMagic(this.leftArmPose != ArmPose.EMPTY || this.rightArmPose != ArmPose.EMPTY); } private void alignArmForAction(ModelRenderer arm, ArmPose pose, boolean both, float swing) { switch (pose) { case ITEM: float swag = 1; if (!isFlying && both) { swag -= (float)Math.pow(swing, 2); } float mult = 1 - swag/2f; arm.rotateAngleX = bipedLeftArm.rotateAngleX * mult - (PI / 10) * swag; case EMPTY: arm.rotateAngleY = 0; break; case BLOCK: blockArm(arm); break; default: } } private void blockArm(ModelRenderer arm) { arm.rotateAngleX = arm.rotateAngleX / 2 - 0.9424779F; arm.rotateAngleY = PI / 6; } protected void swingItem(Entity entity, float swingProgress) { if (swingProgress > -9990.0F && !this.isSleeping) { EnumHandSide mainSide = this.getMainHand(entity); boolean mainRight = mainSide == EnumHandSide.RIGHT; ArmPose mainPose = mainRight ? rightArmPose : leftArmPose; if (mainPose == ArmPose.EMPTY) return; float f16 = 1 - swingProgress; f16 *= f16 * f16; f16 = 1 - f16; float f22 = MathHelper.sin(f16 * PI); float f28 = MathHelper.sin(swingProgress * PI); float f33 = f28 * (0.7F - bipedHead.rotateAngleX) * 0.75F; if (metadata.hasMagic()) { swingArm(mainRight ? unicornArmRight : unicornArmLeft, f22, f33, f28); } else { swingArm(getArmForSide(mainSide), f22, f33, f28); } } } private void swingArm(ModelRenderer arm, float f22, float f33, float f28) { arm.rotateAngleX = (float) (arm.rotateAngleX - (f22 * 1.2D + f33)); arm.rotateAngleY += this.bipedBody.rotateAngleY * 2.0F; arm.rotateAngleZ = f28 * -0.4F; } protected void swingArms(float tick) { float cos = MathHelper.cos(tick * 0.09F) * 0.05F + 0.05F; float sin = MathHelper.sin(tick * 0.067F) * 0.05F; if (this.rightArmPose != ArmPose.EMPTY && !this.isSleeping) { if (this.metadata.hasMagic()) { this.unicornArmRight.rotateAngleZ += cos; this.unicornArmRight.rotateAngleX += sin; } else { this.bipedRightArm.rotateAngleZ += cos; this.bipedRightArm.rotateAngleX += sin; } } if (this.leftArmPose != ArmPose.EMPTY && !this.isSleeping) { if (this.metadata.hasMagic()) { this.unicornArmLeft.rotateAngleZ += cos; this.unicornArmLeft.rotateAngleX += sin; } else { this.bipedLeftArm.rotateAngleZ += cos; this.bipedLeftArm.rotateAngleX += sin; } } } protected void adjustBody(float rotateAngleX, float rotationPointY, float rotationPointZ) { this.adjustBodyComponents(rotateAngleX, rotationPointY, rotationPointZ); this.adjustNeck(rotateAngleX, rotationPointY, rotationPointZ); } protected void adjustBodyComponents(float rotateAngleX, float rotationPointY, float rotationPointZ) { bipedBody.rotateAngleX = rotateAngleX; bipedBody.rotationPointY = rotationPointY; bipedBody.rotationPointZ = rotationPointZ; upperTorso.rotateAngleX = rotateAngleX; upperTorso.rotationPointY = rotationPointY; upperTorso.rotationPointZ = rotationPointZ; } protected void adjustNeck(float rotateAngleX, float rotationPointY, float rotationPointZ) { neck.setRotationPoint(NECK_ROT_X + rotateAngleX, rotationPointY, rotationPointZ); } /** * Aligns legs to a sneaky position. */ protected void sneakLegs() { unicornArmRight.rotateAngleX += SNEAK_LEG_X_ROTATION_ADJUSTMENT; unicornArmLeft.rotateAngleX += SNEAK_LEG_X_ROTATION_ADJUSTMENT; bipedRightArm.rotateAngleX -= SNEAK_LEG_X_ROTATION_ADJUSTMENT; bipedLeftArm.rotateAngleX -= SNEAK_LEG_X_ROTATION_ADJUSTMENT; bipedLeftLeg.rotationPointY = bipedRightLeg.rotationPointY = FRONT_LEG_RP_Y_SNEAK; } protected void ponySleep() { bipedRightArm.rotateAngleX = ROTATE_270; bipedLeftArm.rotateAngleX = ROTATE_270; bipedRightLeg.rotateAngleX = ROTATE_90; bipedLeftLeg.rotateAngleX = ROTATE_90; setHead(1, 2, isSneak ? -1 : 1); shiftRotationPoint(bipedRightArm, 0, 2, 6); shiftRotationPoint(bipedLeftArm, 0, 2, 6); shiftRotationPoint(bipedRightLeg, 0, 2, -8); shiftRotationPoint(bipedLeftLeg, 0, 2, -8); } protected void aimBow(ArmPose leftArm, ArmPose rightArm, float tick) { if (leftArm == ArmPose.BOW_AND_ARROW || rightArm == ArmPose.BOW_AND_ARROW) { if (this.metadata.hasMagic()) { if (rightArm == ArmPose.BOW_AND_ARROW) aimBowPony(unicornArmRight, tick, true); if (leftArm == ArmPose.BOW_AND_ARROW) aimBowPony(unicornArmLeft, tick, false); } else { if (rightArm == ArmPose.BOW_AND_ARROW) aimBowPony(bipedRightArm, tick, false); if (leftArm == ArmPose.BOW_AND_ARROW) aimBowPony(bipedLeftArm, tick, false); } } } protected void aimBowPony(ModelRenderer arm, float tick, boolean shift) { arm.rotateAngleZ = 0; arm.rotateAngleY = bipedHead.rotateAngleY - 0.06F; arm.rotateAngleX = ROTATE_270 + bipedHead.rotateAngleX; arm.rotateAngleZ += MathHelper.cos(tick * 0.09F) * 0.05F + 0.05F; arm.rotateAngleX += MathHelper.sin(tick * 0.067F) * 0.05F; if (shift) shiftRotationPoint(arm, 0, 0, 1); } protected void fixSpecialRotationPoints(float move) { } @Override public void render(Entity entityIn, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scale) { pushMatrix(); transform(BodyPart.HEAD); renderHead(entityIn, limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scale); popMatrix(); pushMatrix(); transform(BodyPart.NECK); renderNeck(); popMatrix(); pushMatrix(); transform(BodyPart.BODY); renderBody(entityIn, limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scale); popMatrix(); pushMatrix(); transform(BodyPart.LEGS); renderLegs(); popMatrix(); } protected void renderHead(Entity entityIn, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scale) { bipedHead.render(scale); bipedHeadwear.render(scale); bipedHead.postRender(scale); horn.render(entityIn, limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scale); } protected void renderNeck() { GlStateManager.scale(0.9, 0.9, 0.9); neck.render(scale); } protected void renderBody(Entity entityIn, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scale) { bipedBody.render(scale); if (textureHeight == 64) { bipedBodyWear.render(scale); } upperTorso.render(scale); bipedBody.postRender(scale); wings.render(entityIn, limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scale); tail.render(metadata.getTail(), scale); } protected void renderLegs() { if (!isSneak) bipedBody.postRender(scale); bipedLeftArm.render(scale); bipedRightArm.render(scale); bipedLeftLeg.render(scale); bipedRightLeg.render(scale); if (textureHeight == 64) { bipedLeftArmwear.render(scale); bipedRightArmwear.render(scale); bipedLeftLegwear.render(scale); bipedRightLegwear.render(scale); } } @Override protected void initTextures() { boxList.clear(); initHeadTextures(); initBodyTextures(); initLegTextures(); tail = new PonyTail(this); } protected void initHeadTextures() { bipedCape = new PonyRenderer(this, 0, 0).size(64, 32); bipedHead = new PonyRenderer(this, 0, 0); bipedHeadwear = new PonyRenderer(this, 32, 0); } protected void initBodyTextures() { bipedBody = new ModelRenderer(this, 16, 16); if (textureHeight == 64) { bipedBodyWear = new ModelRenderer(this, 16, 32); } upperTorso = new PlaneRenderer(this, 24, 0); neck = new PlaneRenderer(this, 0, 16); } protected void initLegTextures() { bipedRightArm = new ModelRenderer(this, 40, 16); bipedRightLeg = new ModelRenderer(this, 0, 16); bipedLeftArm = new ModelRenderer(this, 32, 48); bipedLeftLeg = new ModelRenderer(this, 16, 48); bipedRightArmwear = new ModelRenderer(this, 40, 32); bipedRightLegwear = new ModelRenderer(this, 0, 32); bipedLeftArmwear = new ModelRenderer(this, 48, 48); bipedLeftLegwear = new ModelRenderer(this, 0, 48); unicornArmRight = new PonyRenderer(this, 40, 32).size(64, 64); unicornArmLeft = new PonyRenderer(this, 40, 32).size(64, 64); boxList.remove(unicornArmRight); } @Override protected void initPositions(float yOffset, float stretch) { initHeadPositions(yOffset, stretch); initBodyPositions(yOffset, stretch); initLegPositions(yOffset, stretch); initTailPositions(yOffset, stretch); } protected void initTailPositions(float yOffset, float stretch) { tail.init(yOffset, stretch); } protected void initHeadPositions(float yOffset, float stretch) { bipedCape.addBox(-5.0F, 0.0F, -1.0F, 10, 16, 1, stretch); ((PonyRenderer)bipedHead).offset(HEAD_CENTRE_X, HEAD_CENTRE_Y, HEAD_CENTRE_Z) .around(HEAD_RP_X, HEAD_RP_Y + yOffset, HEAD_RP_Z - 2) .box(-4, -4, -4, 8, 8, 8, stretch) .tex(12, 16) .box(-4, -6, 1, 2, 2, 2, stretch) .mirror() .box(2, -6, 1, 2, 2, 2, stretch); ((PonyRenderer)bipedHeadwear).offset(HEAD_CENTRE_X, HEAD_CENTRE_Y, HEAD_CENTRE_Z) .around(HEAD_RP_X, HEAD_RP_Y + yOffset, HEAD_RP_Z - 2) .box(-4, -4, -4, 8, 8, 8, stretch + 0.5F); } /** * Creates the main torso and neck. */ protected void initBodyPositions(float yOffset, float stretch) { bipedBody.addBox(-4, 4, -2, 8, 8, 4, stretch); bipedBody.setRotationPoint(HEAD_RP_X, HEAD_RP_Y + yOffset, HEAD_RP_Z); bipedBodyWear.addBox(-4, 4, -2, 8, 8, 4, stretch + 0.25F); bipedBodyWear.setRotationPoint(HEAD_RP_X, HEAD_RP_Y + yOffset, HEAD_RP_Z); upperTorso.offset(BODY_CENTRE_X, BODY_CENTRE_Y, BODY_CENTRE_Z) .around(HEAD_RP_X, HEAD_RP_Y + yOffset, HEAD_RP_Z) .tex(24, 0) .addEastPlane( 4, -4, -4, 8, 8, stretch) .tex(56, 0) .addBottomPlane(-4, 4, -4, 8, 8, stretch) .tex(4, 0) .addEastPlane( 4, -4, 4, 8, 4, stretch) .tex(36, 16) .addBackPlane(-4, -4, 8, 8, 4, stretch) .addBackPlane(-4, 0, 8, 8, 4, stretch) .addBottomPlane(-4, 4, 4, 8, 4, stretch) .flipZ().tex(24, 0).addWestPlane(-4, -4, -4, 8, 8, stretch) .tex(32, 20).addTopPlane(-4, -4, -4, 8, 12, stretch) .tex(4, 0) .addWestPlane(-4, -4, 4, 8, 4, stretch) // Tail stub .child(0) .tex(32, 0).addTopPlane(-1, 2, 2, 2, 6, stretch) .addBottomPlane(-1, 4, 2, 2, 6, stretch) .addEastPlane( 1, 2, 2, 2, 6, stretch) .addBackPlane(-1, 2, 8, 2, 2, stretch) .flipZ().addWestPlane(-1, 2, 2, 2, 6, stretch) .rotateAngleX = 0.5F; neck.at(NECK_CENTRE_X, NECK_CENTRE_Y, NECK_CENTRE_Z) .around(HEAD_RP_X, HEAD_RP_Y + yOffset, HEAD_RP_Z) .addFrontPlane(0, 0, 0, 4, 4, stretch) .addBackPlane(0, 0, 4, 4, 4, stretch) .addEastPlane(4, 0, 0, 4, 4, stretch) .addWestPlane(0, 0, 0, 4, 4, stretch) .rotateAngleX = NECK_ROT_X; } protected void initLegPositions(float yOffset, float stretch) { int armWidth = smallArms ? 3 : 4; float rarmY = smallArms ? 8.5f : 8; float rarmX = smallArms ? 2 : 3; float armX = THIRDP_ARM_CENTRE_X - 2; float armY = THIRDP_ARM_CENTRE_Y - 6; float armZ = THIRDP_ARM_CENTRE_Z - 2; bipedLeftArm .addBox(armX, armY, armZ, armWidth, 12, 4, stretch); bipedRightArm.addBox(armX, armY, armZ, armWidth, 12, 4, stretch); bipedLeftLeg .addBox(armX, armY, armZ, 4, 12, 4, stretch); bipedRightLeg.addBox(armX, armY, armZ, 4, 12, 4, stretch); bipedLeftArm .setRotationPoint( rarmX, yOffset + rarmY, 0); bipedRightArm.setRotationPoint(-rarmX, yOffset + rarmY, 0); bipedLeftLeg .setRotationPoint( rarmX, yOffset, 0); bipedRightLeg.setRotationPoint(-rarmX, yOffset, 0); if (bipedLeftArmwear != null) { bipedLeftArmwear.addBox(armX, armY, armZ, 3, 12, 4, stretch + 0.25f); bipedLeftArmwear.setRotationPoint(3, yOffset + rarmY, 0); } if (bipedRightArmwear != null) { bipedRightArmwear.addBox(armX, armY, armZ, armWidth, 12, 4, stretch + 0.25f); bipedRightArmwear.setRotationPoint(-3, yOffset + rarmY, 0); } if (bipedLeftLegwear != null) { bipedLeftLegwear.addBox(armX, armY, armZ, 4, 12, 4, stretch + 0.25f); bipedRightLegwear.setRotationPoint(3, yOffset, 0); } if (bipedRightLegwear != null) { bipedRightLegwear.addBox(armX, armY, armZ, 4, 12, 4, stretch + 0.25f); bipedRightLegwear.setRotationPoint(-3, yOffset, 0); } unicornArmLeft .addBox(FIRSTP_ARM_CENTRE_X - 2, armY, armZ, 4, 12, 4, stretch + .25f); unicornArmRight.addBox(FIRSTP_ARM_CENTRE_X - 2, armY, armZ, 4, 12, 4, stretch + .25f); unicornArmLeft .setRotationPoint(5, yOffset + 2, 0); unicornArmRight.setRotationPoint(-5, yOffset + 2, 0); } @Override public void renderCape(float scale) { bipedCape.render(scale); } }
package com.mitosis.spring5app.bean; import java.util.HashMap; import java.util.Map; import org.apache.kafka.clients.consumer.ConsumerConfig; import org.apache.kafka.common.serialization.StringDeserializer; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.annotation.EnableKafka; import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; import org.springframework.kafka.config.KafkaListenerContainerFactory; import org.springframework.kafka.core.ConsumerFactory; import org.springframework.kafka.core.DefaultKafkaConsumerFactory; import org.springframework.kafka.listener.ConcurrentMessageListenerContainer; /** * * @author root */ //@Configuration //@EnableKafka public class KafkaConsumerConfig { @Value("${brokerList}") private String brokerList; @Bean KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() { ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>(); factory.setConsumerFactory(consumerFactory()); factory.setConcurrency(3); factory.getContainerProperties().setPollTimeout(3000); return factory; } @Bean public ConsumerFactory<String, String> consumerFactory() { return new DefaultKafkaConsumerFactory<>(consumerConfigs()); } @Bean public Map<String, Object> consumerConfigs() { Map<String, Object> propsMap = new HashMap<>(); propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokerList); propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false); propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "100"); propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "15000"); propsMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); propsMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, "mitosis"); propsMap.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); return propsMap; } @Bean public Listener listener() { return new Listener(); } }
package com.redhat.ceylon.compiler.js; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface; import com.redhat.ceylon.compiler.typechecker.model.Declaration; import com.redhat.ceylon.compiler.typechecker.model.Method; import com.redhat.ceylon.compiler.typechecker.model.Module; import com.redhat.ceylon.compiler.typechecker.model.Scope; import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration; /** * Manages the identifier names in the JavaScript code generated for a Ceylon * compilation unit. * * @author Ivo Kasiuk */ public class JsIdentifierNames { private boolean prototypeStyle = false; private static long uniqueID = 0; private static long nextUID() { if (++uniqueID <= 0) { uniqueID = 1; } return uniqueID; } private static Set<String> reservedWords = new HashSet<String>(); static { //reservedWords.add("abstract"); reservedWords.add("boolean"); //reservedWords.add("break"); reservedWords.add("byte"); //reservedWords.add("case"); //reservedWords.add("catch"); reservedWords.add("char"); //reservedWords.add("class"); reservedWords.add("const"); //reservedWords.add("continue"); reservedWords.add("debugger"); reservedWords.add("default"); reservedWords.add("delete"); reservedWords.add("do"); reservedWords.add("double"); //reservedWords.add("else"); reservedWords.add("enum"); reservedWords.add("export"); reservedWords.add("extends"); reservedWords.add("false"); reservedWords.add("final"); //reservedWords.add("finally"); reservedWords.add("float"); //reservedWords.add("for"); //reservedWords.add("function"); reservedWords.add("goto"); //reservedWords.add("if"); reservedWords.add("implements"); //reservedWords.add("import"); //reservedWords.add("in"); reservedWords.add("instanceof"); reservedWords.add("int"); //reservedWords.add("interface"); reservedWords.add("long"); reservedWords.add("native"); reservedWords.add("new"); reservedWords.add("null"); reservedWords.add("package"); reservedWords.add("private"); reservedWords.add("protected"); reservedWords.add("public"); //reservedWords.add("return"); reservedWords.add("short"); reservedWords.add("static"); //reservedWords.add("super"); //reservedWords.add("switch"); reservedWords.add("synchronized"); //reservedWords.add("this"); //reservedWords.add("throw"); reservedWords.add("throws"); reservedWords.add("transient"); reservedWords.add("true"); //reservedWords.add("try"); reservedWords.add("typeof"); reservedWords.add("var"); //reservedWords.add("void"); reservedWords.add("volatile"); //reservedWords.add("while"); reservedWords.add("with"); } public JsIdentifierNames(boolean prototypeStyle) { this.prototypeStyle = prototypeStyle; } /** * Determine the identifier name to be used in the generated JavaScript code * to represent the given declaration. */ public String name(Declaration decl) { return getName(decl, false); } /** * Determine the function name to be used in the generated JavaScript code * for the getter of the given declaration. */ public String getter(Declaration decl) { if (decl == null) { return ""; } String name = getName(decl, true); return String.format("get%c%s", Character.toUpperCase(name.charAt(0)), name.substring(1)); } /** * Determine the function name to be used in the generated JavaScript code * for the setter of the given declaration. */ public String setter(Declaration decl) { String name = getName(decl, true); return String.format("set%c%s", Character.toUpperCase(name.charAt(0)), name.substring(1)); } /** * Determine the identifier to be used in the generated JavaScript code as * an alias for the given package. */ public String moduleAlias(Module pkg) { StringBuilder sb = new StringBuilder("$$$"); for (String s: pkg.getName()) { sb.append(s.substring(0,1)); } sb.append(getUID(pkg)); return sb.toString(); } /** * Creates a new unique identifier. */ public String createTempVariable(String baseName) { return String.format("%s$%d", baseName, nextUID()); } /** * Creates a new unique identifier. */ public String createTempVariable() { return createTempVariable("tmpvar"); } /** * Determine identifier to be used for the self variable of the given type. */ public String self(TypeDeclaration decl) { String name = decl.getName(); if (!(decl.isShared() || decl.isToplevel())) { name = String.format("%s$%d", name, getUID(decl)); } else { name += nestingSuffix(decl); } return String.format("$$%c%s", Character.toLowerCase(name.charAt(0)), name.substring(1)); } /** * Returns a disambiguation suffix for the given type. It is guaranteed that * the suffixes generated for two different types are different. */ public String typeSuffix(TypeDeclaration typeDecl) { return String.format("$$%s$", typeDecl.getQualifiedNameString().replace('.', '$')); } private String nestingSuffix(Declaration decl) { String suffix = ""; if (decl instanceof TypeDeclaration) { StringBuilder sb = new StringBuilder(); Scope scope = decl.getContainer(); while (scope instanceof TypeDeclaration) { sb.append('$'); sb.append(((TypeDeclaration) scope).getName()); scope = scope.getContainer(); } suffix = sb.toString(); } return suffix; } public void forceName(Declaration decl, String name) { uniqueVarNames.put(decl, name); } private Map<Module, Long> moduleUIDs = new HashMap<Module, Long>(); private Map<Declaration, Long> uniqueVarIDs = new HashMap<Declaration, Long>(); private Map<Declaration, String> uniqueVarNames = new HashMap<Declaration, String>(); private String getName(Declaration decl, boolean forGetterSetter) { if (decl == null) { return null; } String name = decl.getName(); if (!((decl.isShared() || decl.isToplevel()) && (forGetterSetter || (decl instanceof Method) || (decl instanceof ClassOrInterface)))) { name = uniqueVarNames.get(decl); if (name == null) { String format = (prototypeStyle && decl.isMember()) ? "%s$%d$" : "%s$%d"; name = String.format(format, decl.getName(), getUID(decl)); } } else { String suffix = nestingSuffix(decl); if (suffix.length() > 0) { name += suffix; } else if (!forGetterSetter && reservedWords.contains(name)) { name = '$' + name; } } return name; } private long getUID(Declaration decl) { Long id = uniqueVarIDs.get(decl); if (id == null) { id = nextUID(); uniqueVarIDs.put(decl, id); } return id; } private long getUID(Module pkg) { Long id = moduleUIDs.get(pkg); if (id == null) { id = nextUID(); moduleUIDs.put(pkg, id); } return id; } }
package com.kii.thingif; import android.content.Context; import android.content.SharedPreferences; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import android.util.Pair; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.WorkerThread; import com.google.gson.JsonParseException; import com.kii.thingif.command.Action; import com.kii.thingif.command.Command; import com.kii.thingif.command.CommandForm; import com.kii.thingif.exception.StoredInstanceNotFoundException; import com.kii.thingif.exception.ThingIFException; import com.kii.thingif.exception.ThingIFRestException; import com.kii.thingif.exception.UnloadableInstanceVersionException; import com.kii.thingif.exception.UnsupportedActionException; import com.kii.thingif.exception.UnsupportedSchemaException; import com.kii.thingif.gateway.EndNode; import com.kii.thingif.gateway.Gateway; import com.kii.thingif.gateway.PendingEndNode; import com.kii.thingif.internal.GsonRepository; import com.kii.thingif.internal.http.IoTRestClient; import com.kii.thingif.internal.http.IoTRestRequest; import com.kii.thingif.schema.Schema; import com.kii.thingif.trigger.ServerCode; import com.kii.thingif.trigger.Predicate; import com.kii.thingif.trigger.Trigger; import com.kii.thingif.internal.utils.JsonUtils; import com.kii.thingif.internal.utils.Path; import com.kii.thingif.trigger.TriggerOptions; import com.kii.thingif.trigger.TriggeredCommandForm; import com.kii.thingif.trigger.TriggeredServerCodeResult; import com.kii.thingif.trigger.TriggersWhat; import com.squareup.okhttp.MediaType; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.text.MessageFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * This class operates an IoT device that is specified by {@link #onboard(String, String, String, JSONObject)} method. */ public class ThingIFAPI<T extends Alias> implements Parcelable { private static final String SHARED_PREFERENCES_KEY_INSTANCE = "ThingIFAPI_INSTANCE"; private static final String SHARED_PREFERENCES_SDK_VERSION_KEY = "ThingIFAPI_VERSION"; private static final String MINIMUM_LOADABLE_SDK_VERSION = "0.13.0"; private static Context context; private final String tag; private final KiiApp app; private final Owner owner; private Target target; private final Map<Pair<String, Integer>, Schema> schemas = new HashMap<Pair<String, Integer>, Schema>(); private final IoTRestClient restClient; private String installationID; /** * Try to load the instance of ThingIFAPI using stored serialized instance. * <BR> * Instance is automatically saved when following methods are called. * <BR> * {@link #onboard(String, String, String, JSONObject)}, {@link #onboard(String, String)}, * {@link #copyWithTarget(Target, String)} * and {@link #installPush} has been successfully completed. * <BR> * (When {@link #copyWithTarget(Target, String)} is called, only the copied instance is saved.) * <BR> * <BR> * * If the ThingIFAPI instance is build without the tag, all instance is saved in same place * and overwritten when the instance is saved. * <BR> * <BR> * * If the ThingIFAPI instance is build with the tag(optional), tag is used as key to distinguish * the storage area to save the instance. This would be useful to saving multiple instance. * You need specify tag to load the instance by the * {@link #loadFromStoredInstance(Context, String) api}. * * When you catch exceptions, please call {@link #onboard(String, String, String, JSONObject)} * for saving or updating serialized instance. * * @param context context * @return ThingIFAPI instance. * @throws StoredInstanceNotFoundException when the instance has not stored yet. * @throws UnloadableInstanceVersionException when the instance couldn't be loaded. */ @NonNull public static ThingIFAPI loadFromStoredInstance(@NonNull Context context) throws StoredInstanceNotFoundException, UnloadableInstanceVersionException { return loadFromStoredInstance(context, null); } /** * Try to load the instance of ThingIFAPI using stored serialized instance. * <BR> * For details please refer to the {@link #loadFromStoredInstance(Context)} document. * * @param context context * @param tag specified when the ThingIFAPI has been built. * @return ThingIFAPI instance. * @throws StoredInstanceNotFoundException when the instance has not stored yet. * @throws UnloadableInstanceVersionException when the instance couldn't be loaded. */ @NonNull public static ThingIFAPI loadFromStoredInstance(@NonNull Context context, String tag) throws StoredInstanceNotFoundException, UnloadableInstanceVersionException { ThingIFAPI.context = context.getApplicationContext(); SharedPreferences preferences = getSharedPreferences(); String serializedJson = preferences.getString(getStoredInstanceKey(tag), null); if (serializedJson == null) { throw new StoredInstanceNotFoundException(tag); } String storedSDKVersion = preferences.getString(getStoredSDKVersionKey(tag), null); if (!isLoadableSDKVersion(storedSDKVersion)) { throw new UnloadableInstanceVersionException(tag, storedSDKVersion, MINIMUM_LOADABLE_SDK_VERSION); } return GsonRepository.gson().fromJson(serializedJson, ThingIFAPI.class); } /** * Clear all saved instances in the SharedPreferences. */ public static void removeAllStoredInstances() { SharedPreferences preferences = getSharedPreferences(); SharedPreferences.Editor editor = preferences.edit(); editor.clear(); editor.apply(); } /** * Remove saved specified instance in the SharedPreferences. * * @param tag tag to specify stored instance. */ public static void removeStoredInstance(@Nullable String tag) { SharedPreferences preferences = getSharedPreferences(); SharedPreferences.Editor editor = preferences.edit(); editor.remove(getStoredSDKVersionKey(tag)); editor.remove(getStoredInstanceKey(tag)); editor.apply(); } private static void saveInstance(ThingIFAPI instance) { SharedPreferences preferences = getSharedPreferences(); if (preferences != null) { SharedPreferences.Editor editor = preferences.edit(); editor.putString(getStoredSDKVersionKey(instance.tag), SDKVersion.versionString); editor.putString(getStoredInstanceKey(instance.tag), GsonRepository.gson().toJson(instance)); editor.apply(); } } private static String getStoredInstanceKey(String tag) { return SHARED_PREFERENCES_KEY_INSTANCE + (tag == null ? "" : "_" +tag); } private static String getStoredSDKVersionKey(String tag) { return SHARED_PREFERENCES_SDK_VERSION_KEY + (tag == null ? "" : "_" +tag); } private static boolean isLoadableSDKVersion(String storedSDKVersion) { if (storedSDKVersion == null) { return false; } String[] actualVersions = storedSDKVersion.split("\\."); if (actualVersions.length != 3) { return false; } String[] minimumLoadableVersions = ThingIFAPI.MINIMUM_LOADABLE_SDK_VERSION.split("\\."); for (int i = 0; i < 3; ++i) { int actual = Integer.parseInt(actualVersions[i]); int expect = Integer.parseInt(minimumLoadableVersions[i]); if (actual < expect) { return false; } else if (actual > expect) { break; } } return true; } ThingIFAPI( @Nullable Context context, @Nullable String tag, @NonNull KiiApp app, @NonNull Owner owner, @Nullable Target target, @NonNull List<Schema> schemas, String installationID) { // Parameters are checked by ThingIFAPIBuilder if (context != null) { ThingIFAPI.context = context.getApplicationContext(); } this.tag = tag; this.app = app; this.owner = owner; this.target = target; for (Schema schema : schemas) { this.schemas.put(new Pair<String, Integer>(schema.getSchemaName(), schema.getSchemaVersion()), schema); } this.installationID = installationID; this.restClient = new IoTRestClient(); } /** * Create the clone instance that has specified target and tag. * * @param target coping target. * @param tag A key to store instnace. * @return ThingIFAPI instance */ public ThingIFAPI copyWithTarget(@NonNull Target target, @Nullable String tag) { if (target == null) { throw new IllegalArgumentException("target is null"); } ThingIFAPI api = new ThingIFAPI(context, tag, this.app, this.owner, target, new ArrayList<Schema>(this.schemas.values()), this.installationID); saveInstance(api); return api; } @NonNull @WorkerThread public Target onboard( @NonNull String vendorThingID, @NonNull String thingPassword, @Nullable String thingType, @Nullable JSONObject thingProperties) throws ThingIFException { OnboardWithVendorThingIDOptions.Builder builder = new OnboardWithVendorThingIDOptions.Builder(); builder.setThingType(thingType).setThingProperties(thingProperties); return onboardWithVendorThingID(vendorThingID, thingPassword, builder.build()); } @NonNull @WorkerThread public Target onboard( @NonNull String vendorThingID, @NonNull String thingPassword, @Nullable OnboardWithVendorThingIDOptions options) throws ThingIFException { return onboardWithVendorThingID(vendorThingID, thingPassword, options); } private Target onboardWithVendorThingID( String vendorThingID, String thingPassword, OnboardWithVendorThingIDOptions options) throws ThingIFException { if (this.onboarded()) { throw new IllegalStateException("This instance is already onboarded."); } if (TextUtils.isEmpty(vendorThingID)) { throw new IllegalArgumentException("vendorThingID is null or empty"); } if (TextUtils.isEmpty(thingPassword)) { throw new IllegalArgumentException("thingPassword is null or empty"); } JSONObject requestBody = new JSONObject(); LayoutPosition layoutPosition = null; try { requestBody.put("vendorThingID", vendorThingID); requestBody.put("thingPassword", thingPassword); if (options != null) { String thingType = options.getThingType(); String firmwareVersion = options.getFirmwareVersion(); JSONObject thingProperties = options.getThingProperties(); layoutPosition = options.getLayoutPosition(); DataGroupingInterval dataGroupingInterval = options.getDataGroupingInterval(); if (thingType != null) { requestBody.put("thingType", thingType); } if (firmwareVersion != null) { requestBody.put("firmwareVersion", firmwareVersion); } if (thingProperties != null && thingProperties.length() > 0) { requestBody.put("thingProperties", thingProperties); } if (layoutPosition != null) { requestBody.put("layoutPosition", layoutPosition.name()); } if (dataGroupingInterval != null) { requestBody.put("dataGroupingInterval", dataGroupingInterval.getInterval()); } } requestBody.put("owner", this.owner.getTypedID().toString()); } catch (JSONException e) { } return this.onboard(MediaTypes.MEDIA_TYPE_ONBOARDING_WITH_VENDOR_THING_ID_BY_OWNER_REQUEST, requestBody, vendorThingID, layoutPosition); } @NonNull @WorkerThread public Target onboard( @NonNull String thingID, @NonNull String thingPassword) throws ThingIFException { return onboardWithThingID(thingID, thingPassword, null); } @NonNull @WorkerThread public Target onboard( @NonNull String thingID, @NonNull String thingPassword, @Nullable OnboardWithThingIDOptions options) throws ThingIFException { return onboardWithThingID(thingID, thingPassword, options); } private Target onboardWithThingID( String thingID, String thingPassword, OnboardWithThingIDOptions options) throws ThingIFException { if (this.onboarded()) { throw new IllegalStateException("This instance is already onboarded."); } if (TextUtils.isEmpty(thingID)) { throw new IllegalArgumentException("thingID is null or empty"); } if (TextUtils.isEmpty(thingPassword)) { throw new IllegalArgumentException("thingPassword is null or empty"); } JSONObject requestBody = new JSONObject(); LayoutPosition layoutPosition = null; try { requestBody.put("thingID", thingID); requestBody.put("thingPassword", thingPassword); requestBody.put("owner", this.owner.getTypedID().toString()); if (options != null) { layoutPosition = options.getLayoutPosition(); DataGroupingInterval dataGroupingInterval = options.getDataGroupingInterval(); if (layoutPosition != null) { requestBody.put("layoutPosition", layoutPosition.name()); } if (dataGroupingInterval != null) { requestBody.put("dataGroupingInterval", dataGroupingInterval.getInterval()); } } } catch (JSONException e) { } // FIXME: Currently, Server does not return the VendorThingID when onboarding is successful. return this.onboard(MediaTypes.MEDIA_TYPE_ONBOARDING_WITH_THING_ID_BY_OWNER_REQUEST, requestBody, null, layoutPosition); } private Target onboard(MediaType contentType, JSONObject requestBody, String vendorThingID, LayoutPosition layoutPosition) throws ThingIFException { String path = MessageFormat.format("/thing-if/apps/{0}/onboardings", this.app.getAppID()); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers, contentType, requestBody); JSONObject responseBody = this.restClient.sendRequest(request); String thingID = responseBody.optString("thingID", null); String accessToken = responseBody.optString("accessToken", null); if (layoutPosition == LayoutPosition.GATEWAY) { this.target = new Gateway(thingID, vendorThingID); } else if (layoutPosition == LayoutPosition.ENDNODE) { this.target = new EndNode(thingID, vendorThingID, accessToken); } else { this.target = new StandaloneThing(thingID, vendorThingID, accessToken); } saveInstance(this); return this.target; } public EndNode onboardEndnodeWithGateway( @NonNull PendingEndNode pendingEndNode, @NonNull String endnodePassword) throws ThingIFException { return onboardEndNodeWithGateway(pendingEndNode, endnodePassword, null); } public EndNode onboardEndnodeWithGateway( @NonNull PendingEndNode pendingEndNode, @NonNull String endnodePassword, @Nullable OnboardEndnodeWithGatewayOptions options) throws ThingIFException { return onboardEndNodeWithGateway(pendingEndNode, endnodePassword, options); } private EndNode onboardEndNodeWithGateway( PendingEndNode pendingEndNode, String endnodePassword, @Nullable OnboardEndnodeWithGatewayOptions options) throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding the gateway"); } if (this.target instanceof EndNode) { throw new IllegalStateException("Target must be Gateway"); } if (pendingEndNode == null) { throw new IllegalArgumentException("pendingEndNode is null or empty"); } if (TextUtils.isEmpty(pendingEndNode.getVendorThingID())) { throw new IllegalArgumentException("vendorThingID is null or empty"); } if (TextUtils.isEmpty(endnodePassword)) { throw new IllegalArgumentException("endnodePassword is null or empty"); } JSONObject requestBody = new JSONObject(); try { requestBody.put("gatewayThingID", this.target.getTypedID().getID()); requestBody.put("endNodeVendorThingID", pendingEndNode.getVendorThingID()); requestBody.put("endNodePassword", endnodePassword); if (!TextUtils.isEmpty(pendingEndNode.getThingType())) { requestBody.put("endNodeThingType", pendingEndNode.getThingType()); } if (pendingEndNode.getThingProperties() != null && pendingEndNode.getThingProperties().length() > 0) { requestBody.put("endNodeThingProperties", pendingEndNode.getThingProperties()); } if (options != null) { DataGroupingInterval dataGroupingInterval = options.getDataGroupingInterval(); if (dataGroupingInterval != null) { requestBody.put("dataGroupingInterval", dataGroupingInterval.getInterval()); } } requestBody.put("owner", this.owner.getTypedID().toString()); } catch (JSONException e) { } String path = MessageFormat.format("/thing-if/apps/{0}/onboardings", this.app.getAppID()); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers, MediaTypes.MEDIA_TYPE_ONBOARDING_ENDNODE_WITH_GATEWAY_THING_ID_REQUEST, requestBody); JSONObject responseBody = this.restClient.sendRequest(request); String thingID = responseBody.optString("endNodeThingID", null); String accessToken = responseBody.optString("accessToken", null); return new EndNode(thingID, pendingEndNode.getVendorThingID(), accessToken); } /** * Checks whether on boarding is done. * @return true if done, otherwise false. */ public boolean onboarded() { return this.target != null; } /** * Install push notification to receive notification from IoT Cloud. This will install on production environment. * IoT Cloud will send notification when the Target replies to the Command. * Application can receive the notification and check the result of Command * fired by Application or registered Trigger. * After installation is done Installation ID is managed in this class. * @param deviceToken for GCM, specify token obtained by * InstanceID.getToken(). * for JPUSH, specify id obtained by * JPushInterface.getUdid(). * @param pushBackend Specify backend to use. * @return Installation ID used in IoT Cloud. * @throws ThingIFException Thrown when failed to connect IoT Cloud Server. * @throws ThingIFRestException Thrown when server returns error response. * @see #installPush(String, PushBackend, boolean) for development/production environment installation. */ @NonNull @WorkerThread public String installPush( @Nullable String deviceToken, @NonNull PushBackend pushBackend ) throws ThingIFException { return this.installPush(deviceToken, pushBackend, false); } /** * Install push notification to receive notification from IoT Cloud. * IoT Cloud will send notification when the Target replies to the Command. * Application can receive the notification and check the result of Command * fired by Application or registered Trigger. * After installation is done Installation ID is managed in this class. * @param deviceToken for GCM, specify token obtained by * InstanceID.getToken(). * for JPUSH, specify id obtained by * JPushInterface.getUdid(). * @param pushBackend Specify backend to use. * @param development Specify development flag to use. Indicates if the installation is for development or production environment. * @return Installation ID used in IoT Cloud. * @throws ThingIFException Thrown when failed to connect IoT Cloud Server. * @throws ThingIFRestException Thrown when server returns error response. */ @NonNull @WorkerThread public String installPush( @Nullable String deviceToken, @NonNull PushBackend pushBackend, boolean development ) throws ThingIFException{ if (pushBackend == null) { throw new IllegalArgumentException("pushBackend is null"); } String path = MessageFormat.format("/api/apps/{0}/installations", this.app.getAppID()); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); JSONObject requestBody = new JSONObject(); try { if (!TextUtils.isEmpty(deviceToken)) { requestBody.put("installationRegistrationID", deviceToken); } if (development){ requestBody.put("development", true); } requestBody.put("deviceType", pushBackend.getDeviceType()); } catch (JSONException e) { } IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers, MediaTypes.MEDIA_TYPE_INSTALLATION_CREATION_REQUEST, requestBody); JSONObject responseBody = this.restClient.sendRequest(request); this.installationID = responseBody.optString("installationID", null); saveInstance(this); return this.installationID; } /** * Get installationID if the push is already installed. * null will be returned if the push installation has not been done. * @return Installation ID used in IoT Cloud. */ @Nullable public String getInstallationID() { return this.installationID; } /** * Uninstall push notification. * After done, notification from IoT Cloud won't be notified. * @param installationID installation ID returned from * {@link #installPush(String, PushBackend)} * if null is specified, value obtained by * {@link #getInstallationID()} is used. * @throws ThingIFException Thrown when failed to connect IoT Cloud Server. * @throws ThingIFRestException Thrown when server returns error response. */ @NonNull @WorkerThread public void uninstallPush(@NonNull String installationID) throws ThingIFException { if (installationID == null) { throw new IllegalArgumentException("installationID is null"); } String path = MessageFormat.format("/api/apps/{0}/installations/{1}", this.app.getAppID(), installationID); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.DELETE, headers); this.restClient.sendRequest(request); } /** * Post new command to IoT Cloud. * Command will be delivered to specified target and result will be notified * through push notification. * @param form form of command. It contains name of schema, version of * schema, list of actions etc. * @return Created Command instance. At this time, Command is delivered to * the target Asynchronously and may not finished. Actual Result will be * delivered through push notification or you can check the latest status * of the command by calling {@link #getCommand}. * @throws ThingIFException Thrown when failed to connect IoT Cloud Server. * @throws ThingIFRestException Thrown when server returns error response. */ @NonNull @WorkerThread public Command postNewCommand( @NonNull CommandForm<T> form) throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/commands", this.app.getAppID(), this.target.getTypedID().toString()); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); JSONObject requestBody = createPostNewCommandRequestBody(form); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers, MediaTypes.MEDIA_TYPE_JSON, requestBody); JSONObject responseBody = this.restClient.sendRequest(request); String commandID = responseBody.optString("commandID", null); return this.getCommand(commandID); } /** * Get specified command. * @param commandID ID of the command to obtain. ID is present in the * instance returned by {@link #postNewCommand} * and can be obtained by {@link Command#getCommandID} * * @return Command instance. * @throws ThingIFException Thrown when failed to connect IoT Cloud Server. * @throws ThingIFRestException Thrown when server returns error response. * @throws UnsupportedSchemaException Thrown when the returned response has a schema that cannot handle this instance. * @throws UnsupportedActionException Thrown when the returned response has a action that cannot handle this instance. */ @NonNull @WorkerThread public Command getCommand( @NonNull String commandID) throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } if (TextUtils.isEmpty(commandID)) { throw new IllegalArgumentException("commandID is null or empty"); } String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/commands/{2}", this.app.getAppID(), this.target.getTypedID().toString(), commandID); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers); JSONObject responseBody = this.restClient.sendRequest(request); String schemaName = responseBody.optString("schema", null); int schemaVersion = responseBody.optInt("schemaVersion"); Schema schema = this.getSchema(schemaName, schemaVersion); if (schema == null) { throw new UnsupportedSchemaException(schemaName, schemaVersion); } //TODO: // FIXME: 12/16/16 return this.deserialize(schema, responseBody, Command.class); } /** * List Commands in the specified Target.<br> * If the Schema of the Command included in the response does not matches with the Schema * registered this ThingIfAPI instance, It won't be included in returned value. * @param bestEffortLimit Maximum number of the Commands in the response. * if the value is {@literal <}= 0, default limit internally * defined is applied. * Meaning of 'bestEffort' is if the specified limit * is greater than default limit, default limit is * applied. * @param paginationKey Used to get the next page of previously obtained. * If there is further page to obtain, this method * returns paginationKey as the 2nd element of pair. * Applying this key to the argument results continue * to get the result from the next page. * @return 1st Element is Commands belongs to the Target. 2nd element is * paginationKey if there is next page to be obtained. * @throws ThingIFException Thrown when failed to connect IoT Cloud Server. * @throws ThingIFRestException Thrown when server returns error response. * @throws UnsupportedActionException Thrown when the returned response has a action that cannot handle this instance. */ @NonNull public Pair<List<Command>, String> listCommands ( int bestEffortLimit, @Nullable String paginationKey) throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/commands", this.app.getAppID(), this.target.getTypedID().toString()); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers); if (bestEffortLimit > 0) { request.addQueryParameter("bestEffortLimit", bestEffortLimit); } if (!TextUtils.isEmpty(paginationKey)) { request.addQueryParameter("paginationKey", paginationKey); } JSONObject responseBody = this.restClient.sendRequest(request); String nextPaginationKey = responseBody.optString("nextPaginationKey", null); JSONArray commandArray = responseBody.optJSONArray("commands"); List<Command> commands = new ArrayList<Command>(); if (commandArray != null) { for (int i = 0; i < commandArray.length(); i++) { JSONObject commandJson = commandArray.optJSONObject(i); String schemaName = commandJson.optString("schema", null); int schemaVersion = commandJson.optInt("schemaVersion"); Schema schema = this.getSchema(schemaName, schemaVersion); if (schema == null) { continue; } commands.add(this.deserialize(schema, commandJson, Command.class)); } } return new Pair<List<Command>, String>(commands, nextPaginationKey); } @NonNull @WorkerThread public Trigger postNewTrigger( @NonNull TriggeredCommandForm<T> form, @NonNull Predicate predicate, @Nullable TriggerOptions options) throws ThingIFException { return postNewTriggerWithForm(form, predicate, options); } private Trigger postNewTriggerWithForm( @NonNull TriggeredCommandForm<T> form, @NonNull Predicate predicate, @Nullable TriggerOptions options) throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } if (form == null) { throw new IllegalArgumentException("form is null."); } if (predicate == null) { throw new IllegalArgumentException("predicate is null."); } JSONObject requestBody = options != null ? JsonUtils.newJson(GsonRepository.gson().toJson(options)) : new JSONObject(); try { requestBody.put("triggersWhat", TriggersWhat.COMMAND.name()); requestBody.put("predicate", JsonUtils.newJson( GsonRepository.gson().toJson(predicate))); //TODO: // FIXME: 12/15/16 fix the parse code JSONObject command = JsonUtils.newJson( GsonRepository.gson( ).toJson(form)); command.put("issuer", this.owner.getTypedID()); if (form.getTargetID() == null) { command.put("target", this.target.getTypedID().toString()); } requestBody.put("command", command); } catch (JSONException e) { // Won't happen. // TODO: remove this after test finished. throw new RuntimeException(e); } return postNewTrigger(requestBody); } /** * Post new Trigger with server code to IoT Cloud. * * @param serverCode Specify server code you want to execute. * @param predicate Specify when the Trigger fires command. * @param options option fileds of this trigger. * @return Instance of the Trigger registered in IoT Cloud. * @throws ThingIFException Thrown when failed to connect IoT Cloud Server. * @throws ThingIFRestException Thrown when server returns error response. */ @NonNull @WorkerThread public Trigger postNewTrigger( @NonNull ServerCode serverCode, @NonNull Predicate predicate, @Nullable TriggerOptions options) throws ThingIFException { return postServerCodeNewTrigger(serverCode, predicate, options); } /** * Post new Trigger with server code to IoT Cloud. * * <p> * Limited version of {@link #postNewTrigger(ServerCode, Predicate, * TriggerOptions)}. This method can not be set title, description and * metadata of {@link Trigger}. * </p> * * @param serverCode Specify server code you want to execute. * @param predicate Specify when the Trigger fires command. * @return Instance of the Trigger registered in IoT Cloud. * @throws ThingIFException Thrown when failed to connect IoT Cloud Server. * @throws ThingIFRestException Thrown when server returns error response. */ @NonNull @WorkerThread public Trigger postNewTrigger( @NonNull ServerCode serverCode, @NonNull Predicate predicate) throws ThingIFException { return postServerCodeNewTrigger(serverCode, predicate, null); } @NonNull @WorkerThread private Trigger postServerCodeNewTrigger( @NonNull ServerCode serverCode, @NonNull Predicate predicate, @Nullable TriggerOptions options) throws ThingIFException { if (this.target == null) { throw new IllegalStateException( "Can not perform this action before onboarding"); } if (serverCode == null) { throw new IllegalArgumentException("serverCode is null"); } if (predicate == null) { throw new IllegalArgumentException("predicate is null"); } JSONObject requestBody = options != null ? JsonUtils.newJson(GsonRepository.gson().toJson(options)) : new JSONObject(); try { requestBody.put("predicate", JsonUtils.newJson(GsonRepository.gson().toJson(predicate))); requestBody.put("triggersWhat", TriggersWhat.SERVER_CODE.name()); requestBody.put("serverCode", JsonUtils.newJson(GsonRepository.gson().toJson(serverCode))); } catch (JSONException e) { // Won't happen } return this.postNewTrigger(requestBody); } private Trigger postNewTrigger(@NonNull JSONObject requestBody) throws ThingIFException { String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/triggers", this.app.getAppID(), this.target.getTypedID().toString()); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.POST, headers, MediaTypes.MEDIA_TYPE_JSON, requestBody); JSONObject responseBody = this.restClient.sendRequest(request); String triggerID = responseBody.optString("triggerID", null); return this.getTrigger(triggerID); } /** * Get specified Trigger. * @param triggerID ID of the Trigger to get. * @return Trigger instance. * @throws ThingIFException Thrown when failed to connect IoT Cloud Server. * @throws ThingIFRestException Thrown when server returns error response. * @throws UnsupportedSchemaException Thrown when the returned response has a schema that cannot handle this instance. * @throws UnsupportedActionException Thrown when the returned response has a action that cannot handle this instance. */ @NonNull @WorkerThread public Trigger getTrigger( @NonNull String triggerID) throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } if (TextUtils.isEmpty(triggerID)) { throw new IllegalArgumentException("triggerID is null or empty"); } String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/triggers/{2}", this.app.getAppID(), this.target.getTypedID().toString(), triggerID); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers); JSONObject responseBody = this.restClient.sendRequest(request); Schema schema = null; JSONObject commandObject = responseBody.optJSONObject("command"); if (commandObject != null) { String schemaName = commandObject.optString("schema", null); int schemaVersion = commandObject.optInt("schemaVersion"); schema = this.getSchema(schemaName, schemaVersion); if (schema == null) { throw new UnsupportedSchemaException(schemaName, schemaVersion); } } return this.deserialize(schema, responseBody, this.target.getTypedID()); } @NonNull @WorkerThread public Trigger patchTrigger( @NonNull String triggerID, @Nullable TriggeredCommandForm<T> form, @Nullable Predicate predicate, @Nullable TriggerOptions options) throws ThingIFException { return patchTriggerWithForm(triggerID, form, predicate, options); } @NonNull @WorkerThread private Trigger patchTriggerWithForm( @NonNull String triggerID, @Nullable TriggeredCommandForm<T> form, @Nullable Predicate predicate, @Nullable TriggerOptions options) throws ThingIFException { if (this.target == null) { throw new IllegalStateException( "Can not perform this action before onboarding"); } if (TextUtils.isEmpty(triggerID)) { throw new IllegalArgumentException("triggerID is null or empty"); } if (form == null && predicate == null && options == null) { throw new IllegalArgumentException( "All of form, predicate and options are null."); } JSONObject requestBody = null; try { if (options != null) { requestBody = JsonUtils.newJson(GsonRepository.gson().toJson(options)); } else { requestBody = new JSONObject(); } requestBody.put("triggersWhat", TriggersWhat.COMMAND.name()); if (predicate != null) { requestBody.put("predicate", JsonUtils.newJson( GsonRepository.gson().toJson(predicate))); } if (form != null) { //TODO: // FIXME: 12/15/16 need to fix parse code JSONObject command = JsonUtils.newJson( GsonRepository.gson( ).toJson(form)); command.put("issuer", this.owner.getTypedID()); if (form.getTargetID() == null) { command.put("target", this.target.getTypedID().toString()); } requestBody.put("command", command); } } catch (JSONException e) { // Won't happen } return this.patchTrigger(triggerID, requestBody); } @NonNull @WorkerThread public Trigger patchTrigger( @NonNull String triggerID, @Nullable ServerCode serverCode, @Nullable Predicate predicate, @Nullable TriggerOptions options) throws ThingIFException { return patchServerCodeTrigger(triggerID, serverCode, predicate, options); } @NonNull @WorkerThread public Trigger patchTrigger( @NonNull String triggerID, @Nullable ServerCode serverCode, @Nullable Predicate predicate) throws ThingIFException { if (serverCode == null && predicate == null) { throw new IllegalArgumentException( "serverCode and predicate are null."); } return patchServerCodeTrigger(triggerID, serverCode, predicate, null); } @NonNull @WorkerThread private Trigger patchServerCodeTrigger( @NonNull String triggerID, @Nullable ServerCode serverCode, @Nullable Predicate predicate, @Nullable TriggerOptions options) throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } if (TextUtils.isEmpty(triggerID)) { throw new IllegalArgumentException("triggerID is null or empty"); } if (serverCode == null && predicate == null && options == null) { throw new IllegalArgumentException( "serverCode, predicate and options are null."); } JSONObject requestBody = null; try { if (options != null) { requestBody = JsonUtils.newJson( GsonRepository.gson().toJson(options)); } else { requestBody = new JSONObject(); } if (predicate != null) { requestBody.put("predicate", JsonUtils.newJson( GsonRepository.gson().toJson(predicate))); } if (serverCode != null) { requestBody.put("serverCode", JsonUtils.newJson( GsonRepository.gson().toJson(serverCode))); } requestBody.put("triggersWhat", TriggersWhat.SERVER_CODE.name()); } catch (JSONException e) { // Won't happen } return this.patchTrigger(triggerID, requestBody); } private Trigger patchTrigger(@NonNull String triggerID, @NonNull JSONObject requestBody) throws ThingIFException { String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/triggers/{2}", this.app.getAppID(), this.target.getTypedID().toString(), triggerID); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.PATCH, headers, MediaTypes.MEDIA_TYPE_JSON, requestBody); this.restClient.sendRequest(request); return this.getTrigger(triggerID); } /** * Enable/Disable registered Trigger * If its already enabled(/disabled), * this method won't throw Exception and behave as succeeded. * @param triggerID ID of the Trigger to be enabled(/disabled). * @param enable specify whether enable of disable the Trigger. * @return Updated Trigger Instance. * @throws ThingIFException Thrown when failed to connect IoT Cloud Server. * @throws ThingIFRestException Thrown when server returns error response. */ @NonNull @WorkerThread public Trigger enableTrigger( @NonNull String triggerID, boolean enable) throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } if (TextUtils.isEmpty(triggerID)) { throw new IllegalArgumentException("triggerID is null or empty"); } String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/triggers/{2}/{3}", this.app.getAppID(), this.target.getTypedID().toString(), triggerID, (enable ? "enable" : "disable")); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.PUT, headers); this.restClient.sendRequest(request); return this.getTrigger(triggerID); } /** * Delete the specified Trigger. * @param triggerID ID of the Trigger to be deleted. * @return Deleted Trigger Id. * @throws ThingIFException Thrown when failed to connect IoT Cloud Server. * @throws ThingIFRestException Thrown when server returns error response. */ @NonNull @WorkerThread public String deleteTrigger( @NonNull String triggerID) throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } if (TextUtils.isEmpty(triggerID)) { throw new IllegalArgumentException("triggerID is null or empty"); } String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/triggers/{2}", this.app.getAppID(), target.getTypedID().toString(), triggerID); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.DELETE, headers); this.restClient.sendRequest(request); return triggerID; } /** * Retrieves list of server code results that was executed by the specified trigger. Results will be listing with order by modified date descending (latest first) * @param triggerID trigger ID to retrieve server code results. * @param bestEffortLimit limit the maximum number of the results in the * Response. It ensures numbers in * response is equals to or less than specified number. * But doesn't ensures number of the results * in the response is equal to specified value.<br> * If the specified value {@literal <}= 0, Default size of the limit * is applied by IoT Cloud. * @param paginationKey If specified obtain rest of the items. * @return first is list of the results and second is paginationKey returned * by IoT Cloud. paginationKey is null when there is next page to be obtained. * Obtained paginationKey can be used to get the rest of the items stored * in the target. * @throws ThingIFException Thrown when failed to connect IoT Cloud Server. * @throws ThingIFRestException Thrown when server returns error response. */ @NonNull @WorkerThread public Pair<List<TriggeredServerCodeResult>, String> listTriggeredServerCodeResults ( @NonNull String triggerID, int bestEffortLimit, @Nullable String paginationKey ) throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } if (TextUtils.isEmpty(triggerID)) { throw new IllegalArgumentException("triggerID is null or empty"); } String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/triggers/{2}/results/server-code", this.app.getAppID(), this.target.getTypedID().toString(), triggerID); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers); if (bestEffortLimit > 0) { request.addQueryParameter("bestEffortLimit", bestEffortLimit); } if (!TextUtils.isEmpty(paginationKey)) { request.addQueryParameter("paginationKey", paginationKey); } JSONObject responseBody = this.restClient.sendRequest(request); String nextPaginationKey = responseBody.optString("nextPaginationKey", null); JSONArray resultArray = responseBody.optJSONArray("triggerServerCodeResults"); List<TriggeredServerCodeResult> results = new ArrayList<TriggeredServerCodeResult>(); if (resultArray != null) { for (int i = 0; i < resultArray.length(); i++) { JSONObject resultJson = resultArray.optJSONObject(i); results.add(this.deserialize(resultJson, TriggeredServerCodeResult.class)); } } return new Pair<List<TriggeredServerCodeResult>, String>(results, nextPaginationKey); } /** * List Triggers belongs to the specified Target.<br> * If the Schema of the Trigger included in the response does not matches with the Schema * registered this ThingIfAPI instance, It won't be included in returned value. * @param bestEffortLimit limit the maximum number of the Triggers in the * Response. It ensures numbers in * response is equals to or less than specified number. * But doesn't ensures number of the Triggers * in the response is equal to specified value.<br> * If the specified value {@literal <}= 0, Default size of the limit * is applied by IoT Cloud. * @param paginationKey If specified obtain rest of the items. * @return first is list of the Triggers and second is paginationKey returned * by IoT Cloud. paginationKey is null when there is next page to be obtained. * Obtained paginationKey can be used to get the rest of the items stored * in the target. * @throws ThingIFException Thrown when failed to connect IoT Cloud Server. * @throws ThingIFRestException Thrown when server returns error response. * @throws UnsupportedActionException Thrown when the returned response has a action that cannot handle this instance. */ @NonNull @WorkerThread public Pair<List<Trigger>, String> listTriggers( int bestEffortLimit, @Nullable String paginationKey) throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/triggers", this.app.getAppID(), this.target.getTypedID().toString()); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers); if (bestEffortLimit > 0) { request.addQueryParameter("bestEffortLimit", bestEffortLimit); } if (!TextUtils.isEmpty(paginationKey)) { request.addQueryParameter("paginationKey", paginationKey); } JSONObject responseBody = this.restClient.sendRequest(request); String nextPaginationKey = responseBody.optString("nextPaginationKey", null); JSONArray triggerArray = responseBody.optJSONArray("triggers"); List<Trigger> triggers = new ArrayList<Trigger>(); if (triggerArray != null) { for (int i = 0; i < triggerArray.length(); i++) { JSONObject triggerJson = triggerArray.optJSONObject(i); JSONObject commandJson = triggerJson.optJSONObject("command"); Schema schema = null; if (commandJson != null) { String schemaName = commandJson.optString("schema", null); int schemaVersion = commandJson.optInt("schemaVersion"); schema = this.getSchema(schemaName, schemaVersion); if (schema == null) { continue; } } triggers.add(this.deserialize(schema, triggerJson, this.target.getTypedID())); } } return new Pair<List<Trigger>, String>(triggers, nextPaginationKey); } /** * Get the State of specified Target. * State will be serialized with Gson library. * @param classOfS Specify class of the State. * @param <S> State class. * @return Instance of Target State. * @throws ThingIFException Thrown when failed to connect IoT Cloud Server. * @throws ThingIFRestException Thrown when server returns error response. */ @NonNull @WorkerThread public <S extends TargetState> S getTargetState( @NonNull Class<S> classOfS) throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } if (classOfS == null) { throw new IllegalArgumentException("classOfS is null"); } String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/states", this.app.getAppID(), this.target.getTypedID().toString()); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers); JSONObject responseBody = this.restClient.sendRequest(request); S ret = GsonRepository.gson().fromJson(responseBody.toString(), classOfS); return ret; } /** * Get the Vendor Thing ID of specified Target. * * @return Vendor Thing ID * @throws ThingIFException Thrown when failed to connect IoT Cloud Server. */ @NonNull @WorkerThread public String getVendorThingID() throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } String path = MessageFormat.format("/api/apps/{0}/things/{1}/vendor-thing-id", this.app.getAppID(), this.target.getTypedID().getID()); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers); JSONObject responseBody = this.restClient.sendRequest(request); return responseBody.optString("_vendorThingID", null); } /** * Update the Vendor Thing ID of specified Target. * * @param newVendorThingID New vendor thing id * @param newPassword New password * @throws ThingIFException Thrown when failed to connect IoT Cloud Server. */ @WorkerThread public void updateVendorThingID(@NonNull String newVendorThingID, @NonNull String newPassword) throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } if (TextUtils.isEmpty(newPassword)) { throw new IllegalArgumentException("newPassword is null or empty"); } if (TextUtils.isEmpty(newVendorThingID)) { throw new IllegalArgumentException("newVendorThingID is null or empty"); } JSONObject requestBody = new JSONObject(); try { requestBody.put("_vendorThingID", newVendorThingID); requestBody.put("_password", newPassword); } catch (JSONException e) { } String path = MessageFormat.format("/api/apps/{0}/things/{1}/vendor-thing-id", this.app.getAppID(), this.target.getTypedID().getID()); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.PUT, headers, MediaTypes.MEDIA_TYPE_VENDOR_THING_ID_UPDATE_REQUEST, requestBody); this.restClient.sendRequest(request); } /** Get Kii App * @return Kii Cloud Application. */ @NonNull public KiiApp getApp() { return this.app; } /** * Get AppID * @return app ID */ @NonNull public String getAppID() { return this.app.getAppID(); } /** * Get AppKey * @return app key */ @NonNull public String getAppKey() { return this.app.getAppKey(); } /** * Get base URL * @return base URL */ @NonNull public String getBaseUrl() { return this.app.getBaseUrl(); } /** * Get list of schema. * @return list of schema. */ @NonNull public List<Schema> getSchemas() { return new ArrayList<Schema>(this.schemas.values()); } /** * Get owner who uses the ThingIFAPI. * @return owner */ @NonNull public Owner getOwner() { return this.owner; } /** * Get target thing that is operated by the ThingIFAPI. * @return target of this ThingIFAPI. */ @Nullable public Target getTarget() { return this.target; } /** * Get a tag. * @return tag. */ @Nullable public String getTag() { return this.tag; } @Nullable private Schema getSchema(String schemaName, int schemaVersion) { return this.schemas.get(new Pair<String, Integer>(schemaName, schemaVersion)); } private Map<String, String> newHeader() { Map<String, String> headers = new HashMap<String, String>(); if (!TextUtils.isEmpty(this.getAppID())) { headers.put("X-Kii-AppID", this.getAppID()); } if (!TextUtils.isEmpty(this.getAppKey())) { headers.put("X-Kii-AppKey", this.getAppKey()); } if (this.owner != null && !TextUtils.isEmpty(this.owner.getAccessToken())) { headers.put("Authorization", "Bearer " + this.owner.getAccessToken()); } return headers; } private JSONObject createPostNewCommandRequestBody(CommandForm src) throws ThingIFException { JSONObject ret = JsonUtils.newJson(GsonRepository.gson().toJson(src)); try { ret.put("issuer", this.owner.getTypedID().toString()); } catch (JSONException e) { throw new AssertionError(e); } return ret; } private <T> T deserialize(JSONObject json, Class<T> clazz) throws ThingIFException { return this.deserialize(null, json, clazz); } private <T> T deserialize(Schema schema, JSONObject json, Class<T> clazz) throws ThingIFException { return this.deserialize(schema, json.toString(), clazz); } private Trigger deserialize(Schema schema, JSONObject json, TypedID targetID) throws ThingIFException { JSONObject copied = null; try { copied = new JSONObject(json.toString()); copied.put("targetID", targetID.toString()); } catch (JSONException e) { throw new ThingIFException("unexpected error.", e); } return this.deserialize(schema, copied.toString(), Trigger.class); } private <T> T deserialize(Schema schema, String json, Class<T> clazz) throws ThingIFException { try { return GsonRepository.gson(schema).fromJson(json, clazz); } catch (JsonParseException e) { if (e.getCause() instanceof ThingIFException) { throw (ThingIFException)e.getCause(); } throw e; } } private static SharedPreferences getSharedPreferences() { if (context != null) { return context.getSharedPreferences("com.kii.thingif.preferences", Context.MODE_PRIVATE); } return null; } // Implementation of Parcelable protected ThingIFAPI(Parcel in) { this.tag = in.readString(); this.app = in.readParcelable(KiiApp.class.getClassLoader()); this.owner = in.readParcelable(Owner.class.getClassLoader()); this.target = in.readParcelable(Target.class.getClassLoader()); ArrayList<Schema> schemas = in.createTypedArrayList(Schema.CREATOR); for (Schema schema : schemas) { this.schemas.put(new Pair<String, Integer>(schema.getSchemaName(), schema.getSchemaVersion()), schema); } this.restClient = new IoTRestClient(); this.installationID = in.readString(); } public static final Creator<ThingIFAPI> CREATOR = new Creator<ThingIFAPI>() { @Override public ThingIFAPI createFromParcel(Parcel in) { return new ThingIFAPI(in); } @Override public ThingIFAPI[] newArray(int size) { return new ThingIFAPI[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.tag); dest.writeParcelable(this.app, flags); dest.writeParcelable(this.owner, flags); dest.writeParcelable(this.target, flags); dest.writeTypedList(new ArrayList<Schema>(this.schemas.values())); dest.writeString(this.installationID); } /** * Get version of the SDK. * @return Version string. */ @NonNull public static String getSDKVersion() { return SDKVersion.versionString; } public boolean check( @NonNull String thingType, @NonNull String firmwareVersion) throws ThingIFException{ //TODO: // FIXME: 12/20/16 implement the logic return false; } public void updateThingType( @NonNull String thingType) { //TODO: // FIXME: 12/20/16 implement the logic } public void updateFirmwareVersion( @NonNull String firmwareVersion) { //TODO: // FIXME: 12/20/16 implement the logic } /** * Get thing type of the thing. * @return Name of thing type of the thing. If thing type is not set, null is returned. */ @Nullable public String getThingType(){ //TODO: // FIXME: 12/20/16 implement the logic. return null; } /** * Get firmware version of the thing. * @return Firmware version of the thing. If firmware version is not set, null is returned. */ @Nullable public String getFirmwareVersion() { //TODO: // FIXME: 12/20/16 implement the logic. return null; } }
package com.stephenramthun.algorithms.sorting; public class Quicksort { private static final int LIMIT = 50; /** * Sorts a given array of integers in ascending order. * * @param array Array of integers to sort. */ public static void sort(int[] array) { sort(array, 0, array.length - 1); } /** * Sorts a given array of objects in ascending order. * * @param array Array of objects to sort. */ public static void sort(Comparable[] array) { sort(array, 0, array.length - 1); } private static void sort(int[] array, int left, int right) { if (right - left > LIMIT) { int part = partition(array, left, right); sort(array, left, part); sort(array, part + 1, right); } else { InsertionSort.sort(array, left, right + 1); } } private static void sort(Comparable[] array, int left, int right) { if (right - left > LIMIT) { int part = partition(array, left, right); sort(array, left, part); sort(array, part + 1, right); } else { InsertionSort.sort(array, left, right + 1); } } private static int partition(int[] array, int left, int right) { int pivot = array[left]; int i = left - 1; int j = right + 1; while (i < j) { do { i++; } while (array[i] < pivot); do { j } while (array[j] > pivot); if (i < j) { Utility.swap(array, i, j); } } return j; } @SuppressWarnings("unchecked") private static int partition(Comparable[] array, int left, int right) { Comparable pivot = array[left]; int i = left - 1; int j = right + 1; while (i < j) { int comparison; do { i++; comparison = array[i].compareTo(pivot); } while (comparison < 0); do { j comparison = array[j].compareTo(pivot); } while (comparison > 0); if (i < j) { Utility.swap(array, i, j); } } return j; } }
package com.szmslab.quickjavamail.receive; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.List; import java.util.Properties; import javax.mail.Header; import javax.mail.Message; import javax.mail.Message.RecipientType; import javax.mail.MessagingException; import javax.mail.Multipart; import javax.mail.Part; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeUtility; import org.apache.commons.lang3.StringUtils; import com.szmslab.quickjavamail.utils.AttachmentFile; import com.szmslab.quickjavamail.utils.InlineImageFile; import com.szmslab.quickjavamail.utils.MailAddress; import com.szmslab.quickjavamail.utils.MailUtil; /** * * * @author szmslab */ public class MessageLoader { private boolean isDeleted; private Message message; private MessageContent contentCashe; /** * * * @param message * */ public MessageLoader(Message message) { this.message = message; this.isDeleted = false; } /** * * * @param message * * @param isDeleted * */ public MessageLoader(Message message, boolean isDeleted) { this.message = message; this.isDeleted = isDeleted; } /** * * * @return */ public boolean isDeleted() { return isDeleted; } /** * * * @param isDeleted * */ public void deleted(boolean isDeleted) { this.isDeleted = isDeleted; } /** * * * @return */ public Message getOriginalMessage() { return message; } /** * Message-ID * * @return Message-ID * @throws MessagingException */ public String getMessageId() throws MessagingException { return StringUtils.defaultString(StringUtils.join(message.getHeader("Message-ID"), ",")); } /** * MUA * * @return MUA * @throws MessagingException */ public String getMessageUserAgent() throws MessagingException { String mua = StringUtils.join(message.getHeader("User-Agent"), ","); if (StringUtils.isBlank(mua)) { mua = StringUtils.defaultString(StringUtils.join(message.getHeader("X-Mailer"), ",")); } return mua; } /** * * * @return * @throws MessagingException */ public Date getSentDate() throws MessagingException { return message.getSentDate(); } /** * * * @return * @throws MessagingException */ public int getSize() throws MessagingException { return message.getSize(); } /** * From * * @return From * @throws MessagingException */ public List<MailAddress> getFromAddressList() throws MessagingException { return toMailAddressList((InternetAddress[]) message.getFrom()); } /** * ReplyTo * * @return ReplyTo * @throws MessagingException */ public List<MailAddress> getReplyToAddressList() throws MessagingException { return toMailAddressList((InternetAddress[]) message.getReplyTo()); } /** * To * * @return To * @throws MessagingException */ public List<MailAddress> getToAddressList() throws MessagingException { return toMailAddressList((InternetAddress[]) message.getRecipients(RecipientType.TO)); } /** * Cc * * @return Cc * @throws MessagingException */ public List<MailAddress> getCcAddressList() throws MessagingException { return toMailAddressList((InternetAddress[]) message.getRecipients(RecipientType.CC)); } /** * * * @return * @throws MessagingException */ @SuppressWarnings("unchecked") public Properties getHeaders() throws MessagingException { Properties p = new Properties(); for (Enumeration<Header> headers = message.getAllHeaders(); headers.hasMoreElements();) { Header header = headers.nextElement(); p.setProperty(header.getName(), header.getValue()); } return p; } /** * * * @return * @throws MessagingException */ public String getSubject() throws MessagingException { return message.getSubject(); } /** * TEXT * * @return TEXT * @throws MessagingException * @throws IOException */ public String getText() throws MessagingException, IOException { return getContent().text; } /** * HTML * * @return HTML * @throws MessagingException * @throws IOException */ public String getHtml() throws MessagingException, IOException { return getContent().html; } /** * * * @return * @throws MessagingException * @throws IOException */ public List<AttachmentFile> getAttachmentFileList() throws MessagingException, IOException { return getContent().attachmentFileList; } /** * * * @return * @throws MessagingException * @throws IOException */ public List<InlineImageFile> getInlineImageFileList() throws MessagingException, IOException { return getContent().inlineImageFileList; } /** * * * @return * @throws MessagingException */ public boolean isPartial() throws MessagingException { return message.getContentType().indexOf("message/partial") >= 0; } /** * * * @return * @throws MessagingException * @throws IOException */ public ByteArrayInputStream getPartialContent() throws MessagingException, IOException { return getContent().partialContent; } /** * InternetAddressMailAddress * * @param addresses * InternetAddress * @return MailAddress */ private List<MailAddress> toMailAddressList(InternetAddress[] addresses) { List<MailAddress> list = new ArrayList<MailAddress>(); if (addresses != null) { for (InternetAddress address : addresses) { list.add(new MailAddress(address.getAddress(), address.getPersonal())); } } return list; } /** * * * @return * @throws MessagingException * @throws IOException */ private MessageContent getContent() throws MessagingException, IOException { if (contentCashe == null) { MessageContent msgContent = new MessageContent(); Object c = message.getContent(); if (c instanceof Multipart) { setMultipartContent((Multipart) c, msgContent); } else if (c instanceof ByteArrayInputStream) { msgContent.partialContent = (ByteArrayInputStream) c; } else { if (message.isMimeType("text/html")) { msgContent.html += c.toString(); } else { msgContent.text += c.toString(); } } contentCashe = msgContent; } return contentCashe; } /** * MessageContent * * @param multiPart * * @param msgContent * * @throws MessagingException * @throws IOException */ private void setMultipartContent(Multipart multiPart, MessageContent msgContent) throws MessagingException, IOException { for (int i = 0; i < multiPart.getCount(); i++) { Part part = multiPart.getBodyPart(i); String contentType = part.getContentType(); if (contentType.indexOf("multipart") >= 0) { setMultipartContent((Multipart) part.getContent(), msgContent); } else { String disposition = part.getDisposition(); if (Part.ATTACHMENT.equals(disposition)) { String encoding = MailUtil.getEncoding(part); String fileName = MailUtil.decodeText(part.getFileName()); if (part.isMimeType("message/rfc822") && "base64".equals(encoding)) { // Content-Type"message/rfc822"Content-Transfer-Encoding"base64" // BASE64EML Object rawContent = part.getContent(); if (rawContent instanceof Message) { MimeMessage attachmentMail = new MimeMessage(null, MimeUtility.decode(((Message) rawContent).getInputStream(), encoding)); if (StringUtils.isBlank(fileName)) { // Subject fileName = MailUtil.toValidFileName(attachmentMail.getSubject(), "_", "NoSubject") + ".eml"; } msgContent.attachmentFileList.add( new AttachmentFile(fileName, MailUtil.toByteArrayDataSource(attachmentMail, contentType))); } } else { msgContent.attachmentFileList.add( new AttachmentFile(fileName, part.getDataHandler().getDataSource())); } } else { if (part.isMimeType("text/html")) { msgContent.html += part.getContent().toString(); } else if (part.isMimeType("text/plain")) { msgContent.text += part.getContent().toString(); } else { // Content-Disposition"inline"Content-Type"text/plain" // Content-Typeinline if (Part.INLINE.equals(disposition)) { String cid = ""; if (part instanceof MimeBodyPart) { MimeBodyPart mimePart = (MimeBodyPart) part; cid = mimePart.getContentID(); } msgContent.inlineImageFileList.add( new InlineImageFile(cid, MailUtil.decodeText(part.getFileName()), part.getDataHandler().getDataSource())); } } } } } } /** * * * @author szmslab */ class MessageContent { /** * (TEXT) */ public String text = ""; /** * (HTML) */ public String html = ""; public List<AttachmentFile> attachmentFileList = new ArrayList<AttachmentFile>(); public List<InlineImageFile> inlineImageFileList = new ArrayList<InlineImageFile>(); public ByteArrayInputStream partialContent = null; } }
package com.twu.biblioteca.controller; import com.twu.biblioteca.exceptions.BookNotBorrowable; import com.twu.biblioteca.exceptions.BookNotReturnable; import com.twu.biblioteca.exceptions.MovieNotBorrowable; import com.twu.biblioteca.exceptions.MovieNotReturnable; import com.twu.biblioteca.model.Book; import com.twu.biblioteca.model.Library; import com.twu.biblioteca.model.Movie; import com.twu.biblioteca.model.User; import java.util.List; /** * LibraryController is responsible for updating the Library Model. * * @author Desiree Kelly * @version 1.0 */ public class LibraryController { private BorrowService borrowService; private ReturnService returnService; private Library library; private User user; public LibraryController(Library library, BorrowService borrowService, ReturnService returnService) { this.borrowService = borrowService; this.returnService = returnService; this.library = library; } public boolean borrowBook(Book book, User user) throws BookNotBorrowable { return borrowService.borrowBook(book, user); } public boolean returnBook(Book book, User user) throws BookNotReturnable { return returnService.returnBook(book, user); } public boolean borrowMovie(Movie movie) throws MovieNotBorrowable{ return borrowService.borrowMovie(movie); } public boolean returnMovie(Movie movie) throws MovieNotReturnable { return returnService.returnMovie(movie); } public List<Book> getAvailableBooks() { return library.getAvailableBooks(); } public List<Book> getBorrowedBooks() { return library.getBorrowedBooks(); } public List<Movie> getAvailableMovies(){ return library.getAvailableMovies(); } public List<Movie> getBorrowedMovies(){ return library.getBorrowedMovies(); } public boolean availableBooksIsEmpty() { if (library.getAvailableBooks().isEmpty()) { return true; } return false; } public boolean borrowedBooksIsEmpty() { if (library.getBorrowedBooks().isEmpty()) { return true; } return false; } public boolean availableMoviesIsEmpty() { if (library.getAvailableMovies().isEmpty()) { return true; } return false; } public boolean borrowedMoviesIsEmpty() { if (library.getBorrowedMovies().isEmpty()) { return true; } return false; } public int getAvailableBooksSize() { return library.getAvailableBooks().size(); } public int getBorrowedBooksSize() { return library.getBorrowedBooks().size(); } public int getAvailableMoviesSize() { return library.getAvailableMovies().size(); } public int getBorrowedMoviesSize() { return library.getBorrowedMovies().size(); } public String checkoutBook(int option) throws BookNotBorrowable { Book bookToBorrow = library.getAvailableBooks().get(option - 1); borrowBook(bookToBorrow, user); return bookToBorrow.getTitle().toString(); } public String checkinBook(int option) throws BookNotReturnable { Book bookToReturn = library.getBorrowedBooks().get(option - 1); returnBook(bookToReturn, user); return bookToReturn.getTitle().toString(); } public String checkoutMovie(int option) throws MovieNotBorrowable { Movie movieToBorrow = library.getAvailableMovies().get(option - 1); borrowMovie(movieToBorrow); return movieToBorrow.getName().toString(); } public String checkinMovie(int option) throws MovieNotReturnable { Movie movieToReturn = library.getBorrowedMovies().get(option - 1); returnMovie(movieToReturn); return movieToReturn.getName().toString(); } public User login(String libraryNumber, String password) { user = library.login(libraryNumber, password); return user; } public String getCustomerInformation() { return user.getCustomerInformation(); } public String getUserName() { return user.getName(); } public boolean isLibrarian() { return user.isLibrarian(); } public boolean booksCheckedOutByCustomersListIsEmpty() { if (library.getBooksCheckedOutByCustomersList() == null) { return true; } return false; } public String getBooksCheckedOutByCustomersList() { return library.getBooksCheckedOutByCustomersList(); } }
package com.witchworks.common.block.tools; import com.witchworks.api.helper.IModelRegister; import com.witchworks.client.handler.ModelHandler; import com.witchworks.common.block.BlockMod; import com.witchworks.common.lib.LibBlockName; import com.witchworks.common.tile.TileCauldron; import net.minecraft.block.BlockStairs; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.SoundType; import net.minecraft.block.material.Material; import net.minecraft.block.state.BlockStateContainer; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import javax.annotation.Nullable; import java.util.List; import static com.witchworks.api.WitchWorksAPI.HALF; import static net.minecraft.block.BlockHorizontal.FACING; public class BlockCauldron extends BlockMod implements IModelRegister, ITileEntityProvider { private static final AxisAlignedBB BOUNDING_BOX = new AxisAlignedBB(0.0625, 0, 0.0625, 15 * 0.0625, 11 * 0.0625, 15 * 0.0625); private static final AxisAlignedBB AABB_LEGS = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 0.3125D, 1.0D); private static final AxisAlignedBB AABB_WALL_NORTH = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 1.0D, 11 * 0.0625, 0.125D); private static final AxisAlignedBB AABB_WALL_SOUTH = new AxisAlignedBB(0.0D, 0.0D, 0.875D, 1.0D, 11 * 0.0625, 1.0D); private static final AxisAlignedBB AABB_WALL_EAST = new AxisAlignedBB(0.875D, 0.0D, 0.0D, 1.0D, 11 * 0.0625, 1.0D); private static final AxisAlignedBB AABB_WALL_WEST = new AxisAlignedBB(0.0D, 0.0D, 0.0D, 0.125D, 11 * 0.0625, 1.0D); public BlockCauldron() { super(LibBlockName.CAULDRON, Material.IRON); setSound(SoundType.METAL); setResistance(5F); setHardness(5F); } @Override protected IBlockState defaultState() { return super.defaultState() .withProperty(FACING, EnumFacing.NORTH) .withProperty(HALF, BlockStairs.EnumHalf.BOTTOM); } @SuppressWarnings("deprecation") @Override public void addCollisionBoxToList(IBlockState state, World worldIn, BlockPos pos, AxisAlignedBB entityBox, List<AxisAlignedBB> collidingBoxes, @Nullable Entity entityIn, boolean p_185477_7_) { addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_LEGS); addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_WALL_WEST); addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_WALL_NORTH); addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_WALL_EAST); addCollisionBoxToList(pos, entityBox, collidingBoxes, AABB_WALL_SOUTH); } @SuppressWarnings("deprecation") @Override public IBlockState getStateFromMeta(int meta) { IBlockState iblockstate = getDefaultState().withProperty(HALF, (meta & 4) > 0 ? BlockStairs.EnumHalf.TOP : BlockStairs.EnumHalf.BOTTOM); iblockstate = iblockstate.withProperty(FACING, EnumFacing.getFront(5 - (meta & 3))); return iblockstate; } @Override public int getMetaFromState(IBlockState state) { int i = 0; if (state.getValue(HALF) == BlockStairs.EnumHalf.TOP) { i |= 4; } i = i | 5 - state.getValue(FACING).getIndex(); return i; } protected BlockStateContainer createBlockState() { return new BlockStateContainer(this, FACING, HALF); } @Override public IBlockState getStateForPlacement(World world, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer, EnumHand hand) { IBlockState iblockstate = super.getStateForPlacement(world, pos, facing, hitX, hitY, hitZ, meta, placer, hand); iblockstate = iblockstate.withProperty(FACING, placer.getHorizontalFacing()); return facing != EnumFacing.DOWN && (facing == EnumFacing.UP || hitY <= 0.5F) ? iblockstate.withProperty(HALF, BlockStairs.EnumHalf.BOTTOM) : iblockstate.withProperty(HALF, BlockStairs.EnumHalf.TOP); } @Override public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) { final TileCauldron tile = (TileCauldron) worldIn.getTileEntity(pos); return tile != null && tile.useKettle(playerIn, hand, playerIn.getHeldItem(hand)); } @Override public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileCauldron(); } @SuppressWarnings("deprecation") @Override public boolean isFullCube(IBlockState state) { return false; } @SuppressWarnings("deprecation") @Override public boolean isOpaqueCube(IBlockState state) { return false; } @Override public boolean isPassable(IBlockAccess worldIn, BlockPos pos) { return true; } @SuppressWarnings("deprecation") @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { return BOUNDING_BOX; } @Override @SideOnly(Side.CLIENT) public void registerModel() { ModelHandler.registerModel(this, 0); } }
package com.xtremelabs.robolectric.shadows; import android.graphics.*; import com.xtremelabs.robolectric.internal.Implementation; import com.xtremelabs.robolectric.internal.Implements; import java.util.ArrayList; import java.util.List; import static com.xtremelabs.robolectric.Robolectric.newInstanceOf; import static com.xtremelabs.robolectric.Robolectric.shadowOf; /** * Shadows the {@code android.graphics.Canvas} class. * <p/> * Broken. * This implementation is very specific to the application for which it was developed. * Todo: Reimplement. Consider using the same strategy of collecting a history of draw events and providing methods for writing queries based on type, number, and order of events. */ @SuppressWarnings({"UnusedDeclaration"}) @Implements(Canvas.class) public class ShadowCanvas { private List<PathPaintHistoryEvent> pathPaintEvents = new ArrayList<PathPaintHistoryEvent>(); private List<TextPaintHistoryEvent> textPaintEvents = new ArrayList<TextPaintHistoryEvent>(); private List<CirclePaintHistoryEvent> circlePaintEvents = new ArrayList<CirclePaintHistoryEvent>(); private Paint drawnPaint; private Bitmap targetBitmap = newInstanceOf(Bitmap.class); private float translateX; private float translateY; private float scaleX = 1; private float scaleY = 1; public void __constructor__(Bitmap bitmap) { this.targetBitmap = bitmap; } public void appendDescription(String s) { shadowOf(targetBitmap).appendDescription(s); } public String getDescription() { return shadowOf(targetBitmap).getDescription(); } @Implementation public void translate(float x, float y) { this.translateX = x; this.translateY = y; } @Implementation public void scale(float sx, float sy) { this.scaleX = sx; this.scaleY = sy; } @Implementation public void scale(float sx, float sy, float px, float py) { this.scaleX = sx; this.scaleY = sy; } @Implementation public void drawPaint(Paint paint) { drawnPaint = paint; } @Implementation public void drawText (String text, float x, float y, Paint paint) { drawnPaint = paint; textPaintEvents.add(new TextPaintHistoryEvent(text, new PointF(x, y), paint)); } @Implementation public void drawColor(int color) { appendDescription("draw color " + color); } @Implementation public void drawBitmap(Bitmap bitmap, float left, float top, Paint paint) { describeBitmap(bitmap, paint); int x = (int) (left + translateX); int y = (int) (top + translateY); if (x != 0 && y != 0) { appendDescription(" at (" + x + "," + y + ")"); } if (scaleX != 1 && scaleY != 1) { appendDescription(" scaled by (" + scaleX + "," + scaleY + ")"); } } @Implementation public void drawPath(Path path, Paint paint) { pathPaintEvents.add(new PathPaintHistoryEvent(path, paint)); separateLines(); appendDescription("Path " + shadowOf(path).getPoints().toString()); } private void describeBitmap(Bitmap bitmap, Paint paint) { separateLines(); appendDescription(shadowOf(bitmap).getDescription()); if (paint != null) { ColorFilter colorFilter = paint.getColorFilter(); if (colorFilter != null) { appendDescription(" with " + colorFilter); } } } private void separateLines() { if (getDescription().length() != 0) { appendDescription("\n"); } } @Implementation public void drawBitmap(Bitmap bitmap, Matrix matrix, Paint paint) { describeBitmap(bitmap, paint); appendDescription(" transformed by matrix"); } public int getPathPaintHistoryCount() { return pathPaintEvents.size(); } public int getCirclePaintHistoryCount() { return circlePaintEvents.size(); } public int getTextPaintHistoryCount() { return textPaintEvents.size(); } public boolean hasDrawnPath() { return getPathPaintHistoryCount() > 0; } public boolean hasDrawnCircle() { return circlePaintEvents.size() > 0; } public boolean hasDrawnText() { return textPaintEvents.size() > 0; } public Paint getDrawnPathPaint(int i) { return pathPaintEvents.get(i).pathPaint; } public Paint getDrawnTextPaint(int i) { return textPaintEvents.get(i).textPaint; } public Path getDrawnPath(int i) { return pathPaintEvents.get(i).drawnPath; } public String getDrawnText(int i) { return textPaintEvents.get(i).text; } public PointF getDrawnTextPoint(int i) { return textPaintEvents.get(i).textPoint; } public CirclePaintHistoryEvent getDrawnCircle(int i) { return circlePaintEvents.get(i); } public void resetCanvasHistory() { pathPaintEvents.clear(); circlePaintEvents.clear(); } public Paint getDrawnPaint() { return drawnPaint; } private static class PathPaintHistoryEvent { private Path drawnPath; private Paint pathPaint; PathPaintHistoryEvent(Path drawnPath, Paint pathPaint) { this.drawnPath = drawnPath; this.pathPaint = pathPaint; } } private static class TextPaintHistoryEvent { private String text; private PointF textPoint; private Paint textPaint; TextPaintHistoryEvent(String text, PointF textPoint, Paint paint) { this.text = text; this.textPoint = textPoint; this.textPaint = paint; } } public static class CirclePaintHistoryEvent { public Paint paint; public float centerX; public float centerY; public float radius; private CirclePaintHistoryEvent(float centerX, float centerY, float radius, Paint paint) { this.paint = paint; this.centerX = centerX; this.centerY = centerY; this.radius = radius; } } }
package com.youcruit.mailchimp.client.http; import java.io.IOException; import java.net.URI; import java.util.Collections; import java.util.Map; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.youcruit.mailchimp.client.exceptions.MailchimpException; import com.youcruit.mailchimp.client.objects.pojos.Operation; import com.youcruit.mailchimp.client.objects.pojos.request.AbstractRequest; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.MediaType; import okhttp3.Request; import okhttp3.Request.Builder; import okhttp3.RequestBody; import okhttp3.Response; public class OkHttpClient implements HttpClient { private static final MediaType APPLICATION_JSON = MediaType.parse("application/json"); private static final Logger LOGGER = LogManager.getLogger(OkHttpClient.class); private final okhttp3.OkHttpClient client; private final Gson gson; private final URI baseUri; public OkHttpClient(String password, URI baseUri) { okhttp3.OkHttpClient.Builder okHttpClient = new okhttp3.OkHttpClient.Builder(); okHttpClient.readTimeout(300, TimeUnit.SECONDS); okHttpClient.connectTimeout(60, TimeUnit.SECONDS); okHttpClient.writeTimeout(60, TimeUnit.SECONDS); if (password != null) { okHttpClient.authenticator(new BasicAuthenticator("mailchimp-v3-java-client", password)); } okHttpClient.interceptors().add(new UserAgentInterceptor()); this.baseUri = baseUri; this.client = okHttpClient.build(); this.gson = createGson(); } public OkHttpClient(URI baseUri) { this(null, baseUri); } protected Gson createGson() { return new GsonBuilder().create(); } @Override public <V> V sync(Operation<V> operation) throws IOException { return sync(operation.body, operation.method, operation.responseClass, operation.params, operation.path); } @Override public <V> V sync(AbstractRequest requestBody, Method method, Class<V> responseClass, Map<String, String> queryParameters, String... pathSegments) throws IOException { URI uri = pathToUri(queryParameters, pathSegments); final Request request = createRequest(uri, requestBody, method); final Response response = client.newCall(request).execute(); String responseJson = response.body().string(); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Response json for " + uri + " : " + responseJson); } if (response.isSuccessful()) { if (Void.class.getName().equals(responseClass.getName())) { return null; } return gson.fromJson(responseJson, responseClass); } else { LOGGER.warn("Error response json from mandrill " + uri + " : " + responseJson); throw new MailchimpException(response.code(), response.message(), uri); } } private Request createRequest(URI uri, Object requestBody, HttpClient.Method method) { Request.Builder requestBuilder = new Request.Builder().url(uri.toString()); RequestBody payload = null; if (requestBody == null && method == Method.POST) { requestBody = Collections.emptyMap(); } if (requestBody != null) { String requestString = gson.toJson(requestBody); if (LOGGER.isDebugEnabled()) { StringBuilder sb = new StringBuilder(method.name()).append(" Request for ").append(uri); LOGGER.debug(sb); if (LOGGER.isTraceEnabled()) { sb.append(" : ").append(requestBody); LOGGER.trace(sb); } } payload = RequestBody.create(APPLICATION_JSON, requestString.getBytes(UTF8)); } requestBuilder.method(method.name(), payload); return requestBuilder.build(); } private static class UserAgentInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request originalRequest = chain.request(); Builder builder = originalRequest.newBuilder(); builder.removeHeader("User-Agent").addHeader("User-Agent", USER_AGENT); return chain.proceed(builder.build()); } } private URI pathToUri(Map<String, String> queryParameters, String... pathSegments) { HttpUrl.Builder builder = HttpUrl.get(baseUri).newBuilder(); for (String pathSegment : pathSegments) { builder.addPathSegment(pathSegment); } for (Map.Entry<String, String> e : queryParameters.entrySet()) { builder.addQueryParameter(e.getKey(), e.getValue()); } return builder.build().uri(); } }
package dbathon.web.gvds.persistence; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.persistence.Query; import com.google.common.base.Joiner; public class WhereClauseBuilder { private static final Joiner AND_JOINER = Joiner.on(" and "); private static final Joiner OR_JOINER = Joiner.on(" or "); private static final Pattern PARAM_PATTERN = Pattern.compile("\\?"); private static class Conditions { public final Joiner joiner; public List<String> conditions = new ArrayList<>(); private Conditions(Joiner joiner) { this.joiner = joiner; } @Override public String toString() { return joiner.join(conditions); } } private final String paramNamePrefix; private final Map<String, Object> paramsMap = new HashMap<>(); private final List<Conditions> stack = new ArrayList<>(); public WhereClauseBuilder(String paramNamePrefix) { this.paramNamePrefix = "_" + paramNamePrefix + "_"; stack.add(new Conditions(AND_JOINER)); } public WhereClauseBuilder() { this("wcb"); } private Conditions current() { return stack.get(stack.size() - 1); } private String processCondition(String condition, boolean parens, Object[] params) { final StringBuffer sb = new StringBuffer(condition.length() * 2); if (parens) { sb.append("("); } final Matcher m = PARAM_PATTERN.matcher(condition); boolean found = m.find(); int idx = 0; if (!found) { sb.append(condition); } else { do { if (idx > params.length - 1) { throw new IllegalArgumentException("to few params: " + params.length); } final String paramName = paramNamePrefix + paramsMap.size(); paramsMap.put(paramName, params[idx]); m.appendReplacement(sb, ":"); sb.append(paramName); ++idx; found = m.find(); } while (found); m.appendTail(sb); } if (params != null && params.length != idx) { throw new IllegalArgumentException("to many params: " + params.length + " instead of " + idx); } if (parens) { sb.append(")"); } return sb.toString(); } private void addInternal(String condition, boolean parens, Object... params) { current().conditions.add(processCondition(condition, parens, params)); } public void add(String condition, Object... params) { addInternal(condition, true, params); } public void add(String condition) { add(condition, (Object[]) null); } private void start(Joiner joiner) { stack.add(new Conditions(joiner)); } private void finish(Joiner joiner) { if (stack.size() <= 1) { throw new IllegalStateException("nothing to finish"); } final Conditions current = current(); if (current.joiner != joiner) { throw new IllegalArgumentException("wrong finish type"); } // just pop ... stack.remove(stack.size() - 1); // ... and add to the outer conditions if necessary if (!current.conditions.isEmpty()) { addInternal(current.toString(), current.conditions.size() > 1, (Object[]) null); } } public void startAnd() { start(AND_JOINER); } public void startOr() { start(OR_JOINER); } public void finishAnd() { finish(AND_JOINER); } public void finishOr() { finish(OR_JOINER); } public String buildWhereClause() { if (stack.size() != 1) { throw new IllegalStateException("not finished"); } final Conditions current = current(); if (current.conditions.isEmpty()) { return ""; } else { return " where " + current.toString(); } } public Map<String, Object> getParametersMap() { return Collections.unmodifiableMap(paramsMap); } public <Q extends Query> Q applyParameters(Q query) { for (final Entry<String, Object> entry : paramsMap.entrySet()) { query.setParameter(entry.getKey(), entry.getValue()); } return query; } }
package de.alpharogroup.reflection; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import de.alpharogroup.string.StringExtensions; import lombok.experimental.ExtensionMethod; import lombok.experimental.UtilityClass; /** * The class {@link ReflectionExtensions}. */ @ExtensionMethod(StringExtensions.class) @UtilityClass public final class ReflectionExtensions { /** * Gets all fieldnames from the given class as an String array. * * @param cls * The class object to get the fieldnames. * * @return Gets all fieldnames from the given class as an String array. */ public static List<String> getFieldNames(final Class<?> cls) { final Field[] fields = cls.getDeclaredFields(); final List<String> fieldNames = new ArrayList<>(); for (final Field field : fields) { fieldNames.add(field.getName()); } return fieldNames; } /** * Gets all methodnames from the given class as an String array. * * @param cls * The class object to get the methodnames. * * @return Gets all methodnames from the given class as an String array. */ public static String[] getMethodNames(final Class<?> cls) { final Method[] methods = cls.getDeclaredMethods(); final String[] methodNames = new String[methods.length]; for (int i = 0; i < methods.length; i++) { methodNames[i] = methods[i].getName(); } return methodNames; } /** * Generates a Map with the fieldName as key and the method as value. Concatenates the given * prefix and the fieldname and puts the result into the map. * * @param fieldNames * A list with the fieldNames. * @param prefix * The prefix for the methodname. * * @return the method names with prefix from field names */ public static final Map<String, String> getMethodNamesWithPrefixFromFieldNames( final List<String> fieldNames, final String prefix) { final Map<String, String> fieldNameMethodMapper = new HashMap<>(); for (final String fieldName : fieldNames) { final String firstCharacterToUpperCasefieldName = fieldName.firstCharacterToUpperCase(); final String methodName = prefix + firstCharacterToUpperCasefieldName; fieldNameMethodMapper.put(fieldName, methodName); } return fieldNameMethodMapper; } /** * Gets the modifiers from the given Field as a list of String objects. * * @param field * The field to get the modifiers. * @return A list with the modifiers as String objects from the given Field. */ public static List<String> getModifiers(final Field field) { final String modifiers = Modifier.toString(field.getModifiers()); final String[] modifiersArray = modifiers.split(" "); return Arrays.asList(modifiersArray); } @Deprecated public static <T> T getNewInstance(final T obj) throws ClassNotFoundException, InstantiationException, IllegalAccessException { return newInstance(obj); } @SuppressWarnings("unchecked") public static <T> T newInstance(final T obj) throws InstantiationException, IllegalAccessException, ClassNotFoundException { return newInstance((Class<T>)Class.forName(obj.getClass().getCanonicalName())); } public static <T> T newInstance(final Class<T> clazz) throws InstantiationException, IllegalAccessException, ClassNotFoundException { return clazz.newInstance(); } /** * Gets the {@link Field} that match to the given field name that exists in the given object. * * @param <T> * the generic type * @param object * the object * @param fieldName * the field name * @return the declared field * @throws NoSuchFieldException * is thrown if no such field exists. * @throws SecurityException * is thrown if a security manager says no. */ public static <T> Field getDeclaredField(final T object, final String fieldName) throws NoSuchFieldException, SecurityException { Field field = object.getClass().getDeclaredField(fieldName); return field; } /** * Gets the {@link Field} that match to the given field name that exists in the given class. * * @param cls * the cls * @param fieldName * the field name * @return the declared field * @throws NoSuchFieldException * is thrown if no such field exists. * @throws SecurityException * is thrown if a security manager says no. */ public static Field getDeclaredField(final Class<?> cls, final String fieldName) throws NoSuchFieldException, SecurityException { Field field = cls.getDeclaredField(fieldName); return field; } }
package de.proteinms.xtandemparser.viewer; import com.jgoodies.looks.HeaderStyle; import com.jgoodies.looks.Options; import com.jgoodies.looks.plastic.PlasticLookAndFeel; import com.compomics.util.gui.spectrum.SpectrumPanel; import com.compomics.util.gui.spectrum.DefaultSpectrumAnnotation; import com.compomics.util.protein.Header; import de.proteinms.xtandemparser.interfaces.Modification; import de.proteinms.xtandemparser.xtandem.*; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.JXTableHeader; import org.xml.sax.SAXException; import javax.swing.*; import javax.swing.table.DefaultTableModel; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.io.*; import java.util.*; import java.util.List; /** * This class provides a basic viewer for the spectra. * * @author Thilo Muth */ public class XTandemViewer extends JFrame { /** * If set to true, all print outs (both standard and error) will be sent to * the ErrorLog.txt file in the Properties folder. */ private static boolean useErrorLog = true; public final static String APPTITLE = "X!Tandem Viewer"; private final static String MODIFICATIONSLEGEND = " | <M *> are fixed and <M ^> are variable modifications."; private String lastSelectedFolder = "user.home"; private SpectrumPanel spectrumPanel; private String iXTandemFileString; private HashMap<Integer, ArrayList<Peptide>> peptideMap; private HashMap<String, String> proteinLabelMap; private HashMap<Integer, ArrayList<Double>> allMzValues, allIntensityValues; private HashMap<String, ArrayList<Modification>> allFixMods, allVarMods; private HashMap<String, FragmentIon[]> ionsMap; private HashMap<Integer, String> accMap; private Vector spectraTableColToolTips, spectrumTableColToolTips, spectrumJXTableColToolTips, identificationsJXTableColumnToolTips; private HashMap<String, Vector<DefaultSpectrumAnnotation>> allAnnotations; private JCheckBox aIonsJCheckBox, bIonsJCheckBox, cIonsJCheckBox, chargeOneJCheckBox, chargeTwoJCheckBox, chargeOverTwoJCheckBox, xIonsJCheckBox, yIonsJCheckBox, zIonsJCheckBox; private JLabel modificationDetailsJLabel; private JScrollPane jScrollPane1; private JScrollPane jScrollPane3; private JSeparator jSeparator1, jSeparator2; private JXTable identificationsTable, spectraTable, spectrumJXTable; private JPanel jPanel1, jPanel2, jPanel3, jPanel4, spectrumJPanel; private double ionCoverageErrorMargin = 0.0; private ProgressDialog progressDialog; private JMenuItem openMenuItem, exitMenuItem, aboutMenuItem, helpMenuItem, exportSpectraTableMenuItem, exportAllIdentificationsMenuItem, exportAllSpectraMenuItem, exportSelectedSpectrumMenuItem; private XTandemFile iXTandemFile; /** * Constructor gets the xml output result file. * * @param aXTandemXmlFile * @param lastSelectedFolder */ public XTandemViewer(String aXTandemXmlFile, String lastSelectedFolder) { // set up the error log if (useErrorLog && !getJarFilePath().equalsIgnoreCase(".")) { try { String path = "" + this.getClass().getProtectionDomain().getCodeSource().getLocation(); // remove starting 'file:' tag if there if (path.startsWith("file:")) { path = path.substring("file:".length(), path.lastIndexOf("/")); } path = path + "/Properties/ErrorLog.txt"; path = path.replace("%20", " "); File file = new File(path); System.setOut(new java.io.PrintStream(new FileOutputStream(file, true))); System.setErr(new java.io.PrintStream(new FileOutputStream(file, true))); // creates a new error log file if it does not exist if (!file.exists()) { file.createNewFile(); FileWriter w = new FileWriter(file); BufferedWriter bw = new BufferedWriter(w); bw.close(); w.close(); } } catch (Exception e) { JOptionPane.showMessageDialog( null, "An error occured when trying to create the ErrorLog." + "See ../Properties/ErrorLog.txt for more details.", "Error Creating ErrorLog", JOptionPane.ERROR_MESSAGE); e.printStackTrace(); } } // Construct the menu constructMenu(); initComponents(); // Sets icon image setIconImage(Toolkit.getDefaultToolkit().getImage(getClass(). getResource("/icons/xtandemviewer.gif"))); spectraTable.getColumn(" ").setMaxWidth(35); spectraTable.getColumn(" ").setMinWidth(35); spectraTable.getColumn("m/z").setMaxWidth(65); spectraTable.getColumn("m/z").setMinWidth(65); spectraTable.getColumn("Charge").setMaxWidth(65); spectraTable.getColumn("Charge").setMinWidth(65); spectraTable.getColumn("Identified").setMaxWidth(80); spectraTable.getColumn("Identified").setMinWidth(80); spectrumJXTable.getColumn(" ").setMaxWidth(35); spectrumJXTable.getColumn(" ").setMinWidth(35); identificationsTable.getColumn(" ").setMaxWidth(35); identificationsTable.getColumn(" ").setMinWidth(35); identificationsTable.getColumn("Start").setMaxWidth(45); identificationsTable.getColumn("Start").setMinWidth(45); identificationsTable.getColumn("End").setMaxWidth(45); identificationsTable.getColumn("End").setMinWidth(45); identificationsTable.getColumn("Exp. Mass").setMaxWidth(75); identificationsTable.getColumn("Exp. Mass").setMinWidth(75); identificationsTable.getColumn("Theo. Mass").setMaxWidth(75); identificationsTable.getColumn("Theo. Mass").setMinWidth(75); identificationsTable.getColumn("E-value").setMinWidth(75); identificationsTable.getColumn("E-value").setMaxWidth(75); identificationsTable.getColumn("Accession").setPreferredWidth(10); spectraTable.getTableHeader().setReorderingAllowed(false); spectrumJXTable.getTableHeader().setReorderingAllowed(false); identificationsTable.getTableHeader().setReorderingAllowed(false); spectraTableColToolTips = new Vector(); spectraTableColToolTips.add("Spectrum Number"); spectraTableColToolTips.add("Spectrum File Name"); spectraTableColToolTips.add("Precursor Mass Over Charge Ratio"); spectraTableColToolTips.add("Precursor Charge"); spectraTableColToolTips.add("Spectrum Identified"); spectrumTableColToolTips = new Vector(); spectrumTableColToolTips.add(null); spectrumTableColToolTips.add("Mass Over Charge Ratio"); spectrumTableColToolTips.add("Intensity"); spectrumJXTableColToolTips = new Vector(); spectrumJXTableColToolTips.add(null); spectrumJXTableColToolTips.add("Mass Over Charge Ratio"); spectrumJXTableColToolTips.add("Intensity"); identificationsJXTableColumnToolTips = new Vector(); identificationsJXTableColumnToolTips.add("Spectrum Number"); identificationsJXTableColumnToolTips.add("Peptide Sequence"); identificationsJXTableColumnToolTips.add("Modified Peptide Sequence"); identificationsJXTableColumnToolTips.add("Peptide Start Index"); identificationsJXTableColumnToolTips.add("Peptide End Index"); identificationsJXTableColumnToolTips.add("Experimental Mass"); identificationsJXTableColumnToolTips.add("Theoretical Mass"); identificationsJXTableColumnToolTips.add("E-value"); identificationsJXTableColumnToolTips.add("Protein Accession Number"); identificationsJXTableColumnToolTips.add("Protein Description"); setMinimumSize(new Dimension(900, 600)); setLocationRelativeTo(null); setVisible(true); insertFiles(aXTandemXmlFile, lastSelectedFolder); } /** * Returns the path to the jar file. * * @return the path to the jar file */ private String getJarFilePath() { String path = this.getClass().getResource("XTandemViewer.class").getPath(); if (path.lastIndexOf("/xtandem-parser-") != -1) { // remove starting 'file:' tag if there if (path.startsWith("file:")) { path = path.substring("file:".length(), path.lastIndexOf("/xtandem-parser-")); } else { path = path.substring(0, path.lastIndexOf("/xtandem-parser-")); } path = path.replace("%20", " "); } else { path = "."; } return path; } /** * Constructing the menu at the top of the frame */ private void constructMenu() { JMenuBar menuBar = new JMenuBar(); menuBar.putClientProperty(Options.HEADER_STYLE_KEY, HeaderStyle.SINGLE); menuBar.putClientProperty(PlasticLookAndFeel.IS_3D_KEY, Boolean.FALSE); // Defining the menus JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic('F'); JMenu exportMenu = new JMenu("Export"); exportMenu.setMnemonic('E'); // JMenu parameterMenu = new JMenu("Parameters"); // parameterMenu.setMnemonic('P'); JMenu helpMenu = new JMenu("Help"); helpMenu.setMnemonic('H'); menuBar.add(fileMenu); menuBar.add(exportMenu); // menuBar.add(parameterMenu); menuBar.add(helpMenu); // The menu items openMenuItem = new JMenuItem(); exitMenuItem = new JMenuItem(); helpMenuItem = new JMenuItem(); aboutMenuItem = new JMenuItem(); exportSpectraTableMenuItem = new JMenuItem(); exportAllIdentificationsMenuItem = new JMenuItem(); exportAllSpectraMenuItem = new JMenuItem(); exportSelectedSpectrumMenuItem = new JMenuItem(); // inputParameterMenuItem = new JMenuItem(); // inputParameterMenuItem.setMnemonic('I'); // inputParameterMenuItem.setText("Input Parameters"); // inputParameterMenuItem.setToolTipText("Show Input Parameters"); // inputParameterMenuItem.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent evt) { // inputParameterMenuItemActionPerformed(evt); // parameterMenu.add(inputParameterMenuItem); // performanceParameterMenuItem = new JMenuItem(); // performanceParameterMenuItem.setMnemonic('P'); // performanceParameterMenuItem.setText("Performance Parameters"); // performanceParameterMenuItem.setToolTipText("Show the Performance Parameters"); // performanceParameterMenuItem.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent evt) { // //performanceParameterMenuItemActionPerformed(evt); // parameterMenu.add(performanceParameterMenuItem); exportSpectraTableMenuItem.setMnemonic('T'); exportSpectraTableMenuItem.setText("Spectra Files Table"); exportSpectraTableMenuItem.setToolTipText("Export the Spectra Files Table as Tab Delimited Text File"); exportSpectraTableMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exportSpectraFilesTable(evt); } }); exportMenu.add(exportSpectraTableMenuItem); exportAllIdentificationsMenuItem.setMnemonic('I'); exportAllIdentificationsMenuItem.setText("All Identifications (all hits)"); exportAllIdentificationsMenuItem.setToolTipText("Export All Identifications (all hits) as Tab Delimited Text File"); exportAllIdentificationsMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exportAllIdentifications(evt); } }); exportMenu.add(exportAllIdentificationsMenuItem); exportSelectedSpectrumMenuItem.setMnemonic('S'); exportSelectedSpectrumMenuItem.setText("Selected Spectrum"); exportSelectedSpectrumMenuItem.setToolTipText("Export the Selected Spectrum as Tab Delimited Text File"); exportSelectedSpectrumMenuItem.setEnabled(false); exportSelectedSpectrumMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exportSelectedSpectrum(evt); } }); exportMenu.add(exportSelectedSpectrumMenuItem); exportAllSpectraMenuItem.setMnemonic('S'); exportAllSpectraMenuItem.setText("All Spectra"); exportAllSpectraMenuItem.setToolTipText("Export all the Spectra as DTA Files"); exportAllSpectraMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { exportAllSpectra(evt); } }); exportMenu.add(exportAllSpectraMenuItem); helpMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F1, 0)); helpMenuItem.setMnemonic('H'); helpMenuItem.setText("Help"); helpMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { helpTriggered(); } }); helpMenu.add(helpMenuItem); aboutMenuItem.setMnemonic('a'); aboutMenuItem.setText("About"); aboutMenuItem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { aboutTriggered(); } }); helpMenu.add(aboutMenuItem); openMenuItem.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); openMenuItem.setMnemonic('O'); openMenuItem.setText("Open"); openMenuItem.setToolTipText("Open a New X!Tandem XML File"); openMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { openActionPerformed(evt); } }); fileMenu.add(openMenuItem); exitMenuItem.setMnemonic('x'); exitMenuItem.setText("Exit"); exitMenuItem.setToolTipText("Exit XTandem Viewer"); exitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { System.exit(0); } }); fileMenu.add(exitMenuItem); setJMenuBar(menuBar); } /** * The method that builds the help frame. */ private void helpTriggered() { setCursor(new Cursor(java.awt.Cursor.WAIT_CURSOR)); new HelpFrame(this, getClass().getResource("/html/help.html")); setCursor(new Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } /** * The method that builds the about dialog. */ private void aboutTriggered() { StringBuffer tMsg = new StringBuffer(); tMsg.append(APPTITLE + " " + new Properties().getVersion()); tMsg.append("\n"); tMsg.append("\n"); tMsg.append("The XTandem parser is a Java project for extracting information from X!Tandem output xml files."); tMsg.append("\n"); tMsg.append("\n"); tMsg.append("The latest version is available at http://xtandem-parser.googlecode.com"); tMsg.append("\n"); tMsg.append("\n"); tMsg.append("If any questions arise, contact the corresponding author: "); tMsg.append("\n"); tMsg.append("Thilo.Muth@uni-jena.de"); tMsg.append("\n"); tMsg.append("\n"); tMsg.append(""); tMsg.append(""); JOptionPane.showMessageDialog(this, tMsg, "About " + APPTITLE + " " + new Properties().getVersion(), JOptionPane.INFORMATION_MESSAGE); } /** * This method initializes all the gui components. */ private void initComponents() { jPanel1 = new javax.swing.JPanel(); jScrollPane3 = new javax.swing.JScrollPane(); spectraTable = new JXTable() { @Override protected JXTableHeader createDefaultTableHeader() { return new JXTableHeader(columnModel) { @Override public String getToolTipText(MouseEvent e) { String tip; java.awt.Point p = e.getPoint(); int index = columnModel.getColumnIndexAtX(p.x); int realIndex = columnModel.getColumn(index).getModelIndex(); tip = (String) spectraTableColToolTips.get(realIndex); return tip; } }; } }; jPanel2 = new javax.swing.JPanel(); modificationDetailsJLabel = new javax.swing.JLabel(); JLabel jLabel1 = new JLabel(); JScrollPane jScrollPane4 = new JScrollPane(); identificationsTable = new JXTable() { @Override protected JXTableHeader createDefaultTableHeader() { return new JXTableHeader(columnModel) { @Override public String getToolTipText(MouseEvent e) { String tip; java.awt.Point p = e.getPoint(); int index = columnModel.getColumnIndexAtX(p.x); int realIndex = columnModel.getColumn(index).getModelIndex(); tip = (String) identificationsJXTableColumnToolTips.get(realIndex); return tip; } }; } }; jPanel3 = new JPanel(); spectrumJPanel = new JPanel(); jPanel4 = new JPanel(); aIonsJCheckBox = new JCheckBox(); bIonsJCheckBox = new JCheckBox(); cIonsJCheckBox = new JCheckBox(); jSeparator1 = new JSeparator(); yIonsJCheckBox = new JCheckBox(); xIonsJCheckBox = new JCheckBox(); zIonsJCheckBox = new JCheckBox(); jSeparator2 = new JSeparator(); chargeOneJCheckBox = new JCheckBox(); chargeTwoJCheckBox = new JCheckBox(); chargeOverTwoJCheckBox = new JCheckBox(); jScrollPane1 = new JScrollPane(); spectrumJXTable = new JXTable() { @Override protected JXTableHeader createDefaultTableHeader() { return new JXTableHeader(columnModel) { @Override public String getToolTipText(MouseEvent e) { String tip; java.awt.Point p = e.getPoint(); int index = columnModel.getColumnIndexAtX(p.x); int realIndex = columnModel.getColumn(index).getModelIndex(); tip = (String) spectrumJXTableColToolTips.get(realIndex); return tip; } }; } }; setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Spectra Files")); spectraTable.setModel(new javax.swing.table.DefaultTableModel( new Object[][]{}, new String[]{" ", "Filename", "m/z", "Charge", "Identified"}) { Class[] types = new Class[]{ Integer.class, String.class, Double.class, Integer.class, Boolean.class }; boolean[] canEdit = new boolean[]{ false, false, false, false, false }; @Override public Class getColumnClass(int columnIndex) { return types[columnIndex]; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit[columnIndex]; } }); spectraTable.setOpaque(false); spectraTable.addKeyListener(new java.awt.event.KeyAdapter() { @Override public void keyReleased(java.awt.event.KeyEvent evt) { spectraJXTableKeyReleased(evt); } }); spectraTable.addMouseListener(new java.awt.event.MouseAdapter() { @Override public void mouseClicked(java.awt.event.MouseEvent evt) { spectraJXTableMouseClicked(evt); } }); jScrollPane3.setViewportView(spectraTable); org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(jPanel1Layout.createSequentialGroup().addContainerGap().add(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 460, Short.MAX_VALUE).addContainerGap())); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(jPanel1Layout.createSequentialGroup().add(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 383, Short.MAX_VALUE).addContainerGap())); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Identifications")); modificationDetailsJLabel.setFont(modificationDetailsJLabel.getFont().deriveFont((modificationDetailsJLabel.getFont().getStyle() | java.awt.Font.PLAIN))); jLabel1.setFont(jLabel1.getFont().deriveFont((jLabel1.getFont().getStyle() | java.awt.Font.PLAIN))); jLabel1.setText("Legend: "); identificationsTable.setModel(new javax.swing.table.DefaultTableModel( new Object[][]{}, new String[]{ " ", "Sequence", "Modified Sequence", "Start", "End", "Exp. Mass", "Theo. Mass", "E-value", "Accession", "Description" }) { Class[] types = new Class[]{ Integer.class, String.class, String.class, Integer.class, Integer.class, Double.class, Double.class, Float.class, Float.class, String.class, String.class, String.class }; boolean[] canEdit = new boolean[]{ false, false, false, false, false, false, false, false, false, false, false, false }; @Override public Class getColumnClass(int columnIndex) { return types[columnIndex]; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit[columnIndex]; } }); identificationsTable.setOpaque(false); jScrollPane4.setViewportView(identificationsTable); org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(jPanel2Layout.createSequentialGroup().addContainerGap().add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(jPanel2Layout.createSequentialGroup().add(jLabel1).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(modificationDetailsJLabel)).add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 1146, Short.MAX_VALUE)).addContainerGap())); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup().add(jScrollPane4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE).add(jLabel1).add(modificationDetailsJLabel)))); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Spectrum")); spectrumJPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder()); spectrumJPanel.setLayout(new javax.swing.BoxLayout(spectrumJPanel, javax.swing.BoxLayout.LINE_AXIS)); aIonsJCheckBox.setSelected(true); aIonsJCheckBox.setText("a"); aIonsJCheckBox.setToolTipText("Show a-ions"); aIonsJCheckBox.setMaximumSize(new Dimension(39, 23)); aIonsJCheckBox.setMinimumSize(new Dimension(39, 23)); aIonsJCheckBox.setPreferredSize(new Dimension(39, 23)); aIonsJCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { aIonsJCheckBoxActionPerformed(evt); } }); bIonsJCheckBox.setSelected(true); bIonsJCheckBox.setText("b"); bIonsJCheckBox.setToolTipText("Show b-ions"); bIonsJCheckBox.setMaximumSize(new Dimension(39, 23)); bIonsJCheckBox.setMinimumSize(new Dimension(39, 23)); bIonsJCheckBox.setPreferredSize(new Dimension(39, 23)); bIonsJCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { bIonsJCheckBoxActionPerformed(); } }); cIonsJCheckBox.setSelected(true); cIonsJCheckBox.setText("c"); cIonsJCheckBox.setToolTipText("Show c-ions"); cIonsJCheckBox.setMaximumSize(new Dimension(39, 23)); cIonsJCheckBox.setMinimumSize(new Dimension(39, 23)); cIonsJCheckBox.setPreferredSize(new Dimension(39, 23)); cIonsJCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { cIonsJCheckBoxActionPerformed(); } }); yIonsJCheckBox.setSelected(true); yIonsJCheckBox.setText("y"); yIonsJCheckBox.setToolTipText("Show y-ions"); yIonsJCheckBox.setMaximumSize(new Dimension(39, 23)); yIonsJCheckBox.setMinimumSize(new Dimension(39, 23)); yIonsJCheckBox.setPreferredSize(new Dimension(39, 23)); yIonsJCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { yIonsJCheckBoxActionPerformed(); } }); xIonsJCheckBox.setSelected(true); xIonsJCheckBox.setText("x"); xIonsJCheckBox.setToolTipText("Show x-ions"); xIonsJCheckBox.setMaximumSize(new Dimension(39, 23)); xIonsJCheckBox.setMinimumSize(new Dimension(39, 23)); xIonsJCheckBox.setPreferredSize(new Dimension(39, 23)); xIonsJCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { xIonsJCheckBoxActionPerformed(); } }); zIonsJCheckBox.setSelected(true); zIonsJCheckBox.setText("z"); zIonsJCheckBox.setToolTipText("Show z-ions"); zIonsJCheckBox.setMaximumSize(new Dimension(39, 23)); zIonsJCheckBox.setMinimumSize(new Dimension(39, 23)); zIonsJCheckBox.setPreferredSize(new Dimension(39, 23)); zIonsJCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { zIonsJCheckBoxActionPerformed(); } }); chargeOneJCheckBox.setSelected(true); chargeOneJCheckBox.setText("+"); chargeOneJCheckBox.setToolTipText("Show ions with charge 1"); chargeOneJCheckBox.setMaximumSize(new Dimension(39, 23)); chargeOneJCheckBox.setMinimumSize(new Dimension(39, 23)); chargeOneJCheckBox.setPreferredSize(new Dimension(39, 23)); chargeOneJCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { chargeOneJCheckBoxActionPerformed(); } }); chargeTwoJCheckBox.setSelected(true); chargeTwoJCheckBox.setText("++"); chargeTwoJCheckBox.setToolTipText("Show ions with charge 2"); chargeTwoJCheckBox.setMaximumSize(new java.awt.Dimension(39, 23)); chargeTwoJCheckBox.setMinimumSize(new java.awt.Dimension(39, 23)); chargeTwoJCheckBox.setPreferredSize(new java.awt.Dimension(39, 23)); chargeTwoJCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent evt) { chargeTwoJCheckBoxActionPerformed(); } }); chargeOverTwoJCheckBox.setSelected(true); chargeOverTwoJCheckBox.setText(">2"); chargeOverTwoJCheckBox.setToolTipText("Show ions with charge >2"); chargeOverTwoJCheckBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent evt) { chargeOverTwoJCheckBoxActionPerformed(); } }); org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(jPanel4Layout.createSequentialGroup().addContainerGap().add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(yIonsJCheckBox, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE).add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel4Layout.createSequentialGroup().add(chargeOneJCheckBox, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 42, Short.MAX_VALUE).add(2, 2, 2)).add(org.jdesktop.layout.GroupLayout.TRAILING, zIonsJCheckBox, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE).add(xIonsJCheckBox, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE).add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false).add(org.jdesktop.layout.GroupLayout.TRAILING, chargeTwoJCheckBox, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).add(org.jdesktop.layout.GroupLayout.TRAILING, chargeOverTwoJCheckBox, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 44, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)).add(bIonsJCheckBox, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE).add(aIonsJCheckBox, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE).add(cIonsJCheckBox, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE).add(jPanel4Layout.createSequentialGroup().add(jSeparator2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE).addContainerGap()).add(jPanel4Layout.createSequentialGroup().add(jSeparator1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE).addContainerGap())))); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(jPanel4Layout.createSequentialGroup().addContainerGap().add(aIonsJCheckBox, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(bIonsJCheckBox, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(cIonsJCheckBox, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE).addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED).add(jSeparator1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).add(13, 13, 13).add(xIonsJCheckBox, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(yIonsJCheckBox, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(zIonsJCheckBox, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).add(12, 12, 12).add(jSeparator2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 8, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(chargeOneJCheckBox, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(chargeTwoJCheckBox, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(chargeOverTwoJCheckBox, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).add(13, 13, 13))); spectrumJXTable.setModel(new javax.swing.table.DefaultTableModel( new Object[][]{}, new String[]{ " ", "m/z", "Intensity" }) { Class[] types = new Class[]{ java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class }; boolean[] canEdit = new boolean[]{ false, false, false }; @Override public Class getColumnClass(int columnIndex) { return types[columnIndex]; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return canEdit[columnIndex]; } }); spectrumJXTable.setOpaque(false); jScrollPane1.setViewportView(spectrumJXTable); org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup().addContainerGap().add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING).add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 632, Short.MAX_VALUE).add(jPanel3Layout.createSequentialGroup().add(spectrumJPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 578, Short.MAX_VALUE).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(jPanel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 48, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))).addContainerGap())); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(jPanel3Layout.createSequentialGroup().add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(spectrumJPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)).addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED).add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 97, Short.MAX_VALUE).addContainerGap())); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(layout.createSequentialGroup().addContainerGap().add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(layout.createSequentialGroup().add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).add(18, 18, 18).add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)).add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)).addContainerGap())); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(layout.createSequentialGroup().addContainerGap().add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING).add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE).add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)).addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED).add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE).addContainerGap())); pack(); } /** * ToDo: JavaDoc missing... * * @param aXTandemFile * @param lastSelectedFolder */ void insertFiles(String aXTandemFile, String lastSelectedFolder) { iXTandemFileString = aXTandemFile; progressDialog = new ProgressDialog(this); // Set the last selected folder this.lastSelectedFolder = lastSelectedFolder; // Set the title of the application setTitle(APPTITLE + " " + new Properties().getVersion() + " --- " + new File(iXTandemFileString).getPath()); // Thread for the progress dialog. final Thread t = new Thread(new Runnable() { public void run() { progressDialog.setTitle("Parsing XML File. Please Wait..."); progressDialog.setIndeterminate(true); progressDialog.setVisible(true); } }, "ProgressDialog"); t.start(); // Thread for the parsing of the XTandem xml file. new Thread("ParserThread") { @Override public void run() { spectraTable.setSortable(false); while (spectraTable.getModel().getRowCount() > 0) { ((DefaultTableModel) spectraTable.getModel()).removeRow(0); } while (spectrumJXTable.getModel().getRowCount() > 0) { ((DefaultTableModel) spectrumJXTable.getModel()).removeRow(0); } while (identificationsTable.getModel().getRowCount() > 0) { ((DefaultTableModel) identificationsTable.getModel()).removeRow(0); } modificationDetailsJLabel.setText(""); while (spectrumJPanel.getComponents().length > 0) { spectrumJPanel.remove(0); } spectrumJPanel.validate(); spectrumJPanel.repaint(); // Parse the X!Tandem file. try { iXTandemFile = new XTandemFile(iXTandemFileString); } catch (OutOfMemoryError error) { Runtime.getRuntime().gc(); JOptionPane.showMessageDialog(null, "The task used up all the available memory and had to be stopped.\n" + "Memory boundaries are set in ../Properties/JavaOptions.txt.", "Out of Memory Error", JOptionPane.ERROR_MESSAGE); error.printStackTrace(); System.exit(0); } catch (SAXException saxException) { saxException.getMessage(); JOptionPane.showMessageDialog(null, "Error during parsing the xml file!\n" + saxException.getMessage() + "\n" + "Please load xml file in correct format...", "Parser error", JOptionPane.ERROR_MESSAGE); System.exit(0); } ionCoverageErrorMargin = Parameters.FRAGMENTMASSERROR; // Set up the hash maps peptideMap = new HashMap<Integer, ArrayList<Peptide>>(); proteinLabelMap = new HashMap<String, String>(); accMap = new HashMap<Integer, String>(); allMzValues = new HashMap<Integer, ArrayList<Double>>(); allIntensityValues = new HashMap<Integer, ArrayList<Double>>(); allFixMods = new HashMap<String, ArrayList<Modification>>(); allVarMods = new HashMap<String, ArrayList<Modification>>(); ionsMap = new HashMap<String, FragmentIon[]>(); // Iterate over all the spectra Iterator<Spectrum> iter = iXTandemFile.getSpectraIterator(); // Prepare everything for the peptides. PeptideMap pepMap = iXTandemFile.getPeptideMap(); // Prepare everything for the proteins. ProteinMap protMap = iXTandemFile.getProteinMap(); while (iter.hasNext()) { // Get the next spectrum. Spectrum spectrum = iter.next(); int spectrumNumber = spectrum.getSpectrumNumber(); // Get the peptide hits. ArrayList<Peptide> pepList = pepMap.getAllPeptides(spectrumNumber); for (Peptide peptide : pepList) { List<Domain> domainList = peptide.getDomains(); for (Domain domain : domainList) { Protein protein = protMap.getProtein(domain.getProteinKey()); if (protein != null) { String protAccession; if (protein.getDescription() != null) { protAccession = protein.getDescription(); } else { protAccession = protein.getLabel(); } proteinLabelMap.put(domain.getDomainKey(), protAccession); } // Do the modifications ArrayList<Modification> fixModList = iXTandemFile.getModificationMap().getFixedModifications(domain.getDomainKey()); ArrayList<Modification> varModList = iXTandemFile.getModificationMap().getVariableModifications(domain.getDomainKey()); allFixMods.put(domain.getDomainKey(), fixModList); allVarMods.put(domain.getDomainKey(), varModList); // Get the fragment ions Vector IonVector = iXTandemFile.getFragmentIonsForPeptide(peptide, domain); // Get all the ion types from the vector for (int i = 0; i < IonVector.size(); i++) { FragmentIon[] ions = (FragmentIon[]) IonVector.get(i); ionsMap.put(domain.getDomainKey() + "_" + i, ions); } } } // Get the support data for each spectrum. SupportData supportData = iXTandemFile.getSupportData(spectrumNumber); // Fill the peptide map: for each spectrum get the corressponding peptide list. peptideMap.put(spectrumNumber, pepList); //int spectrumID = spectrum.getSpectrumId(); String label = supportData.getFragIonSpectrumDescription(); int precursorCharge = spectrum.getPrecursorCharge(); double precursorMh = spectrum.getPrecursorMh(); String accession = spectrum.getLabel(); boolean identified; if (pepList.isEmpty()) { identified = false; } else { identified = true; } accMap.put(spectrumNumber, accession); // Add the values to the table (model). ((DefaultTableModel) spectraTable.getModel()).addRow(new Object[]{ spectrumNumber, label, precursorMh, precursorCharge, identified }); // Initialize the array lists ArrayList<Double> mzValues; ArrayList<Double> intensityValues; // Get the spectrum fragment mz and intensity values mzValues = supportData.getXValuesFragIonMass2Charge(); intensityValues = supportData.getYValuesFragIonMass2Charge(); // Fill the maps allMzValues.put(Integer.valueOf(spectrumNumber), mzValues); allIntensityValues.put(Integer.valueOf(spectrumNumber), intensityValues); } spectraTable.setSortable(true); progressDialog.setVisible(false); progressDialog.dispose(); // select the first row in the spectra files table if (spectraTable.getRowCount() > 0) { spectraTable.setRowSelectionInterval(0, 0); spectraJXTableMouseClicked(null); } } }.start(); } /** * This method filters the annotations. * * @param annotations the annotations to be filtered * @return the filtered annotations */ private Vector<DefaultSpectrumAnnotation> filterAnnotations(Vector<DefaultSpectrumAnnotation> annotations) { Vector<DefaultSpectrumAnnotation> filteredAnnotations = new Vector(); for (int i = 0; i < annotations.size(); i++) { String currentLabel = annotations.get(i).getLabel(); boolean useAnnotation = true; // check ion type if (currentLabel.lastIndexOf("a") != -1) { if (!aIonsJCheckBox.isSelected()) { useAnnotation = false; } } else if (currentLabel.lastIndexOf("b") != -1) { if (!bIonsJCheckBox.isSelected()) { useAnnotation = false; } } else if (currentLabel.lastIndexOf("c") != -1) { if (!cIonsJCheckBox.isSelected()) { useAnnotation = false; } } else if (currentLabel.lastIndexOf("x") != -1) { if (!xIonsJCheckBox.isSelected()) { useAnnotation = false; } } else if (currentLabel.lastIndexOf("y") != -1) { if (!yIonsJCheckBox.isSelected()) { useAnnotation = false; } } else if (currentLabel.lastIndexOf("z") != -1) { if (!zIonsJCheckBox.isSelected()) { useAnnotation = false; } } // check ion charge if (useAnnotation) { if (currentLabel.lastIndexOf("+") == -1) { if (!chargeOneJCheckBox.isSelected()) { useAnnotation = false; } } else if (currentLabel.lastIndexOf("+++") != -1) { if (!chargeOverTwoJCheckBox.isSelected()) { useAnnotation = false; } } else if (currentLabel.lastIndexOf("++") != -1) { if (!chargeTwoJCheckBox.isSelected()) { useAnnotation = false; } } } if (useAnnotation) { filteredAnnotations.add(annotations.get(i)); } } return filteredAnnotations; } /** * Opens the file selector dialog for loading another X!Tandem xml file. * * @param evt */ private void openActionPerformed(ActionEvent evt) { new FileSelector(this, APPTITLE); } /** * @see #aIonsJCheckBoxActionPerformed(java.awt.event.ActionEvent) */ private void bIonsJCheckBoxActionPerformed() { aIonsJCheckBoxActionPerformed(null); } /** * @see #aIonsJCheckBoxActionPerformed(java.awt.event.ActionEvent) */ private void cIonsJCheckBoxActionPerformed() { aIonsJCheckBoxActionPerformed(null); } /** * @see #aIonsJCheckBoxActionPerformed(java.awt.event.ActionEvent) */ private void yIonsJCheckBoxActionPerformed() { aIonsJCheckBoxActionPerformed(null); } /** * @see #aIonsJCheckBoxActionPerformed(java.awt.event.ActionEvent) */ private void xIonsJCheckBoxActionPerformed() { aIonsJCheckBoxActionPerformed(null); } /** * @see #aIonsJCheckBoxActionPerformed(java.awt.event.ActionEvent) */ private void zIonsJCheckBoxActionPerformed() { aIonsJCheckBoxActionPerformed(null); } /** * @see #aIonsJCheckBoxActionPerformed(java.awt.event.ActionEvent) */ private void chargeOneJCheckBoxActionPerformed() { aIonsJCheckBoxActionPerformed(null); } /** * @see #aIonsJCheckBoxActionPerformed(java.awt.event.ActionEvent) */ private void chargeTwoJCheckBoxActionPerformed() { aIonsJCheckBoxActionPerformed(null); } /** * @see #aIonsJCheckBoxActionPerformed(java.awt.event.ActionEvent) */ private void chargeOverTwoJCheckBoxActionPerformed() { aIonsJCheckBoxActionPerformed(null); } /** * Updates the ion coverage annotations * * @param evt */ private void aIonsJCheckBoxActionPerformed(ActionEvent evt) { if (identificationsTable.getRowCount() > 0) { int selectedRow = 0; if (identificationsTable.getRowCount() > 1 && identificationsTable.getSelectedRow() != -1) { selectedRow = identificationsTable.getSelectedRow(); } Vector<DefaultSpectrumAnnotation> currentAnnotations = allAnnotations.get( identificationsTable.getValueAt(selectedRow, 1) + "_" + identificationsTable.getValueAt(selectedRow, 7)); spectrumPanel.setAnnotations(filterAnnotations(currentAnnotations)); spectrumPanel.validate(); spectrumPanel.repaint(); } } /** * @see #spectraJXTableMouseClicked(java.awt.event.MouseEvent) */ private void spectraJXTableKeyReleased(KeyEvent evt) { spectraJXTableMouseClicked(null); } /** * Update the tables based on the spectrum selected. * * @param evt */ private void spectraJXTableMouseClicked(MouseEvent evt) { // Set the cursor into the wait status. this.setCursor(new Cursor(Cursor.WAIT_CURSOR)); int row = spectraTable.getSelectedRow(); // Condition if one row is selected. if (row != -1) { List<Double> mzValues = allMzValues.get((Integer) spectraTable.getValueAt(row, 0)); List<Double> intensityValues = allIntensityValues.get((Integer) spectraTable.getValueAt(row, 0)); // Empty the spectrum table. while (spectrumJXTable.getRowCount() > 0) { ((DefaultTableModel) spectrumJXTable.getModel()).removeRow(0); } spectrumJXTable.scrollRectToVisible(spectrumJXTable.getCellRect(0, 0, false)); // Empty the spectrum panel. while (spectrumJPanel.getComponents().length > 0) { spectrumJPanel.remove(0); } double[] mzValuesAsDouble = new double[mzValues.size()]; double[] intensityValuesAsDouble = new double[mzValues.size()]; // Insert the spectrum details into the table for (int i = 0; i < mzValues.size(); i++) { ((DefaultTableModel) spectrumJXTable.getModel()).addRow(new Object[]{ Integer.valueOf(i + 1), mzValues.get(i), intensityValues.get(i) }); mzValuesAsDouble[i] = mzValues.get(i); intensityValuesAsDouble[i] = intensityValues.get(i); } exportSelectedSpectrumMenuItem.setEnabled(true); // Updating the spectrum panel spectrumPanel = new SpectrumPanel( mzValuesAsDouble, intensityValuesAsDouble, ((Double) spectraTable.getValueAt(row, 2)), "" + spectraTable.getValueAt(row, 3), ((String) spectraTable.getValueAt(row, 1)), 60, false); spectrumJPanel.add(spectrumPanel); spectrumJPanel.validate(); spectrumJPanel.repaint(); // Empty the identifications tables while (identificationsTable.getRowCount() > 0) { ((DefaultTableModel) identificationsTable.getModel()).removeRow(0); } allAnnotations = new HashMap(); // Clear the modifications details legend modificationDetailsJLabel.setText(""); // Iterate over all the peptides as identifications (domains) if (peptideMap.get((Integer) spectraTable.getValueAt(row, 0)) != null) { ArrayList<Peptide> pepList = peptideMap.get((Integer) spectraTable.getValueAt(row, 0)); Iterator pepIter = pepList.iterator(); String modificationDetails = ""; while (pepIter.hasNext()) { Peptide peptide = (Peptide) pepIter.next(); List<Domain> domainList = peptide.getDomains(); for (Domain domain : domainList) { String sequence = domain.getDomainSequence(); String[] modifications = new String[sequence.length()]; for (int i = 0; i < modifications.length; i++) { modifications[i] = ""; } String modifiedSequence = ""; String nTerminal = ""; String cTerminal = ""; ArrayList<Modification> fixedModList = allFixMods.get(domain.getDomainKey()); ArrayList<Modification> varModList = allVarMods.get(domain.getDomainKey()); // Handle fixed modifications if (fixedModList != null) { for (int i = 0; i < fixedModList.size(); i++) { FixedModification fixMod = (FixedModification) fixedModList.get(i); int[] modRes = new int[domain.getDomainSequence().length()]; int modIndex = Integer.parseInt(fixMod.getLocation()) - domain.getDomainStart(); modRes[modIndex] = fixMod.getNumber(); for (int j = 0; j < modRes.length; j++) { if (modRes[j] > 0) { modifications[j] += "<" + "M" + modRes[j] + "*" + ">"; } } } } //Handle variable modifications if (varModList != null) { for (int i = 0; i < varModList.size(); i++) { VariableModification varMod = (VariableModification) varModList.get(i); int[] modRes = new int[domain.getDomainSequence().length()]; int modIndex = Integer.parseInt(varMod.getLocation()) - domain.getDomainStart(); modRes[modIndex] = varMod.getNumber(); for (int j = 0; j < modRes.length; j++) { if (modRes[j] > 0) { modifications[j] += "<" + "M" + modRes[j] + "^" + ">"; } } } } // Cycle through all the modifications and extract the modification type if possible for (int i = 0; i < modifications.length; i++) { // Add the amino acid itself to the sequence modifiedSequence += sequence.substring(i, i + 1); if (!modifications[i].equalsIgnoreCase("")) { String[] residues = modifications[i].split(">"); for (int j = 0; j < residues.length; j++) { String currentMod = residues[j] + ">"; int fixModIndex = 0; int varModIndex = 0; if (currentMod.length() > 0) { if (currentMod.contains("*")) { fixModIndex = (Integer.parseInt(currentMod.substring(2, 3)) - 1); } else if (currentMod.contains("^")) { varModIndex = (Integer.parseInt(currentMod.substring(2, 3)) - 1); } } if (modificationDetails.lastIndexOf(currentMod) == -1) { if (fixedModList.size() > 0 && currentMod.contains("*")) { modificationDetails += currentMod + " " + fixedModList.get(fixModIndex).getName(); if (fixedModList.get(fixModIndex).isSubstitution()) { modificationDetails += " Sub. (orignal AA): " + fixedModList.get(fixModIndex).getSubstitutedAminoAcid(); } modificationDetails += ", "; } else if (varModList.size() > 0 && currentMod.contains("^")) { modificationDetails += currentMod + " " + varModList.get(varModIndex).getName(); if (varModList.get(varModIndex).isSubstitution()) { modificationDetails += " Sub. (orignal AA): " + varModList.get(varModIndex).getSubstitutedAminoAcid(); } modificationDetails += ", "; } modifiedSequence += currentMod; } else { modifiedSequence += currentMod; } } } } // N-Terminal if (nTerminal.length() == 0) { nTerminal = "NH2-"; } else { nTerminal += "-"; } // C-Terminal if (cTerminal.length() == 0) { cTerminal = "-COOH"; } else { cTerminal = "-" + cTerminal; } int[][] ionCoverage = new int[sequence.length() + 1][12]; Vector<DefaultSpectrumAnnotation> currentAnnotations = new Vector(); for (int i = 0; i < 12; i++) { FragmentIon[] ions = ionsMap.get(domain.getDomainKey() + "_" + i); for (FragmentIon ion : ions) { int ionNumber = ion.getNumber(); int ionType = ion.getType(); double mzValue = ion.getMZ(); Color color; if (i % 2 == 0) { color = Color.BLUE; } else { color = Color.BLACK; } if (ionType == FragmentIon.A_ION) { ionCoverage[ionNumber][0]++; } if (ionType == FragmentIon.AH2O_ION) { ionCoverage[ionNumber][1]++; } if (ionType == FragmentIon.ANH3_ION) { ionCoverage[ionNumber][2]++; } if (ionType == FragmentIon.B_ION) { ionCoverage[ionNumber][3]++; } if (ionType == FragmentIon.BH2O_ION) { ionCoverage[ionNumber][4]++; } if (ionType == FragmentIon.BNH3_ION) { ionCoverage[ionNumber][5]++; } if (ionType == FragmentIon.C_ION) { ionCoverage[ionNumber][6]++; } if (ionType == FragmentIon.X_ION) { ionCoverage[ionNumber][7]++; } if (ionType == FragmentIon.Y_ION) { ionCoverage[ionNumber][8]++; } if (ionType == FragmentIon.YH2O_ION) { ionCoverage[ionNumber][9]++; } if (ionType == FragmentIon.YNH3_ION) { ionCoverage[ionNumber][10]++; } if (ionType == FragmentIon.Z_ION) { ionCoverage[ionNumber][11]++; } // Use standard ion type names, such as y5++ String ionDesc = ion.getLetter(); if (ionNumber > 0) { ionDesc += ionNumber; } if (ion.getCharge() > 1) { for (int j = 0; j < ion.getCharge(); j++) { ionDesc += "+"; } } currentAnnotations.add(new DefaultSpectrumAnnotation(mzValue, ionCoverageErrorMargin, color, ionDesc)); } } allAnnotations.put((sequence + "_" + domain.getDomainExpect()), currentAnnotations); // only add the annotations for the first identification if (allAnnotations.size() == 1) { // add the ion coverage annotations to the spectrum panel spectrumPanel.setAnnotations(filterAnnotations(currentAnnotations)); spectrumPanel.validate(); spectrumPanel.repaint(); } // add the ion coverage to the modified sequence int[][] ionCoverageProcessed = new int[sequence.length()][2]; // Process termini. // B1 ion (N-terminal residue) if (ionCoverage[1][3] > 0 || ionCoverage[1][4] > 0 || ionCoverage[1][5] > 0) { ionCoverageProcessed[0][0] = 1; } // Y1 ion (C-terminal residue) if (ionCoverage[1][8] > 0 || ionCoverage[1][9] > 0 || ionCoverage[1][10] > 0) { ionCoverageProcessed[ionCoverage.length - 2][1] = 1; } // Last B-ion (C-terminal residue) if (ionCoverage[ionCoverage.length - 1][3] > 0 || ionCoverage[ionCoverage.length - 1][4] > 0 || ionCoverage[ionCoverage.length - 1][5] > 0) { ionCoverageProcessed[ionCoverage.length - 2][0] = 1; } // Last Y-ion (N-terminal residue) if (ionCoverage[ionCoverage.length - 1][8] > 0 || ionCoverage[ionCoverage.length - 1][9] > 0 || ionCoverage[ionCoverage.length - 1][10] > 0) { ionCoverageProcessed[0][1] = 1; } for (int i = 2; i < ionCoverage.length - 1; i++) { if (ionCoverage[i][3] > 0 && ionCoverage[i - 1][3] > 0 || ionCoverage[i][4] > 0 && ionCoverage[i - 1][4] > 0 || ionCoverage[i][5] > 0 && ionCoverage[i - 1][5] > 0) { ionCoverageProcessed[i - 1][0] = 1; } else { ionCoverageProcessed[i - 1][0] = 0; } if (ionCoverage[i][8] > 0 && ionCoverage[i - 1][8] > 0 || ionCoverage[i][9] > 0 && ionCoverage[i - 1][9] > 0 || ionCoverage[i][10] > 0 && ionCoverage[i - 1][10] > 0) { ionCoverageProcessed[ionCoverage.length - 1 - i][1] = 1; } else { ionCoverageProcessed[ionCoverage.length - 1 - i][1] = 0; } } String modifiedSequenceColorCoded = "<html>"; // add nTerminal if (!nTerminal.startsWith("<")) { modifiedSequenceColorCoded += nTerminal; } else { modifiedSequenceColorCoded += "&lt;"; modifiedSequenceColorCoded += nTerminal.substring(1, nTerminal.length() - 2); modifiedSequenceColorCoded += "&gt;-"; } int aminoAcidCounter = 0; for (int i = 0; i < modifiedSequence.length(); i++) { if (modifiedSequence.charAt(i) == '<') { if (ionCoverageProcessed[aminoAcidCounter - 1][0] > 0) { // b ions modifiedSequenceColorCoded += "<u>"; } if (ionCoverageProcessed[aminoAcidCounter - 1][1] > 0) { // y ions modifiedSequenceColorCoded += "<font color=\"red\">"; } modifiedSequenceColorCoded += "&lt;"; i++; while (modifiedSequence.charAt(i) != '>') { modifiedSequenceColorCoded += modifiedSequence.charAt(i++); } modifiedSequenceColorCoded += "&gt;"; if (ionCoverageProcessed[aminoAcidCounter - 1][0] > 0) { // b ions modifiedSequenceColorCoded += "</u>"; } if (ionCoverageProcessed[aminoAcidCounter - 1][1] > 0) { // y ions modifiedSequenceColorCoded += "</font>"; } } else { if (ionCoverageProcessed[aminoAcidCounter][0] > 0) { // b ions modifiedSequenceColorCoded += "<u>"; } if (ionCoverageProcessed[aminoAcidCounter][1] > 0) { // y ions modifiedSequenceColorCoded += "<font color=\"red\">"; } modifiedSequenceColorCoded += modifiedSequence.charAt(i); if (ionCoverageProcessed[aminoAcidCounter][0] > 0) { // b ions modifiedSequenceColorCoded += "</u>"; } if (ionCoverageProcessed[aminoAcidCounter][1] > 0) { // y ions modifiedSequenceColorCoded += "</font>"; } aminoAcidCounter++; } modifiedSequenceColorCoded += "<font color=\"black\">"; } // add cTerminal if (!cTerminal.startsWith("-<")) { modifiedSequenceColorCoded += cTerminal; } else { modifiedSequenceColorCoded += "-&lt;"; modifiedSequenceColorCoded += cTerminal.substring(2, cTerminal.length() - 1); modifiedSequenceColorCoded += "&gt;"; } modifiedSequenceColorCoded += "</html>"; // Calculate the theoretical mass of the domain double theoMass = (domain.getDomainMh() + domain.getDomainDeltaMh()); // parse the header Header header = Header.parseFromFASTA(proteinLabelMap.get(domain.getDomainKey())); String accession = header.getAccession(); String description = header.getDescription(); ((DefaultTableModel) identificationsTable.getModel()).addRow(new Object[]{ (Integer) spectraTable.getValueAt(row, 0), sequence, modifiedSequenceColorCoded, domain.getDomainStart(), domain.getDomainEnd(), new Double(domain.getDomainMh()), new Double(theoMass), new Float(domain.getDomainExpect()), accession, description}); } } if (modificationDetails.endsWith(", ")) { modificationDetails = modificationDetails.substring(0, modificationDetails.length() - 2); } if (modificationDetails.length() > 0) { modificationDetailsJLabel.setText(modificationDetails + MODIFICATIONSLEGEND); } if (identificationsTable.getRowCount() > 1) { identificationsTable.setRowSelectionInterval(0, 0); } } } // At the end set the cursor back to default. this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } /** * Method for exporting the contents of the spectra files table. * * @param evt */ private void exportSpectraFilesTable(ActionEvent evt) { JFileChooser chooser = new JFileChooser(lastSelectedFolder); chooser.setFileFilter(new TxtFileFilter()); chooser.setMultiSelectionEnabled(false); chooser.setDialogTitle("Export Spectra File Details"); File selectedFile; int returnVal = chooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { selectedFile = chooser.getSelectedFile(); if (!selectedFile.getName().toLowerCase().endsWith(".txt")) { selectedFile = new File(selectedFile.getAbsolutePath() + ".txt"); } while (selectedFile.exists()) { int option = JOptionPane.showConfirmDialog(this, "The file " + chooser.getSelectedFile().getName() + " already exists. Replace file?", "Replace File?", JOptionPane.YES_NO_CANCEL_OPTION); if (option == JOptionPane.NO_OPTION) { chooser = new JFileChooser(lastSelectedFolder); chooser.setFileFilter(new TxtFileFilter()); chooser.setMultiSelectionEnabled(false); chooser.setDialogTitle("Export Spectra File Details"); returnVal = chooser.showSaveDialog(this); if (returnVal == JFileChooser.CANCEL_OPTION) { return; } else { selectedFile = chooser.getSelectedFile(); if (!selectedFile.getName().toLowerCase().endsWith(".txt")) { selectedFile = new File(selectedFile.getAbsolutePath() + ".txt"); } } } else { // YES option break; } } this.setCursor(new Cursor(Cursor.WAIT_CURSOR)); try { selectedFile = chooser.getSelectedFile(); if (!selectedFile.getName().toLowerCase().endsWith(".txt")) { selectedFile = new File(selectedFile.getAbsolutePath() + ".txt"); } if (selectedFile.exists()) { selectedFile.delete(); } selectedFile.createNewFile(); FileWriter f = new FileWriter(selectedFile); // add the column headers for (int j = 0; j < spectraTable.getColumnCount() - 1; j++) { f.write(spectraTable.getColumnName(j) + "\t"); } f.write(spectraTable.getColumnName(spectraTable.getColumnCount() - 1) + "\n"); // add the table contents for (int i = 0; i < spectraTable.getRowCount(); i++) { for (int j = 0; j < spectraTable.getColumnCount() - 1; j++) { f.write(spectraTable.getValueAt(i, j) + "\t"); } f.write(spectraTable.getValueAt(i, spectraTable.getColumnCount() - 1) + "\n"); } f.close(); lastSelectedFolder = selectedFile.getPath(); } catch (IOException ex) { JOptionPane.showMessageDialog(this, "An error occured when exporting the spectra file details.", "Error Exporting Spectra Files", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } /** * This method exports all the identifications. * * @param evt */ private void exportAllIdentifications(ActionEvent evt) { JFileChooser chooser = new JFileChooser(lastSelectedFolder); chooser.setFileFilter(new TxtFileFilter()); chooser.setMultiSelectionEnabled(false); chooser.setDialogTitle("Export All Identifications"); File selectedFile; int returnVal = chooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { selectedFile = chooser.getSelectedFile(); if (!selectedFile.getName().toLowerCase().endsWith(".txt")) { selectedFile = new File(selectedFile.getAbsolutePath() + ".txt"); } while (selectedFile.exists()) { int option = JOptionPane.showConfirmDialog(this, "The file " + chooser.getSelectedFile().getName() + " already exists. Replace file?", "Replace File?", JOptionPane.YES_NO_CANCEL_OPTION); if (option == JOptionPane.NO_OPTION) { chooser = new JFileChooser(lastSelectedFolder); chooser.setFileFilter(new TxtFileFilter()); chooser.setMultiSelectionEnabled(false); chooser.setDialogTitle("Export All Identifications"); returnVal = chooser.showSaveDialog(this); if (returnVal == JFileChooser.CANCEL_OPTION) { return; } else { selectedFile = chooser.getSelectedFile(); if (!selectedFile.getName().toLowerCase().endsWith(".txt")) { selectedFile = new File(selectedFile.getAbsolutePath() + ".txt"); } } } else { // YES option break; } } this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); try { selectedFile = chooser.getSelectedFile(); if (!selectedFile.getName().toLowerCase().endsWith(".txt")) { selectedFile = new File(selectedFile.getAbsolutePath() + ".txt"); } if (selectedFile.exists()) { selectedFile.delete(); } selectedFile.createNewFile(); FileWriter f = new FileWriter(selectedFile); // add the column headers for (int j = 0; j < identificationsTable.getColumnCount() - 1; j++) { if (j == 2) { f.write("Modified Sequence" + "\t"); f.write("Ion Coverage" + "\t"); } else { f.write(identificationsTable.getColumnName(j) + "\t"); } } f.write(identificationsTable.getColumnName(identificationsTable.getColumnCount() - 1) + "\n"); // iterate all the identifications and print them to the file // Iterate over all the spectra Iterator<Spectrum> iter = iXTandemFile.getSpectraIterator(); String modificationDetails = ""; while (iter.hasNext()) { ArrayList<Peptide> pepList = peptideMap.get(iter.next().getSpectrumNumber()); for (Peptide peptide : pepList) { List<Domain> domainList = peptide.getDomains(); for (Domain domain : domainList) { String sequence = domain.getDomainSequence(); String[] modifications = new String[sequence.length()]; for (int i = 0; i < modifications.length; i++) { modifications[i] = ""; } String modifiedSequence = ""; String nTerminal = ""; String cTerminal = ""; ArrayList<Modification> fixedModList = allFixMods.get(domain.getDomainKey()); ArrayList<Modification> varModList = allVarMods.get(domain.getDomainKey()); // Handle fixed modifications if (fixedModList != null) { for (int i = 0; i < fixedModList.size(); i++) { FixedModification fixMod = (FixedModification) fixedModList.get(i); int[] modRes = new int[domain.getDomainSequence().length()]; int modIndex = Integer.parseInt(fixMod.getLocation()) - domain.getDomainStart(); modRes[modIndex] = fixMod.getNumber(); for (int j = 0; j < modRes.length; j++) { if (modRes[j] > 0) { modifications[j] += "<" + "M" + modRes[j] + "*" + ">"; } } } } // Handle variable modifications if (varModList != null) { for (int i = 0; i < varModList.size(); i++) { VariableModification varMod = (VariableModification) varModList.get(i); int[] modRes = new int[domain.getDomainSequence().length()]; int modIndex = Integer.parseInt(varMod.getLocation()) - domain.getDomainStart(); modRes[modIndex] = varMod.getNumber(); for (int j = 0; j < modRes.length; j++) { if (modRes[j] > 0) { modifications[j] += "<" + "M" + modRes[j] + "*" + ">"; } } } } // Cycle through all the modifications and extract the modification type if possible for (int i = 0; i < modifications.length; i++) { // Add the amino acid itself to the sequence modifiedSequence += sequence.substring(i, i + 1); if (!modifications[i].equalsIgnoreCase("")) { String[] residues = modifications[i].split(">"); for (int j = 0; j < residues.length; j++) { String currentMod = residues[j] + ">"; if (modificationDetails.lastIndexOf(currentMod) == -1) { if (fixedModList.size() > 0) { modificationDetails += currentMod + " " + fixedModList.get(j).getName() + ", "; } else if (varModList.size() > 0) { modificationDetails += currentMod + " " + varModList.get(j).getName() + ", "; } modifiedSequence += currentMod; } else { modifiedSequence += currentMod; } } } } // N-Terminal if (nTerminal.length() == 0) { nTerminal = "NH2-"; } else { nTerminal += "-"; } // C-Terminal if (cTerminal.length() == 0) { cTerminal = "-COOH"; } else { cTerminal = "-" + cTerminal; } // add ion coverage to peptide sequence int[][] ionCoverage = new int[sequence.length() + 1][12]; for (int i = 0; i < 12; i++) { FragmentIon[] ions = ionsMap.get(domain.getDomainKey() + "_" + i); for (FragmentIon ion : ions) { int ionNumber = ion.getNumber(); int ionType = ion.getType(); double mzValue = ion.getMZ(); Color color; if (i % 2 == 0) { color = Color.BLUE; } else { color = Color.BLACK; } if (ionType == FragmentIon.A_ION) { ionCoverage[ionNumber][0]++; } if (ionType == FragmentIon.AH2O_ION) { ionCoverage[ionNumber][1]++; } if (ionType == FragmentIon.ANH3_ION) { ionCoverage[ionNumber][2]++; } if (ionType == FragmentIon.B_ION) { ionCoverage[ionNumber][3]++; } if (ionType == FragmentIon.BH2O_ION) { ionCoverage[ionNumber][4]++; } if (ionType == FragmentIon.BNH3_ION) { ionCoverage[ionNumber][5]++; } if (ionType == FragmentIon.C_ION) { ionCoverage[ionNumber][6]++; } if (ionType == FragmentIon.X_ION) { ionCoverage[ionNumber][7]++; } if (ionType == FragmentIon.Y_ION) { ionCoverage[ionNumber][8]++; } if (ionType == FragmentIon.YH2O_ION) { ionCoverage[ionNumber][9]++; } if (ionType == FragmentIon.YNH3_ION) { ionCoverage[ionNumber][10]++; } if (ionType == FragmentIon.Z_ION) { ionCoverage[ionNumber][11]++; } } } // add the ion coverage to the modified sequence int[][] ionCoverageProcessed = new int[sequence.length()][2]; // Process termini. // B1 ion (N-terminal residue) if (ionCoverage[1][3] > 0 || ionCoverage[1][4] > 0 || ionCoverage[1][5] > 0) { ionCoverageProcessed[0][0] = 1; } // Y1 ion (C-terminal residue) if (ionCoverage[1][8] > 0 || ionCoverage[1][9] > 0 || ionCoverage[1][10] > 0) { ionCoverageProcessed[ionCoverage.length - 2][1] = 1; } // Last B-ion (C-terminal residue) if (ionCoverage[ionCoverage.length - 1][3] > 0 || ionCoverage[ionCoverage.length - 1][4] > 0 || ionCoverage[ionCoverage.length - 1][5] > 0) { ionCoverageProcessed[ionCoverage.length - 2][0] = 1; } // Last Y-ion (N-terminal residue) if (ionCoverage[ionCoverage.length - 1][8] > 0 || ionCoverage[ionCoverage.length - 1][9] > 0 || ionCoverage[ionCoverage.length - 1][10] > 0) { ionCoverageProcessed[0][1] = 1; } for (int i = 2; i < ionCoverage.length - 1; i++) { if (ionCoverage[i][3] > 0 && ionCoverage[i - 1][3] > 0 || ionCoverage[i][4] > 0 && ionCoverage[i - 1][4] > 0 || ionCoverage[i][5] > 0 && ionCoverage[i - 1][5] > 0) { ionCoverageProcessed[i - 1][0] = 1; } else { ionCoverageProcessed[i - 1][0] = 0; } if (ionCoverage[i][8] > 0 && ionCoverage[i - 1][8] > 0 || ionCoverage[i][9] > 0 && ionCoverage[i - 1][9] > 0 || ionCoverage[i][10] > 0 && ionCoverage[i - 1][10] > 0) { ionCoverageProcessed[ionCoverage.length - 1 - i][1] = 1; } else { ionCoverageProcessed[ionCoverage.length - 1 - i][1] = 0; } } String modifiedSequenceColorCoded = "<html>"; // add nTerminal if (!nTerminal.startsWith("<")) { modifiedSequenceColorCoded += nTerminal; } else { modifiedSequenceColorCoded += "&lt;"; modifiedSequenceColorCoded += nTerminal.substring(1, nTerminal.length() - 2); modifiedSequenceColorCoded += "&gt;-"; } int aminoAcidCounter = 0; for (int i = 0; i < modifiedSequence.length(); i++) { if (modifiedSequence.charAt(i) == '<') { if (ionCoverageProcessed[aminoAcidCounter - 1][0] > 0) { // b ions modifiedSequenceColorCoded += "<u>"; } if (ionCoverageProcessed[aminoAcidCounter - 1][1] > 0) { // y ions modifiedSequenceColorCoded += "<font color=\"red\">"; } modifiedSequenceColorCoded += "&lt;"; i++; while (modifiedSequence.charAt(i) != '>') { modifiedSequenceColorCoded += modifiedSequence.charAt(i++); } modifiedSequenceColorCoded += "&gt;"; if (ionCoverageProcessed[aminoAcidCounter - 1][0] > 0) { // b ions modifiedSequenceColorCoded += "</u>"; } if (ionCoverageProcessed[aminoAcidCounter - 1][1] > 0) { // y ions modifiedSequenceColorCoded += "</font>"; } } else { if (ionCoverageProcessed[aminoAcidCounter][0] > 0) { // b ions modifiedSequenceColorCoded += "<u>"; } if (ionCoverageProcessed[aminoAcidCounter][1] > 0) { // y ions modifiedSequenceColorCoded += "<font color=\"red\">"; } modifiedSequenceColorCoded += modifiedSequence.charAt(i); if (ionCoverageProcessed[aminoAcidCounter][0] > 0) { // b ions modifiedSequenceColorCoded += "</u>"; } if (ionCoverageProcessed[aminoAcidCounter][1] > 0) { // y ions modifiedSequenceColorCoded += "</font>"; } aminoAcidCounter++; } modifiedSequenceColorCoded += "<font color=\"black\">"; } // add cTerminal if (!cTerminal.startsWith("-<")) { modifiedSequenceColorCoded += cTerminal; } else { modifiedSequenceColorCoded += "-&lt;"; modifiedSequenceColorCoded += cTerminal.substring(2, cTerminal.length() - 1); modifiedSequenceColorCoded += "&gt;"; } modifiedSequenceColorCoded += "</html>"; modifiedSequence = nTerminal + modifiedSequence + cTerminal; double theoMass = (domain.getDomainMh() + domain.getDomainDeltaMh()); String accession = proteinLabelMap.get(domain.getDomainKey()); f.write(peptide.getSpectrumNumber() + "\t" + sequence + "\t" + modifiedSequence + "\t" + modifiedSequenceColorCoded + "\t" + domain.getDomainStart() + "\t" + domain.getDomainEnd() + "\t" + new Double(domain.getDomainMh()) + "\t" + theoMass + "\t" + new Float(domain.getDomainExpect()) + "\t" + accession + "\n"); } } } f.close(); lastSelectedFolder = selectedFile.getPath(); } catch (IOException ex) { JOptionPane.showMessageDialog(this, "An error occured when exporting the identifications.", "Error Exporting Identifications", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } } this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } /** * This method exports the selected spectrum information. * * @param evt */ private void exportSelectedSpectrum(ActionEvent evt) { JFileChooser chooser = new JFileChooser(lastSelectedFolder); chooser.setFileFilter(new TxtFileFilter()); chooser.setMultiSelectionEnabled(false); chooser.setDialogTitle("Export Selected Spectrum"); File selectedFile; int returnVal = chooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { selectedFile = chooser.getSelectedFile(); if (!selectedFile.getName().toLowerCase().endsWith(".txt")) { selectedFile = new File(selectedFile.getAbsolutePath() + ".txt"); } while (selectedFile.exists()) { int option = JOptionPane.showConfirmDialog(this, "The file " + chooser.getSelectedFile().getName() + " already exists. Replace file?", "Replace File?", JOptionPane.YES_NO_CANCEL_OPTION); if (option == JOptionPane.NO_OPTION) { chooser = new JFileChooser(lastSelectedFolder); chooser.setFileFilter(new TxtFileFilter()); chooser.setMultiSelectionEnabled(false); chooser.setDialogTitle("Export Selected Spectrum"); returnVal = chooser.showSaveDialog(this); if (returnVal == JFileChooser.CANCEL_OPTION) { return; } else { selectedFile = chooser.getSelectedFile(); if (!selectedFile.getName().toLowerCase().endsWith(".txt")) { selectedFile = new File(selectedFile.getAbsolutePath() + ".txt"); } } } else { // YES option break; } } this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); try { selectedFile = chooser.getSelectedFile(); if (!selectedFile.getName().toLowerCase().endsWith(".txt")) { selectedFile = new File(selectedFile.getAbsolutePath() + ".txt"); } if (selectedFile.exists()) { selectedFile.delete(); } selectedFile.createNewFile(); FileWriter f = new FileWriter(selectedFile); // add the column headers for (int j = 0; j < spectrumJXTable.getColumnCount() - 1; j++) { f.write(spectrumJXTable.getColumnName(j) + "\t"); } f.write(spectrumJXTable.getColumnName(spectrumJXTable.getColumnCount() - 1) + "\n"); // add the table contents for (int i = 0; i < spectrumJXTable.getRowCount(); i++) { for (int j = 0; j < spectrumJXTable.getColumnCount() - 1; j++) { f.write(spectrumJXTable.getValueAt(i, j) + "\t"); } f.write(spectrumJXTable.getValueAt(i, spectrumJXTable.getColumnCount() - 1) + "\n"); } f.close(); lastSelectedFolder = selectedFile.getPath(); } catch (IOException ex) { JOptionPane.showMessageDialog(this, "An error occured when exporting the selected spectrum.", "Error Exporting Selected Spectrum", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } this.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR)); } } /** * Export the all the spectra as DTA files. * * @param evt */ private void exportAllSpectra(ActionEvent evt) { JFileChooser chooser = new JFileChooser(lastSelectedFolder); chooser.setMultiSelectionEnabled(false); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); chooser.setDialogTitle("Export All Spectra As DTA Files"); File selectedFolder; int returnVal = chooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { this.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR)); selectedFolder = chooser.getSelectedFile(); for (int j = 0; j < spectraTable.getRowCount(); j++) { List<Double> mzValues = allMzValues.get((Integer) spectraTable.getValueAt(j, 0)); List<Double> intensityValues = allIntensityValues.get((Integer) spectraTable.getValueAt(j, 0)); File currentFile; String spectrum = spectraTable.getValueAt(j, 1).toString(); if (spectrum.contains(".")) { spectrum = spectrum.replace(".", "_"); } if (spectrum.contains("|")) { spectrum = spectrum.replace("|", "_"); } spectrum = spectrum.replaceAll("/+", "_"); spectrum = spectrum.replaceAll("\\+", "_"); currentFile = new File(selectedFolder, "" + spectrum + ".dta"); FileWriter f; try { f = new FileWriter(currentFile); double precusorMz = ((Double) spectraTable.getValueAt(j, 2)).doubleValue(); int precursorCharge = ((Integer) spectraTable.getValueAt(j, 3)).intValue(); double precursorMh = precusorMz * precursorCharge - precursorCharge * Masses.Hydrogen + Masses.Hydrogen; f.write("" + precursorMh); f.write(" " + precursorCharge + "\n"); // write all the m/z & intensity pairs for (int i = 0; i < mzValues.size(); i++) { f.write(mzValues.get(i) + " " + intensityValues.get(i) + "\n"); } f.close(); lastSelectedFolder = currentFile.getPath(); } catch (IOException ex) { JOptionPane.showMessageDialog(this, "An error occured when exporting the spectra.", "Error Exporting Spectra", JOptionPane.ERROR_MESSAGE); ex.printStackTrace(); } } this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } } }
package fi.csc.microarray.client; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.Component; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Vector; import java.util.concurrent.TimeUnit; import javax.jms.JMSException; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRootPane; import javax.swing.JSplitPane; import javax.swing.LookAndFeel; import javax.swing.SwingUtilities; import javax.swing.UIDefaults; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.filechooser.FileFilter; import javax.swing.plaf.ColorUIResource; import javax.swing.plaf.FontUIResource; import org.apache.log4j.Logger; import com.jgoodies.looks.HeaderStyle; import com.jgoodies.looks.Options; import com.jgoodies.looks.plastic.Plastic3DLookAndFeel; import com.jgoodies.looks.plastic.PlasticTheme; import com.jgoodies.looks.plastic.theme.ExperienceBlue; import com.jgoodies.uif_lite.panel.SimpleInternalFrame; import fi.csc.microarray.ApplicationConstants; import fi.csc.microarray.ErrorReportAsException; import fi.csc.microarray.MicroarrayException; import fi.csc.microarray.client.dataimport.ImportItem; import fi.csc.microarray.client.dataimport.ImportScreen; import fi.csc.microarray.client.dataimport.ImportSession; import fi.csc.microarray.client.dataimport.ImportUtils; import fi.csc.microarray.client.dataimport.ImportUtils.FileLoaderProcess; import fi.csc.microarray.client.dataimport.table.InformationDialog; import fi.csc.microarray.client.dataview.DetailsPanel; import fi.csc.microarray.client.dataview.GraphPanel; import fi.csc.microarray.client.dataview.TreePanel; import fi.csc.microarray.client.dialog.ChipsterDialog; import fi.csc.microarray.client.dialog.ClipboardImportDialog; import fi.csc.microarray.client.dialog.DialogInfo; import fi.csc.microarray.client.dialog.ErrorDialogUtils; import fi.csc.microarray.client.dialog.ImportSettingsAccessory; import fi.csc.microarray.client.dialog.SnapshotAccessory; import fi.csc.microarray.client.dialog.URLImportDialog; import fi.csc.microarray.client.dialog.ChipsterDialog.DetailsVisibility; import fi.csc.microarray.client.dialog.DialogInfo.Severity; import fi.csc.microarray.client.operation.Operation; import fi.csc.microarray.client.operation.OperationDefinition; import fi.csc.microarray.client.operation.OperationPanel; import fi.csc.microarray.client.screen.ChildScreenPool; import fi.csc.microarray.client.screen.HistoryScreen; import fi.csc.microarray.client.screen.Screen; import fi.csc.microarray.client.screen.ShowSourceScreen; import fi.csc.microarray.client.screen.TaskManagerScreen; import fi.csc.microarray.client.selection.DatasetChoiceEvent; import fi.csc.microarray.client.tasks.Task; import fi.csc.microarray.client.tasks.TaskException; import fi.csc.microarray.client.tasks.TaskExecutor; import fi.csc.microarray.client.visualisation.VisualisationFrameManager; import fi.csc.microarray.client.visualisation.VisualisationMethod; import fi.csc.microarray.client.visualisation.Visualisation.Variable; import fi.csc.microarray.client.visualisation.VisualisationFrameManager.FrameType; import fi.csc.microarray.client.waiting.WaitGlassPane; import fi.csc.microarray.client.workflow.WorkflowManager; import fi.csc.microarray.config.DirectoryLayout; import fi.csc.microarray.config.ConfigurationLoader.IllegalConfigurationException; import fi.csc.microarray.databeans.ContentType; import fi.csc.microarray.databeans.DataBean; import fi.csc.microarray.databeans.DataChangeEvent; import fi.csc.microarray.databeans.DataChangeListener; import fi.csc.microarray.databeans.DataFolder; import fi.csc.microarray.databeans.DataItem; import fi.csc.microarray.databeans.DataManager; import fi.csc.microarray.databeans.DataBean.Link; import fi.csc.microarray.databeans.DataBean.Traversal; import fi.csc.microarray.databeans.fs.FSSnapshottingSession; import fi.csc.microarray.description.VVSADLParser.ParseException; import fi.csc.microarray.messaging.auth.AuthenticationRequestListener; import fi.csc.microarray.messaging.auth.ClientLoginListener; import fi.csc.microarray.module.chipster.ChipsterInputTypes; import fi.csc.microarray.util.BrowserLauncher; import fi.csc.microarray.util.Exceptions; import fi.csc.microarray.util.Files; import fi.csc.microarray.util.GeneralFileFilter; import fi.csc.microarray.util.SplashScreen; import fi.csc.microarray.util.Strings; public class SwingClientApplication extends ClientApplication { private static final int METADATA_FETCH_TIMEOUT_SECONDS = 15; private static final long SLOW_VISUALISATION_LIMIT = 5 * 1000; private static final long VERY_SLOW_VISUALISATION_LIMIT = 20 * 1000; /**W * Logger for this class */ private static Logger logger; private JFrame mainFrame = null; private JPanel rightSideViewChanger = null; private JPanel leftSideContentPane = null; private JSplitPane rightSplit = null; private JSplitPane leftSplit = null; private JSplitPane mainSplit = null; private MicroarrayMenuBar menuBar; private TaskManagerScreen taskManagerScreen; private StatusBar statusBar; private SimpleInternalFrame treeFrame; private SimpleInternalFrame graphFrame; private SimpleInternalFrame operationsFrame; private JPanel visualisationArea; private SimpleInternalFrame detailsFrame; private ChildScreenPool childScreens; private TreePanel tree; private DetailsPanel details; private GraphPanel graphPanel; private OperationPanel operationsPanel; private VisualisationFrameManager visualisationFrameManager; private HistoryScreen historyScreen; private SplashScreen splashScreen; private ClientListener clientListener; private AuthenticationRequestListener overridingARL; private WaitGlassPane waitPanel = new WaitGlassPane(); private static float fontSize = VisualConstants.DEFAULT_FONT_SIZE; private boolean unsavedChanges = false; private JFileChooser importExportFileChooser; private JFileChooser snapshotFileChooser; private JFileChooser workflowFileChooser; public SwingClientApplication(ClientListener clientListener, AuthenticationRequestListener overridingARL) throws MicroarrayException, IOException, IllegalConfigurationException { super(); this.clientListener = clientListener; this.overridingARL = overridingARL; splashScreen = new SplashScreen(VisualConstants.SPLASH_SCREEN); reportInitialisation("Initialising " + ApplicationConstants.APPLICATION_TITLE, true); // we want to close the splash screen exception occurs try { initialiseApplication(); } catch (Exception e) { splashScreen.close(); throw new MicroarrayException(e); } // this had to be delayed as logging is not available before loading // configuration logger = Logger.getLogger(SwingClientApplication.class); } public void reportInitialisation(String report, boolean newline) { if (newline) { splashScreen.writeLine(report); } else { splashScreen.write(report); } } protected void initialiseGUI() throws MicroarrayException, IOException { // assert state of initialisation try { definitionsInitialisedLatch.await(METADATA_FETCH_TIMEOUT_SECONDS, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } if (parsedCategories == null) { throw new MicroarrayException("metadata was not received (analyser not functional?)"); } // initialize the main frame mainFrame = new JFrame(); updateWindowTitle(); childScreens = new ChildScreenPool(mainFrame); // Sets look 'n' feel setPlastic3DLookAndFeel(mainFrame); // set location mainFrame.setLocationByPlatform(true); // initialise joblist popup menu // do this method before getStatusBar to avoid null pointer exception this.taskManagerScreen = this.getTaskManagerScreen(); // initialise child screens historyScreen = new HistoryScreen(); childScreens.put("History", historyScreen); childScreens.put("ShowSource", new ShowSourceScreen()); childScreens.put("Import", new ImportScreen()); childScreens.put("TaskList", taskManagerScreen); // create operation panel using metadata try { operationsPanel = new OperationPanel(parsedCategories); } catch (ParseException e) { logger.error("VVSADL parse failed", e); throw new MicroarrayException(e); } operationsFrame = getOperationsFrame(); visualisationFrameManager = new VisualisationFrameManager(); visualisationArea = getVisualisationFrameManager().getFramesPanel(); rightSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, operationsFrame, visualisationArea); rightSplit.setDividerLocation(VisualConstants.TREE_PANEL_HEIGHT); rightSplit.setResizeWeight(0.1); // initialise left side leftSideContentPane = new JPanel(new BorderLayout()); details = new DetailsPanel(leftSideContentPane); leftSideContentPane.setBorder(BorderFactory.createEmptyBorder()); /* Initialize tree and graph */ //moved to getTreeFrame // this.tree = new TreePanel(manager.getRootFolder()); this.graphPanel = new GraphPanel(); treeFrame = getTreeFrame(); graphFrame = getGraphFrame(); leftSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT, treeFrame, graphFrame); leftSplit.setDividerLocation(VisualConstants.TREE_PANEL_HEIGHT); leftSplit.setResizeWeight(0.1); detailsFrame = getDetailsFrame(); leftSideContentPane.add(leftSplit, BorderLayout.CENTER); leftSideContentPane.add(detailsFrame, BorderLayout.SOUTH); rightSideViewChanger = new JPanel(new BorderLayout()); rightSideViewChanger.add(rightSplit, BorderLayout.CENTER); rightSideViewChanger.setBorder(BorderFactory.createEmptyBorder()); // construct the whole main content pane mainSplit = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftSideContentPane, rightSideViewChanger); mainSplit.setDividerLocation(VisualConstants.LEFT_PANEL_WIDTH); mainSplit.setResizeWeight(0.1); // add menus menuBar = new MicroarrayMenuBar(this); // create status bar statusBar = new StatusBar(this); // sets 3D-look (JGoodies property) menuBar.putClientProperty(Options.HEADER_STYLE_KEY, HeaderStyle.SINGLE); // put everything together mainFrame.getContentPane().setLayout(new BorderLayout()); mainFrame.getContentPane().add(mainSplit, BorderLayout.CENTER); mainFrame.getContentPane().add(statusBar.getStatusPanel(), BorderLayout.SOUTH); mainFrame.setJMenuBar(menuBar); menuBar.updateMenuStatus(); // add glass wait panel JRootPane rootPane = SwingUtilities.getRootPane(mainFrame); rootPane.setGlassPane(waitPanel); // add shutdown listener mainFrame.addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent e) { quit(); } }); // make window visible mainFrame.setIconImage(VisualConstants.APPLICATION_ICON.getImage()); mainFrame.pack(); mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); mainFrame.setVisible(true); mainFrame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); // Remember changes to confirm close only when necessary manager.addDataChangeListener(new DataChangeListener() { public void dataChanged(DataChangeEvent event) { unsavedChanges = true; } }); // it's alive! super.setEventsEnabled(true); manager.setEventsEnabled(true); // hide splashscreen splashScreen.close(); // notify listener if (clientListener != null) { SwingUtilities.invokeLater(new Runnable() { public void run() { clientListener.onSuccessfulInitialisation(); } }); } customiseFocusTraversal(); restoreDefaultView(); } private void customiseFocusTraversal() throws MicroarrayException { Vector<Component> order = new Vector<Component>(); order.addAll(tree.getFocusComponents()); order.addAll(operationsPanel.getFocusComponents()); order.addAll(visualisationFrameManager.getFocusComponents()); getMainFrame().setFocusTraversalPolicy(new ClientFocusTraversalPolicy(order)); } private String windowTitleJobPrefix = null; private String windowTitleBlockingPrefix = null; public void updateWindowTitleJobCount(Integer jobCount) { windowTitleJobPrefix = jobCount > 0 ? jobCount + " tasks / " : null; updateWindowTitle(); } public void updateWindowTitleBlockingState(String operation) { if (operation != null) { windowTitleBlockingPrefix = Strings.startWithUppercase(operation) + " / "; } else { windowTitleBlockingPrefix = null; } updateWindowTitle(); } public void updateWindowTitle() { if (windowTitleBlockingPrefix != null) { this.mainFrame.setTitle(windowTitleBlockingPrefix + ApplicationConstants.APPLICATION_TITLE); } else if (windowTitleJobPrefix != null) { this.mainFrame.setTitle(windowTitleJobPrefix + ApplicationConstants.APPLICATION_TITLE); } else { this.mainFrame.setTitle(ApplicationConstants.APPLICATION_TITLE); } } public SimpleInternalFrame getOperationsFrame() { if (operationsFrame == null) { operationsFrame = new SimpleInternalFrame("Analysis tools"); operationsFrame.setContent(operationsPanel); } return operationsFrame; } public SimpleInternalFrame getGraphFrame() throws MicroarrayException { if (graphFrame == null) { graphFrame = new SimpleInternalFrame("Workflow", graphPanel.getButtonToolBar(), graphPanel.getScroller()); } return graphFrame; } public SimpleInternalFrame getTreeFrame() throws MicroarrayException { if (treeFrame == null) { treeFrame = new SimpleInternalFrame("Datasets"); CardLayout cardLayout = new CardLayout(); JPanel cardPanel = new JPanel(cardLayout); QuickLinkPanel linkPanel = new QuickLinkPanel(); this.tree = new TreePanel(manager.getRootFolder(), cardPanel, cardLayout); cardPanel.add(linkPanel, "LINKS"); cardPanel.add(tree, "TREE"); treeFrame.add(cardPanel); cardLayout.first(cardPanel); return treeFrame; } else { return treeFrame; } } public SimpleInternalFrame getDetailsFrame() throws MicroarrayException { if (detailsFrame == null) { class DetailsFrame extends SimpleInternalFrame implements PropertyChangeListener { public DetailsFrame() { super("Notes for dataset"); } public void propertyChange(PropertyChangeEvent evt) { if (evt instanceof DatasetChoiceEvent) { DatasetChoiceEvent dce = (DatasetChoiceEvent) evt; if (dce.getNewValue() != null) { this.setTitle("Notes for dataset " + dce.getNewValue()); } else { this.setTitle("Notes for dataset"); } } } } DetailsFrame detailsFrameWithListener = new DetailsFrame(); addPropertyChangeListener(detailsFrameWithListener); this.detailsFrame = detailsFrameWithListener; detailsFrame.add(details); return detailsFrame; } else { return detailsFrame; } } /** * ExperienceBlue is very nice color theme, but it has ugly orange borders * around focused components. This helper class customizes the theme a bit. * * @author mkoski */ private static class CustomExperienceBlue extends ExperienceBlue { /** * Removes the ugly orange focus color */ @Override public ColorUIResource getFocusColor() { return new ColorUIResource(VisualConstants.PLASTIC3D_FOCUS_COLOR); } @Override public FontUIResource getControlTextFont() { return new FontUIResource(super.getControlTextFont().deriveFont(fontSize)); } @Override public FontUIResource getTitleTextFont() { return new FontUIResource(super.getTitleTextFont().deriveFont(fontSize)); } @Override public FontUIResource getSubTextFont() { return new FontUIResource(super.getSubTextFont().deriveFont(fontSize)); } @Override public FontUIResource getSystemTextFont() { return new FontUIResource(super.getSystemTextFont().deriveFont(fontSize)); } @Override public FontUIResource getUserTextFont() { return new FontUIResource(super.getUserTextFont().deriveFont(fontSize)); } @Override public FontUIResource getWindowTitleFont() { return new FontUIResource(super.getWindowTitleFont().deriveFont(fontSize)); } @Override public FontUIResource getMenuTextFont() { return new FontUIResource(super.getMenuTextFont().deriveFont(fontSize)); } } private static PlasticTheme theme; private static LookAndFeel lnf; /** * This method sets applications appearance to new level by using Plastic3D * Look And Feel and ExperienceBlue color theme. * * The method sets look and feel and updates UIDefault values. After that it * updates all the components to the new appearance. * * @param componentTreeRoot * root component of component tree (frame component in most * cases) * */ public static void setPlastic3DLookAndFeel(Component componentTreeRoot) { // Look and Feel change must be done only once, otherwise the custom // values // from the components get overridden. However this method is called // several // times for different child windows, but these ifs do the job. if (theme == null) { theme = new CustomExperienceBlue(); Plastic3DLookAndFeel.setPlasticTheme(theme); } if (lnf == null) { lnf = new Plastic3DLookAndFeel(); try { UIManager.installLookAndFeel("Plastic3D", lnf.getClass().getName()); UIManager.setLookAndFeel(lnf); } catch (UnsupportedLookAndFeelException e1) { e1.printStackTrace(); } } // set the UI defaults UIDefaults defaults = UIManager.getDefaults(); // Done several times, but luckily map rejects duplicates defaults.putAll(VisualConstants.getUIDefaults()); SwingUtilities.updateComponentTreeUI(componentTreeRoot); } public void setFontSize(float size) { fontSize = size; SwingUtilities.updateComponentTreeUI(mainFrame); fixFileChooserFontSize(importExportFileChooser); // Running progressBar don't care about updateUI statusBar.setFontSize(fontSize); Iterator<Screen> iter = childScreens.getScreenIterator(); while (iter.hasNext()) { Screen screen = iter.next(); SwingUtilities.updateComponentTreeUI(screen.getFrame()); } } public float getFontSize() { return fontSize; } public JFrame getMainFrame() { return mainFrame; } /** * Sets the folder with given name selected or creates a new folder if it * doesn't exist yet. Selected folder is used as a place for imported files. * If folder name is null, root folder is returned * * @param folderName * folder name * @return just created or previously existing folder. If given folder name * is <code>null</code>, root folder is returned */ public DataFolder initializeFolderForImport(String folderName) { DataFolder root = manager.getRootFolder(); if (folderName == null) { logger.debug("initializing for import " + folderName + ": is null => using root"); return root; } else if (ImportUtils.getFolderNames(false).contains(folderName)) { logger.debug("initializing for import " + folderName + ": exists already"); DataFolder folderToSelect; if (folderName.equals(root.getName())) { folderToSelect = root; } else { folderToSelect = root.getChildFolder(folderName); } getSelectionManager().selectSingle(folderToSelect, this); return folderToSelect; } else { logger.debug("initializing for import " + folderName + ": creating new "); DataFolder folder = getDataManager().createFolder(root, folderName); getSelectionManager().selectSingle(folder, this); return folder; } } @Override public void importGroup(final Collection<ImportItem> datas, final String folderName) { runBlockingTask("importing files", new Runnable() { public void run() { DataBean lastGroupMember = null; try { for (ImportItem item : datas) { String dataSetName = item.getOutput().getName(); ContentType contentType = item.getType(); Object dataSource = item.getInput(); // Selects folder where data is imported to, or creates a // new one DataFolder folder = initializeFolderForImport(folderName); // get the InputStream for the data source InputStream input; if (dataSource instanceof File) { input = new FileInputStream((File) (dataSource)); } else if (dataSource instanceof URL) { // TODO Not used anymore, URL-files are saved to the // temp file URL url = (URL) dataSource; try { input = url.openStream(); } catch (FileNotFoundException fnfe) { SwingUtilities.invokeAndWait(new Runnable() { public void run() { showDialog("File not found.", null, "File not found. Check that the typed URL is pointing to a valid location", Severity.ERROR, false); } }); break; } catch (IOException ioe) { SwingUtilities.invokeAndWait(new Runnable() { public void run() { showDialog("Import failed.", null, "Error occured while importing data from URL", Severity.ERROR, false); } }); break; } } else if (dataSource instanceof InputStream) { logger.info("loading data from a plain stream, caching can not be used!"); input = (InputStream) dataSource; } else { throw new IllegalArgumentException("unknown dataSource type: " + dataSource.getClass().getSimpleName()); } // create new data DataBean data = manager.createDataBean(dataSetName, input); data.setContentType(contentType); // add the operation (all databeans have their own import // operation // instance, it would be nice if they would be grouped) Operation importOperation = new Operation(OperationDefinition.IMPORT_DEFINITION, new DataBean[] { data }); data.setOperation(importOperation); // data is ready now, make it visible folder.addChild(data); // Create group links only if both datas are raw type if (lastGroupMember != null && ChipsterInputTypes.hasRawType(lastGroupMember) && ChipsterInputTypes.hasRawType(data)) { DataBean targetData = data; // Link new data to all group linked datas of given cell for (DataBean sourceData : lastGroupMember.traverseLinks(new Link[] { Link.GROUPING }, Traversal.BIDIRECTIONAL)) { logger.debug("Created GROUPING link between " + sourceData.getName() + " and " + targetData.getName()); createLink(sourceData, targetData, DataBean.Link.GROUPING); } // Create link to the given cell after looping to avoid // link duplication createLink(lastGroupMember, targetData, DataBean.Link.GROUPING); } lastGroupMember = data; } // select data final DataBean selectedBean = lastGroupMember; SwingUtilities.invokeAndWait(new Runnable() { public void run() { getSelectionManager().selectSingle(selectedBean, this); } }); } catch (Exception e) { throw new RuntimeException(e); } } }); } /** * Convenience method for showing exception dialogs with hand written * messages and stack traces hidden first. * * @see #showDialog(String, String, String, Severity) */ public void showErrorDialog(String title, Exception error) { showDialog(title, null, Exceptions.getStackTrace(error), Severity.ERROR, false); } /** * @see #showDialog(String, String, String, Severity) */ public void showDialog(String title, Severity severity, boolean modal) { showDialog(title, null, null, severity, modal); } public void showDialog(String title, String message, String details, Severity severity, boolean modal) { showDialog(title, message, details, severity, modal, ChipsterDialog.DetailsVisibility.DETAILS_HIDDEN); } /** * Shows a modal Chipster-styled dialog box to user. Use only when you need * user's immediate attention. * * @param message * message that is always shown to user * @param details * information that is shown in text box that if first closed * @param severity * severity level, affects icon choice */ public void showDialog(String title, String message, String details, Severity severity, boolean modal, ChipsterDialog.DetailsVisibility detailsVisibility) { DialogInfo dialogInfo = new DialogInfo(severity, title, message, details); ChipsterDialog.showDialog(mainFrame, dialogInfo, detailsVisibility, modal); } @Override public File saveWorkflow() { try { JFileChooser fileChooser = this.getWorkflowFileChooser(); int ret = fileChooser.showSaveDialog(this.getMainFrame()); if (ret == JFileChooser.APPROVE_OPTION) { File selected = fileChooser.getSelectedFile(); File newFile = selected.getName().endsWith(WorkflowManager.SCRIPT_EXTENSION) ? selected : new File(selected.getCanonicalPath() + "." + WorkflowManager.SCRIPT_EXTENSION); workflowManager.saveSelectedWorkflow(newFile); unsavedChanges = false; menuBar.addRecentWorkflow(newFile.getName(), Files.toUrl(newFile)); menuBar.updateMenuStatus(); return newFile; } menuBar.updateMenuStatus(); } catch (IOException e) { reportException(e); } return null; } public void runWorkflow(URL workflowScript) { runWorkflow(workflowScript, null); } public void runWorkflow(URL workflowScript, final AtEndListener atEndListener) { workflowManager.runScript(workflowScript, atEndListener); } @Override public File openWorkflow() { try { JFileChooser fileChooser = this.getWorkflowFileChooser(); int ret = fileChooser.showOpenDialog(this.getMainFrame()); if (ret == JFileChooser.APPROVE_OPTION) { runWorkflow(fileChooser.getSelectedFile().toURL()); menuBar.updateMenuStatus(); return fileChooser.getSelectedFile(); } else { menuBar.updateMenuStatus(); return null; } } catch (MalformedURLException e) { reportException(e); return null; } } public void showHistoryScreenFor(DataBean data) { historyScreen.setData(data); childScreens.show("History", true); } public void showDetailsFor(DataBean data) { details.setViewedData(data); } public Icon getIconFor(DataItem element) { if (element instanceof DataFolder) { return VisualConstants.ICON_TYPE_FOLDER; } else { DataBean bean = (DataBean) element; if (bean.queryFeatures("/phenodata").exists()) { return VisualConstants.ICON_TYPE_PHENODATA; } else { return bean.getContentType().getIcon(); } } } public void restoreDefaultView() { leftSplit.setDividerLocation(VisualConstants.TREE_PANEL_HEIGHT); mainSplit.setDividerLocation(VisualConstants.LEFT_PANEL_WIDTH); rightSplit.setDividerLocation(VisualConstants.TREE_PANEL_HEIGHT); mainSplit.validate(); } public void reportTaskError(Task task) throws MicroarrayException { String title = "Running " + task.getNamePrettyPrinted() + " failed. "; String message = "You may have used a tool or parameters which are unsuitable for the selected dataset, or " + "there might be a bug in the analysis tool itself.\n\n" + "The details below may provide hints about the problem. The most useful information is usually at the few last lines."; String details = ""; if (task.getErrorMessage() != null) { details = task.getErrorMessage(); } if (task.getScreenOutput() != null) { details = details + "\n\n" + task.getScreenOutput(); } DialogInfo dialogInfo = new DialogInfo(Severity.WARNING, title, message, details); ChipsterDialog.showDialog(mainFrame, dialogInfo, ChipsterDialog.DetailsVisibility.DETAILS_ALWAYS_VISIBLE, false); } public void reportException(Exception e) { // collect error information to dialogInfo DialogInfo dialogInfo = new DialogInfo(Severity.ERROR, "An error has occurred and the action was not performed successfully.", "If problem persist, please check that your data is valid. For more information open the details panel below.", null); // exception has extra info if (e instanceof ErrorReportAsException) { // exception has everything we need ErrorReportAsException report = (ErrorReportAsException) e; dialogInfo.setTitle(report.getTitle()); dialogInfo.setMessage(report.getMessage()); dialogInfo.setDetails(report.getDetails()); } else if (e instanceof MicroarrayException) { // exception can be scavenged for details MicroarrayException me = (MicroarrayException) e; String details = ""; if (ErrorDialogUtils.getMessage(me.getExtraInfo()) != null) { details += ErrorDialogUtils.getMessage(me.getExtraInfo()) + "\n"; } if (ErrorDialogUtils.getScreenOutput(me.getExtraInfo()) != null) { details += ErrorDialogUtils.getScreenOutput(me.getExtraInfo()); } dialogInfo.setDetails(details); } else { // use stack trace as details dialogInfo.setDetails(Exceptions.getStackTrace(e)); } // show dialog ChipsterDialog.showDialog(this.mainFrame, dialogInfo, ChipsterDialog.DetailsVisibility.DETAILS_HIDDEN, false); // we'll always output these to console and log for traceability and // easier IDE navigation e.printStackTrace(); if (logger != null) { logger.error("client got exception", e); } } public void onException(JMSException e) { reportException(e); } public void showChildScreen(String name, boolean packed) { childScreens.show(name, packed); } public void showMaximisedVisualisation(boolean maximised) { if (maximised) { mainSplit.setDividerLocation(0); rightSplit.setDividerLocation(0); } else { restoreDefaultView(); } rightSideViewChanger.validate(); } public void showPopupMenuFor(MouseEvent e, DataItem data) { List<DataItem> datas = new ArrayList<DataItem>(); datas.add(data); showPopupMenuFor(e, datas); } public void showPopupMenuFor(MouseEvent e, List<DataItem> datas) { ClientContextMenu popup = new ClientContextMenu(this); popup.setOptionsFor(datas); popup.show(e.getComponent(), e.getX(), e.getY()); } /** * Is the selected databeans possible to visualise */ public boolean isSelectedDataVisualisable() { return getDefaultVisualisationForSelection() != VisualisationMethod.NONE; } /** * Gets default visualisation method for selected databeans. The method is * selected by following steps: * * <ol> * <li>If no dataset is selected, return * <code>VisualisationMethod.NONE</code> </li> * <li>If only one dataset is selected, return the default method for the * data </li> * </li> * <li>If multiple datasets are selected, check the best method for each * dataset. If the best method is same for all selected datasets and it can * be used with multiple data, the best method is returned. </li> * <li>If the best method is not same for all of the datas, try to find * just some method which is suitable for all datas and can be used with * multiple datasets. </li> * <li>If there were no method to fill the requirements above, return * <code>VisualisationMethod.NONE</code> </li> * * @return default visualisation method which is suitable for all selected * datasets */ private VisualisationMethod getDefaultVisualisationForSelection() { logger.debug("getting default visualisation"); if (getSelectionManager().getSelectedDataBeans() == null || getSelectionManager().getSelectedDataBeans().size() == 0) { return VisualisationMethod.NONE; } try { List<DataBean> beans = getSelectionManager().getSelectedDataBeans(); if (beans.size() == 1) { return VisualisationMethod.getDefaultVisualisationFor(beans.get(0)); } else if (beans.size() > 1) for (VisualisationMethod method : VisualisationMethod.orderedDefaultCandidates()) { if (method == VisualisationMethod.NONE || !method.getHeadlessVisualiser().isForMultipleDatas()) { continue; } if (method.isApplicableTo(beans)) { return method; } } /* * * VisualisationMethod defaultMethodForDatas = null; // First, try * to find best suitable visualisation for all for (DataBean bean : * beans) { VisualisationMethod method = new * BioBean(bean).getDefaultVisualisation(); if * (defaultMethodForDatas == null && * VisualisationMethod.isApplicableForMultipleDatas(method)) { * defaultMethodForDatas = method; } else { if * (defaultMethodForDatas != method) { // Searching for best method * for all failed defaultMethodForDatas = null; logger.debug("Method " + * method + " can not be used to visualise selected datas"); break; } } } * * if (defaultMethodForDatas != null) { // Visualise datas if the * best method was found logger.debug("Method " + * defaultMethodForDatas + " will be used to visualise selected * datas"); return defaultMethodForDatas; } // Keep looking for * suitable visualisation DataBean firstData = beans.get(0); * * for (VisualisationMethod method : * VisualisationMethod.getApplicableForMultipleDatas()) { if (method == * VisualisationMethod.NONE) { continue; } * * if (method.isApplicableTo(firstData)) { // The method is * applicable to one of the selected datas // Check that the same * method is applicable to the other // datasets too boolean * isSuitableMethod = true; for (DataBean otherData : beans) { if * (otherData.equals(firstData)) { continue; } * * if (!method.isApplicableTo(otherData)) { isSuitableMethod = * false; logger.debug("Method " + method + " can not be used to * visualise selected datas"); break; } } * * if (isSuitableMethod) { logger.debug("Method " + method + " will * be used to visualise selected datas"); return method; } } } */ return VisualisationMethod.NONE; } catch (Exception e) { reportException(e); return VisualisationMethod.NONE; } } public void visualiseWithBestMethod(FrameType target) { setVisualisationMethod(getDefaultVisualisationForSelection(), null, getSelectionManager().getSelectedDataBeans(), target); } public void deleteDatas(DataItem... datas) { // check that we have something to delete if (datas.length == 0) { return; // no selection, do nothing } // choose confirm dialog message JLabel confirmMessage = null; if (datas.length > 1) { confirmMessage = new JLabel("Really delete " + datas.length + " data items?"); } else if (datas[0] instanceof DataFolder) { confirmMessage = new JLabel("Really delete " + datas[0].getName() + " and all of its contents?"); } else if (datas[0] instanceof DataBean) { confirmMessage = new JLabel("Really delete " + datas[0].getName() + " ?"); } else { throw new IllegalArgumentException("datas is illegal"); } // confirm delete if (JOptionPane.showConfirmDialog(this.mainFrame, confirmMessage, "Delete items", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) { return; // deletion was not confirmed } // delete actually deleteDatasWithoutConfirming(datas); } public void deleteDatasWithoutConfirming(DataItem... datas) { // check that we have something to delete if (datas.length == 0) { return; // no selection, do nothing } // remove all selections getSelectionManager().clearAll(true, this); // do actual delete for (DataItem data : datas) { manager.delete(data); } } public void fixFileChooserFontSize(JFileChooser fileChooser) { // Some special care has to be taken to get the fileChooser list update // also if (fileChooser != null) { UIManager.put("FileChooser.listFont", UIManager.getFont("List.font").deriveFont(fontSize)); SwingUtilities.updateComponentTreeUI(fileChooser); } } public void openFileImport() throws MicroarrayException, IOException { JFileChooser fc = getImportExportFileChooser(); fc.setMultiSelectionEnabled(true); ImportSettingsAccessory access = (ImportSettingsAccessory) importExportFileChooser.getAccessory(); access.setDefaults(); int ret = fc.showOpenDialog(getMainFrame()); if (ret == JFileChooser.APPROVE_OPTION) { List<File> files = new ArrayList<File>(); for (File file : fc.getSelectedFiles()) { files.add(file); } ImportSession importSession = new ImportSession(ImportSession.Source.FILES, files, access.getImportFolder(), access.skipActionChooser()); ImportUtils.executeImport(importSession); } } public void openDirectoryImportDialog() { JFileChooser fc = getImportExportDirChooser(); fc.setSelectedFile(new File("")); int ret = fc.showOpenDialog(this.getMainFrame()); if (ret == JFileChooser.APPROVE_OPTION) { File selectedFile = fc.getSelectedFile(); super.importWholeDirectory(selectedFile); } } public void openURLImport() throws MicroarrayException, IOException { URLImportDialog urlImportDlg = new URLImportDialog(this); URL selectedURL = urlImportDlg.getSelectedURL(); String importFolder = urlImportDlg.getSelectedFolderName(); if (selectedURL != null) { File file = ImportUtils.createTempFile(ImportUtils.URLToFilename(selectedURL), ImportUtils.getExtension(ImportUtils.URLToFilename(selectedURL))); ImportUtils.getURLFileLoader().loadFileFromURL(selectedURL, file, importFolder, urlImportDlg.isSkipSelected()); } } public void openClipboardImport() throws MicroarrayException, IOException { new ClipboardImportDialog(this); } protected void quit() { int returnValue = JOptionPane.DEFAULT_OPTION; // Check the running tasks if (taskExecutor.getRunningTaskCount() > 0) { String message = ""; if (taskExecutor.getRunningTaskCount() == 1) { message += "There is a running task. Are you sure you want to cancel the running task?"; } else { message += "There are " + taskExecutor.getRunningTaskCount() + " running tasks. " + "Are you sure you want to cancel all running tasks?"; } Object[] options = { "Cancel running tasks", "Cancel" }; returnValue = JOptionPane.showOptionDialog(this.getMainFrame(), message, "Confirm close", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (returnValue == JOptionPane.YES_OPTION) { taskExecutor.killAll(); } else { return; } } // Check for unsaved changes returnValue = JOptionPane.DEFAULT_OPTION; if (unsavedChanges) { Object[] options = { "Save and close", "Close without saving", "Cancel" }; returnValue = JOptionPane.showOptionDialog(this.getMainFrame(), "Do you want the session to be saved before closing Chipster?", "Confirm close", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (returnValue == 0) { try { saveSession(); } catch (Exception exp) { this.showErrorDialog("Session saving failed", exp); return; } // cancel also if the dialog is closed from the corner x } else if (returnValue != 1) { return; } } // hide immediately to look more reactive... childScreens.disposeAll(); mainFrame.setVisible(false); super.quit(); // this closes the application mainFrame.dispose(); System.exit(0); } /** * Starts Chipster client. Configuration (logging) should be initialised * before calling this method. */ public static void start(String configURL) throws IOException { try { DirectoryLayout.initialiseClientLayout(configURL); } catch (IllegalConfigurationException e) { reportIllegalConfigurationException(e); } ClientListener shutdownListener = new ClientListener() { public void onSuccessfulInitialisation() { // do nothing } public void onFailedInitialisation() { System.exit(1); } }; try { new SwingClientApplication(shutdownListener, null); } catch (Throwable t) { t.printStackTrace(); if (logger != null) { logger.error(t.getMessage()); logger.error(t); } } } public static void main(String[] args) throws IOException { start(null); } public static void reportIllegalConfigurationException(IllegalConfigurationException e) { DialogInfo dialogInfo = new DialogInfo(Severity.ERROR, "Illegal configuration", "Chipster could not start because the provided configuration file is illegal. Please contact your system administrator.", "Reason: " + e.getMessage()); ChipsterDialog.showDialog(null, dialogInfo, DetailsVisibility.DETAILS_HIDDEN, true); throw new RuntimeException("configuration not compatible, will not start"); } @Override public void showSourceFor(String operationName) throws TaskException { childScreens.show("ShowSource", true, operationName); } /** * Opens JFileChooser to ask location for the export, then calls * exportDataDirectory to do the job. * * @param data * @throws MicroarrayException * @throws IOException */ public void exportFolder(DataFolder data) throws MicroarrayException, IOException { File file = new File(data.getName().replace(" ", "_")); // file.mkdirs(); JFileChooser fc = getImportExportDirChooser(); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); fc.setSelectedFile(file); logger.debug("Exporting File: " + fc.getSelectedFile().getAbsolutePath()); int ret = fc.showSaveDialog(getMainFrame()); if (ret == JFileChooser.APPROVE_OPTION) { File selected = new File(fc.getSelectedFile().getAbsolutePath() + File.separator + file.getName()); selected.mkdirs(); exportDataFolder(data, selected); } } /** * Method to export recursively all descendants of the source * */ private void exportDataFolder(DataFolder source, File dir) throws IOException, MicroarrayException { for (DataItem child : source.getChildren()) { if (child instanceof DataBean) { String filename = createFilename((DataBean) child); filename = dir.getAbsolutePath() + File.separator + filename; logger.debug("Exporting dataBean " + child.getName() + " into " + filename); exportToFile((DataBean) child, new File(filename)); } else if (child instanceof DataFolder) { logger.debug("Exporting dataFolder " + child.getName()); String foldername = dir.getAbsolutePath() + File.separator + child.getName().replace(" ", "_"); File file = new File(foldername); file.mkdir(); exportDataFolder((DataFolder) child, file); } } } public void exportDataset(DataBean data) throws MicroarrayException, IOException { JFileChooser fc = this.getImportExportFileChooser(); fc.setDialogType(JFileChooser.SAVE_DIALOG); String proposedName = createFilename(data); fc.setSelectedFile(new File(proposedName)); int ret = fc.showSaveDialog(getMainFrame()); if (ret == JFileChooser.APPROVE_OPTION) { File selectedFile = fc.getSelectedFile(); exportToFile(data, selectedFile); } } private String createFilename(DataBean data) { String proposedName = data.getName().replace(" ", "_"); /* * TODO does not work with mime content types if * (!proposedName.endsWith(data.getContentType())) { proposedName = * proposedName + "." + data.getContentType(); } */ return proposedName; } @Override protected AuthenticationRequestListener getAuthenticationRequestListener() { AuthenticationRequestListener authenticator; if (overridingARL != null) { authenticator = overridingARL; } else { authenticator = new Authenticator(); } authenticator.setLoginListener(new ClientLoginListener() { public void firstLogin() { try { initialiseGUI(); } catch (Exception e) { reportException(e); } } public void loginCancelled() { System.exit(1); } }); return authenticator; } @Override public void setMaximisedVisualisationMode(boolean maximisedVisualisationMode) { showMaximisedVisualisation(maximisedVisualisationMode); } @Override public void setVisualisationMethod(VisualisationMethod method, List<Variable> variables, List<DataBean> datas, FrameType target) { if (method == null || datas == null) { super.setVisualisationMethod(VisualisationMethod.NONE, null, null, target); return; } long estimate = method.estimateDuration(datas); if (estimate > SLOW_VISUALISATION_LIMIT) { int returnValue = JOptionPane.DEFAULT_OPTION; String message = ""; int severity; // Check the running tasks if (estimate > VERY_SLOW_VISUALISATION_LIMIT) { message += "Visualising the selected large dataset with this method might stop Chipster from responding. \n" + "If you choose to continue, it's recommended to save the session before visualising."; severity = JOptionPane.WARNING_MESSAGE; } else { message += "Are you sure you want to visualise large dataset, which may " + "take several seconds?"; severity = JOptionPane.QUESTION_MESSAGE; } Object[] options = { "Cancel", "Visualise" }; returnValue = JOptionPane.showOptionDialog(this.getMainFrame(), message, "Cancel visualisation", JOptionPane.YES_NO_OPTION, severity, null, options, options[0]); if (returnValue == 1) { super.setVisualisationMethod(method, variables, datas, target); } else { return; } } else { super.setVisualisationMethod(method, variables, datas, target); } } public void exportSelectedItems() { try { for (DataItem item : getSelectionManager().getSelectedDataItems()) { if (item instanceof DataBean) { exportDataset((DataBean) item); } else if (item instanceof DataFolder) { exportFolder((DataFolder) item); } } } catch (Exception e) { reportException(e); } } private JFileChooser getImportExportDirChooser() { if (importExportFileChooser == null) { importExportFileChooser = ImportUtils.getFixedFileChooser(); } importExportFileChooser.setAccessory(null); importExportFileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); String description = "Data Directory"; String[] extensions = {}; // only directories for (FileFilter filter : importExportFileChooser.getChoosableFileFilters()) { importExportFileChooser.removeChoosableFileFilter(filter); } importExportFileChooser.addChoosableFileFilter(new GeneralFileFilter(description, extensions)); importExportFileChooser.setAcceptAllFileFilterUsed(false); fixFileChooserFontSize(importExportFileChooser); return importExportFileChooser; } /** * This is public to give access to file filter from ImportUtils * * @return The default JFileChooser with an assigned MicroarrayFileFilter. */ public JFileChooser getImportExportFileChooser() { if (importExportFileChooser == null) { importExportFileChooser = ImportUtils.getFixedFileChooser(); } // FIXME All files to default filter and other as a single file // filters String description = "Common microarray filetypes (cel, spot, gpr, txt, csv, tsv)"; String[] extensions = { "cel", // affymetrix "spot", // SPOT files "gpr", // GenePix "txt", "csv", // illumina "tsv" // chipster }; for (FileFilter filter : importExportFileChooser.getChoosableFileFilters()) { importExportFileChooser.removeChoosableFileFilter(filter); } importExportFileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); importExportFileChooser.setAcceptAllFileFilterUsed(true); FileFilter filter = new GeneralFileFilter(description, extensions); importExportFileChooser.addChoosableFileFilter(filter); importExportFileChooser.setFileFilter(filter); ImportSettingsAccessory access = new ImportSettingsAccessory(importExportFileChooser); importExportFileChooser.setAccessory(access); fixFileChooserFontSize(importExportFileChooser); return importExportFileChooser; } private JFileChooser getSnapshotFileChooser(JComponent accessory) { if (snapshotFileChooser == null) { snapshotFileChooser = ImportUtils.getFixedFileChooser(); String[] extensions = { FSSnapshottingSession.SNAPSHOT_EXTENSION }; snapshotFileChooser.setFileFilter(new GeneralFileFilter("Chipster Session", extensions)); snapshotFileChooser.setSelectedFile(new File("session." + FSSnapshottingSession.SNAPSHOT_EXTENSION)); snapshotFileChooser.setAcceptAllFileFilterUsed(false); snapshotFileChooser.setMultiSelectionEnabled(false); } snapshotFileChooser.setAccessory(accessory); fixFileChooserFontSize(snapshotFileChooser); return snapshotFileChooser; } private JFileChooser getWorkflowFileChooser() { if (workflowFileChooser == null) { workflowFileChooser = ImportUtils.getFixedFileChooser(workflowManager.getScriptDirectory()); workflowFileChooser.setFileFilter(WorkflowManager.FILE_FILTER); workflowFileChooser.setSelectedFile(new File("workflow.bsh")); workflowFileChooser.setAcceptAllFileFilterUsed(false); workflowFileChooser.setMultiSelectionEnabled(false); } fixFileChooserFontSize(workflowFileChooser); return workflowFileChooser; } /** * Opens import tool directly * * @param useSameSettings * * @param file */ public void openImportTool(ImportSession importSession) { ImportScreen importScreen = (ImportScreen) childScreens.get("Import"); importScreen.setImportSession(importSession); importScreen.updateTable(false); childScreens.show("Import", false); } /** * <p>Run a task in background thread and block GUI in a friendly way while the task is being * run. <strong>Note!</strong> If the task modifies GUI, it must use SwingUtilities.invokeAndWait so that * modifications are done in event dispatch thread.</p> * * @param taskName * name of the task we will be running, like "importing" or * "loading" * @param runnable * the task */ public void runBlockingTask(String taskName, final Runnable runnable) { Thread backgroundThread = new Thread(new Runnable() { public void run() { try { runnable.run(); } catch (final Exception e) { SwingUtilities.invokeLater(new Runnable() { public void run() { reportException(e); } }); } finally { waitPanel.stopWaiting(); updateWindowTitleBlockingState(null); } } }); waitPanel.startWaiting("Please wait while " + taskName + "..."); updateWindowTitleBlockingState(taskName); backgroundThread.start(); } public void viewHelpFor(OperationDefinition definition) { viewHelp(HelpMapping.mapToHelppage(definition)); } public void viewHelp(String page) { try { BrowserLauncher.openURL("https://extras.csc.fi/biosciences/" + page); } catch (Exception e) { reportException(e); } } protected void garbageCollect() { System.gc(); statusBar.updateMemoryIndicator(); } public TaskManagerScreen getTaskManagerScreen() { TaskExecutor jobExecutor = Session.getSession().getJobExecutor("client-job-executor"); return new TaskManagerScreen(jobExecutor); } public void createLink(DataBean source, DataBean target, Link type) { source.addLink(type, target); } public void removeLink(DataBean source, DataBean target, Link type) { source.removeLink(type, target); } @Override public void showImportToolFor(File file, String destinationFolder, boolean skipActionChooser) { ImportSession importSession = new ImportSession(ImportSession.Source.FILES, new File[] { file }, destinationFolder, skipActionChooser); openImportTool(importSession); } @Override public void loadSessionFrom(URL url) { try { final File tempFile = ImportUtils.createTempFile(ImportUtils.URLToFilename(url), ImportUtils.getExtension(ImportUtils.URLToFilename(url))); InformationDialog info = new InformationDialog("Loading session", "Loading session from the specified URL", null); FileLoaderProcess fileLoaderProcess = new FileLoaderProcess(tempFile, url, info) { @Override protected void postProcess() { loadSessionImpl(tempFile); }; }; fileLoaderProcess.runProcess(); } catch (IOException e) { reportException(e); } } @Override public void loadSession() { SnapshotAccessory accessory = new SnapshotAccessory(); final JFileChooser fileChooser = getSnapshotFileChooser(accessory); int ret = fileChooser.showOpenDialog(this.getMainFrame()); if (ret == JFileChooser.APPROVE_OPTION) { if (accessory.clearSession()) { if (!clearSession()) { return; // loading cancelled } } loadSessionImpl(fileChooser.getSelectedFile()); } menuBar.updateMenuStatus(); } private void loadSessionImpl(final File sessionFile) { final ClientApplication application = this; // for inner class runBlockingTask("loading the session", new Runnable() { public void run() { try { /* If there wasn't data or it was just cleared, there is no need to warn about * saving after opening session. However, if there was datasets already, combination * of them and new session can be necessary to save. This has to set after the import, because */ boolean somethingToSave = getAllDataBeans().size() != 0; final List<DataItem> newItems = manager.loadSnapshot(sessionFile, manager.getRootFolder(), application); SwingUtilities.invokeAndWait(new Runnable() { public void run() { getSelectionManager().selectSingle(newItems.get(newItems.size() - 1), this); // select last } }); unsavedChanges = somethingToSave; } catch (Exception e) { throw new RuntimeException(e); } } }); } @Override public void saveSession() { JFileChooser fileChooser = getSnapshotFileChooser(null); int ret = fileChooser.showSaveDialog(this.getMainFrame()); final ClientApplication application = this; // for inner class if (ret == JFileChooser.APPROVE_OPTION) { try { final File file = fileChooser.getSelectedFile().getName().endsWith("." + FSSnapshottingSession.SNAPSHOT_EXTENSION) ? fileChooser.getSelectedFile() : new File(fileChooser.getSelectedFile().getCanonicalPath() + "." + FSSnapshottingSession.SNAPSHOT_EXTENSION); if (file.exists()) { int returnValue = JOptionPane.DEFAULT_OPTION; String message = "The file " + file.getCanonicalPath() + " exists already. Do you want " + "to replace it with the one you are saving?"; Object[] options = { "Cancel", "Replace" }; returnValue = JOptionPane.showOptionDialog(this.getMainFrame(), message, "Confirm replace", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (returnValue != 1) { return; } } runBlockingTask("saving session", new Runnable() { public void run() { try { getDataManager().saveSnapshot(file, application); } catch (IOException e) { throw new RuntimeException(e); } } }); menuBar.updateMenuStatus(); unsavedChanges = false; } catch (Exception exp) { showErrorDialog("Saving session failed.", exp); } } menuBar.updateMenuStatus(); } /** * @return true if cleared, false if canceled */ public boolean clearSession() { int returnValue = JOptionPane.DEFAULT_OPTION; if (unsavedChanges) { String message = "The current session contains unsaved changes.\nDo you want to clear it anyway?"; Object[] options = { "Cancel", "Clear" }; returnValue = JOptionPane.showOptionDialog(this.getMainFrame(), message, "Clear session", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); } if (!unsavedChanges || returnValue == 1) { this.deleteDatasWithoutConfirming(manager.getRootFolder()); unsavedChanges = false; return true; } return false; } @Override public void heartBeat() { statusBar.updateMemoryIndicator(); } public DataManager getDataManager() { return manager; } public VisualisationFrameManager getVisualisationFrameManager() { return visualisationFrameManager; } @Override public void flipTaskListVisibility(boolean closeIfVisible) { statusBar.flipTaskListVisibility(closeIfVisible); } @Override protected void taskCountChanged(int newTaskCount, boolean attractAttention) { int completion = 0; if (newTaskCount > 0) { completion = taskExecutor.getTasks(true, false).iterator().next().getCompletionPercentage(); } statusBar.taskCountChanged(newTaskCount, completion, attractAttention); } public void refreshTaskList() { this.taskManagerScreen.refreshTasks(); } public Screen getTaskListScreen() { return childScreens.get("TaskList"); } }
package info.faceland.strife.attributes; import java.util.HashMap; import java.util.Map; public enum StrifeAttribute { LEVEL_REQUIREMENT("Level Requirement"), HEALTH("Health"), REGENERATION("Base Regeneration"), BARRIER("Maximum Barrier"), BARRIER_SPEED("Barrier Recharge Rate"), ARMOR("Armor"), WARDING("Warding"), EVASION("Evasion"), FIRE_RESIST("Fire Resistance"), ICE_RESIST("Ice Resistance"), LIGHTNING_RESIST("Lightning Resistance"), EARTH_RESIST("Earth Resistance"), LIGHT_RESIST("Light Resistance"), DARK_RESIST("Shadow Resistance"), ALL_RESIST("Elemental Resist"), BLOCK("Block"), DAMAGE_REDUCTION("Damage Reduction"), DAMAGE_REFLECT("Reflected Damage"), MELEE_DAMAGE("Melee Damage"), RANGED_DAMAGE("Ranged Damage"), MAGIC_DAMAGE("Magic Damage"), ATTACK_SPEED("Attack Speed"), OVERCHARGE("Overcharge"), CRITICAL_RATE("Critical Rate"), CRITICAL_DAMAGE("Critical Damage"), ARMOR_PENETRATION("Armor Penetration"), WARD_PENETRATION("Ward Penetration"), ACCURACY("Accuracy"), FIRE_DAMAGE("Fire Damage"), LIGHTNING_DAMAGE("Lightning Damage"), ICE_DAMAGE("Ice Damage"), EARTH_DAMAGE("Earth Damage"), LIGHT_DAMAGE("Light Damage"), DARK_DAMAGE("Shadow Damage"), IGNITE_CHANCE("Ignite Chance"), IGNITE_DURATION("Ignite Duration"), SHOCK_CHANCE("Shock Chance"), FREEZE_CHANCE("Freeze Chance"), CORRUPT_CHANCE("Corrupt Chance"), MAX_EARTH_RUNES("Max Earth Runes"), MAXIMUM_RAGE("Maximum Rage"), RAGE_ON_HIT("Rage On Hit"), RAGE_WHEN_HIT("Rage When Hit"), RAGE_ON_KILL("Rage On Kill"), BLEED_CHANCE("Bleed Chance"), BLEED_DAMAGE("Bleed Damage"), LIFE_STEAL("Life Steal"), HP_ON_HIT("Health On Hit"), HP_ON_KILL("Health On Kill"), MULTISHOT("Multishot"), MOVEMENT_SPEED("Movement Speed"), TRUE_DAMAGE("True Damage"), PVP_ATTACK("PvP Attack"), PVP_DEFENCE("PvP Defence"), CRAFT_SKILL("Crafting Skill Level"), ENCHANT_SKILL("Enchanting Skill Level"), FISH_SKILL("Fishing Skill Level"), MINE_SKILL("Mining Skill Level"), XP_GAIN("Experience Gain"), SKILL_XP_GAIN("Skill Experience Gain"), ITEM_DISCOVERY("Item Discovery"), ITEM_RARITY("Item Rarity"), GOLD_FIND("Gold Find"), HEAD_DROP("Head Drop"), DOGE("Doge Chance"), HEALTH_MULT(), REGEN_MULT("Regeneration"), ARMOR_MULT(), EVASION_MULT(), WARD_MULT(), MELEE_MULT(), RANGED_MULT(), MAGIC_MULT(), DAMAGE_MULT(), PROJECTILE_SPEED("Projectile Speed"), ELEMENTAL_MULT("Elemental Damage"), ACCURACY_MULT(), APEN_MULT(), WPEN_MULT(), EXPLOSION_MAGIC("Explosion Magic"), SPELL_STRIKE_RANGE("Spell Strike Range"), HEALTH_PER_TEN_B_LEVEL("Max Health Per Ten BLvl"), BARRIER_PER_TEN_B_LEVEL("Max Barrier Per Ten BLvl"), DAMAGE_PER_TEN_B_LEVEL("Damage Per Ten BLvl"), ARMOR_PER_TEN_B_LEVEL("Armor Per Ten BLvl"), EVASION_PER_TEN_B_LEVEL("Evasion Per Ten BLvl"), MS_PER_TEN_B_LEVEL("Move Speed Per Ten BLvl"), AS_PER_TEN_B_LEVEL("Attack Speed Per Ten BLvl"); // values() is dumb, so we only run it once, and hit use this to // change String to enum instead of try catching or values() // TODO: We map String to StrifeAttribute, why not let the user customize the string rather than declaring it in the enum? private static final Map<String, StrifeAttribute> copyOfValues = buildStringToAttributeMap(); private static Map<String, StrifeAttribute> buildStringToAttributeMap() { Map<String, StrifeAttribute> values = new HashMap<>(); for (StrifeAttribute attribute : StrifeAttribute.values()) { if (attribute.getName() == null) { continue; } values.put(attribute.getName(), attribute); } return values; } public static StrifeAttribute fromName(String name) { return copyOfValues.getOrDefault(name, null); } private final String name; StrifeAttribute(String name) { this.name = name; } StrifeAttribute() { this.name = null; } public String getName() { return name; } }
package io.github.metaluna.ck2edit.gui.mod; import io.github.metaluna.ck2edit.business.mod.ModManager; import io.github.metaluna.ck2edit.business.mod.Mod; import io.github.metaluna.ck2edit.business.mod.ModFile; import io.github.metaluna.ck2edit.business.mod.opinionmodifier.OpinionModifierFile; import io.github.metaluna.ck2edit.gui.mod.opiniomodifier.OpinionModifierTreeItem; import java.nio.file.Path; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import javafx.fxml.FXML; import javafx.scene.control.Alert; import javafx.scene.control.ButtonType; import javafx.scene.control.SplitPane; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; import javax.inject.Inject; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class ModPresenter { public void initialize() { this.modTreeView.setCellFactory(treeView -> new ModTreeCell(this::onModFileOpen, this::onModFileDelete)); // defined here because tree cells don't receive any key events this.modTreeView.addEventFilter(KeyEvent.KEY_PRESSED, event -> { if (event.getCode() == KeyCode.ENTER) { LOG.trace("ENTER key pressed"); TreeItem<Object> selected = this.modTreeView.getSelectionModel().getSelectedItem(); if (selected instanceof ModFileTreeItem) { onModFileOpen((ModFileTreeItem) selected); } } }); } public void load(Path modFile) { Mod mod; LOG.info("Loading mod file '%s'...", modFile.toString()); mod = modManager.fromFile(modFile); this.currentMod = Optional.of(mod); setWindowTitle(mod.getName()); loadTreeFromMod(mod); } public void saveFile() { LOG.entry(); this.currentFile .filter(f -> f instanceof OpinionModifierFile) .ifPresent(f -> modManager.saveFile((OpinionModifierFile) f)); LOG.exit(); } public void saveAllFiles() { LOG.entry(); throw new UnsupportedOperationException("Not supported yet."); // LOG.exit(); } private static final Logger LOG = LogManager.getFormatterLogger(); @Inject private ModManager modManager; @FXML private SplitPane centerSplitPane; @FXML private TreeView<Object> modTreeView; @FXML private BorderPane modOpenFilesPane; private Optional<Mod> currentMod = Optional.empty(); private Optional<ModFile> currentFile = Optional.empty(); private String baseTitle; private void onModFileOpen(ModFileTreeItem modFileItem) { LOG.entry(modFileItem); this.currentFile = Optional.of(modFileItem.getFile()); this.modOpenFilesPane.setCenter(modFileItem.createView().getView()); LOG.exit(); } private void onModFileDelete(ModFileTreeItem modFileItem) { LOG.entry(modFileItem); ModFile modFile = modFileItem.getFile(); if (showConfirmationDialog(modFile)) { removeFileFromTree(this.modTreeView.getRoot(), modFileItem); closeOpenFile(modFile); this.currentFile = Optional.empty(); modManager.deleteFile(modFile); } LOG.exit(); } private void loadTreeFromMod(Mod mod) { final TreeItem<Object> root = new TreeItem<>(mod.getName()); List<ModFile> opinionModifiers = mod.getOpinionModifiers(); if (!opinionModifiers.isEmpty()) { TreeItem<Object> opinionModifierRoot = new TreeItem<>("Opinion Modifiers"); opinionModifierRoot.setExpanded(true); opinionModifierRoot.getChildren().addAll(opinionModifiers.stream() .map(m -> new OpinionModifierTreeItem((OpinionModifierFile) m)) .collect(Collectors.toList()) ); root.getChildren().add(opinionModifierRoot); } this.modTreeView.setRoot(root); root.setExpanded(true); } private void setWindowTitle(String name) { Stage stage; if (!getStage().isPresent()) { return; } stage = getStage().get(); if (baseTitle == null) { baseTitle = stage.getTitle(); } stage.setTitle(name + " | " + baseTitle); } private Optional<Stage> getStage() { Optional<Stage> result; try { result = Optional.ofNullable((Stage) centerSplitPane.getScene().getWindow()); } catch (Exception e) { result = Optional.empty(); } return result; } private boolean showConfirmationDialog(ModFile modFile) { LOG.entry(modFile); boolean result; Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setHeaderText(String.format("Deleting the file %s", modFile)); alert.setContentText("Do you really want to delete this file? This cannot be undone."); Optional<ButtonType> answer = alert.showAndWait(); result = answer.isPresent() && answer.get() == ButtonType.OK; return LOG.exit(result); } private boolean removeFileFromTree(TreeItem<Object> node, ModFileTreeItem modFileItem) { LOG.entry(node, modFileItem); // only check leaves if (node.isLeaf()) { // found it! if (node == modFileItem) { node.getParent().getChildren().remove(node); return LOG.exit(true); } else { return LOG.exit(false); } } else { // check all children for (TreeItem<Object> child : node.getChildren()) { boolean isFound = removeFileFromTree(child, modFileItem); if (isFound) { return LOG.exit(true); } } // nothing found in this branch return LOG.exit(false); } } private void closeOpenFile(ModFile modFile) { LOG.entry(modFile); this.currentFile .filter(f -> f == modFile) .ifPresent(f -> { LOG.trace("Closing view of opened mod file '%s'", f); this.modOpenFilesPane.setCenter(null); }); LOG.exit(); } }
package jade.core; //#MIDP_EXCLUDE_FILE import jade.lang.acl.ACLMessage; import jade.core.behaviours.Behaviour; //__SECURITY__BEGIN import jade.security.JADEPrincipal; import jade.security.JADESecurityException; import jade.security.Credentials; //__SECURITY__END /** * This is a degenerate toolkit which is used before the actual one is * setup or during agent termination. Every method which returns an object * will return null and all others do nothing. * @author Dick Cowan - HP */ final class DummyToolkit implements AgentToolkit { static AgentToolkit at = null; static AgentToolkit instance() { if (at == null) { at = new DummyToolkit(); } return at; } public Location here() { return null; } //FIXME should we here throw an InternalError also? public void handleEnd(AID agentID) {} public void handleSend(ACLMessage msg, AID sender) {} public void handlePosted(AID agentID, ACLMessage msg) {} public void handleReceived(AID agentID, ACLMessage msg) {} public void handleChangedAgentState(AID agentID, int from, int to) {} public void handleBehaviourAdded(AID agentID, Behaviour b) {} public void handleBehaviourRemoved(AID agentID, Behaviour b) {} public void handleChangeBehaviourState(AID agentID, Behaviour b, String from, String to) {} // FIXME: Needed due to the Persistence Service being an add-on public void handleSave(AID agentID, String repository) throws ServiceException, NotFoundException, IMTPException {} public void handleReload(AID agentID, String repository) throws ServiceException, NotFoundException, IMTPException {} public void handleFreeze(AID agentID, String repository, ContainerID bufferContainer) throws ServiceException, NotFoundException, IMTPException {} public jade.wrapper.AgentContainer getContainerController(JADEPrincipal principal, Credentials credentials) { return null; } public void setPlatformAddresses(AID id) {} public AID getAMS() { return null; } public AID getDefaultDF() { return null; } public String getProperty(String key, String aDefault) { return null; } public ServiceHelper getHelper(Agent a, String serviceName) throws ServiceException { return null; } }
package me.prettyprint.cassandra.model; import org.apache.cassandra.thrift.Clock; import me.prettyprint.cassandra.model.ConsistencyLevelPolicy.OperationType; import me.prettyprint.cassandra.service.CassandraClient; import me.prettyprint.cassandra.service.Cluster; import me.prettyprint.cassandra.service.Keyspace; import me.prettyprint.cassandra.utils.Assert; public /*final*/ class KeyspaceOperator { private ConsistencyLevelPolicy consistencyLevelPolicy; private final Cluster cluster; private final String keyspace; public KeyspaceOperator(String keyspace, Cluster cluster, ConsistencyLevelPolicy consistencyLevelPolicy) { Assert.noneNull(keyspace, cluster, consistencyLevelPolicy); this.keyspace = keyspace; this.cluster = cluster; this.consistencyLevelPolicy = consistencyLevelPolicy; } public void setConsistencyLevelPolicy(ConsistencyLevelPolicy cp) { this.consistencyLevelPolicy = cp; } public Cluster getCluster() { return cluster; } @Override public String toString() { return "KeyspaceOperator(" + keyspace +"," + cluster + ")"; } public Clock createClock() { return cluster.createClock(); } /*package*/ <T> ExecutionResult<T> doExecute(KeyspaceOperationCallback<T> koc) throws HectorException { CassandraClient c = null; Keyspace ks = null; try { c = cluster.borrowClient(); ks = c.getKeyspace(keyspace, consistencyLevelPolicy.get(OperationType.READ)); return koc.doInKeyspaceAndMeasure(ks); } finally { if ( ks != null ) { cluster.releaseClient(ks.getClient()); } } } }
package net.fortytwo.extendo.brainstem; import android.widget.EditText; import com.illposed.osc.OSCMessage; import net.fortytwo.extendo.Main; import net.fortytwo.extendo.brain.BrainModeClient; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.util.HashMap; import java.util.Map; public class TypeatronControl extends BluetoothDeviceControl { private final Main.Toaster toaster; private byte[] lastInput; private enum Mode {LowercaseText, UppercaseText, Punctuation, Numeric, Mash} private enum Modifier {Control, None} private class StateNode { /** * A symbol emitted when this state is reached */ public String symbol; /** * A mode entered when this state is reached */ public Mode mode; /** * A modifier applied when this state is reached */ public Modifier modifier; public StateNode[] nextNodes = new StateNode[5]; } private Map<Mode, StateNode> rootStates; private Mode currentMode; private Modifier currentModifier; private StateNode currentButtonState; private int totalButtonsCurrentlyPressed; public TypeatronControl(final String address, final OSCDispatcher oscDispatcher, final EditText textEditor, final Main.Toaster toaster) { super(address); this.toaster = toaster; setupParser(); oscDispatcher.register("/exo/tt/keys", new OSCMessageHandler() { public void handle(final OSCMessage message) { Object[] args = message.getArguments(); if (1 == args.length) { inputReceived(((String) args[0]).getBytes()); textEditor.setText("Typeatron keys: " + args[0] + " (" + totalButtonsCurrentlyPressed + " pressed)"); } else { textEditor.setText("Typeatron control error (wrong # of args)"); } } }); oscDispatcher.register("/exo/tt/error", new OSCMessageHandler() { public void handle(OSCMessage message) { Object[] args = message.getArguments(); if (1 == args.length) { textEditor.append("\nTypeatron device error: " + args[0]); } else { textEditor.setText("Typeatron control error (wrong # of args)"); } } }); } private void tryBrainmodeClient() throws IOException { PipedOutputStream pout = new PipedOutputStream(); PipedInputStream pin = new PipedInputStream(); pin.connect(pout); BrainModeClient client = new BrainModeClient(pin); } private void addChord(final String sequence, final Mode outputMode, final Modifier outputModifier, final String outputSymbol, final Mode inputMode) { StateNode cur = rootStates.get(inputMode); int l = sequence.length(); for (int j = 0; j < l; j++) { int index = sequence.charAt(j) - 49; StateNode next = cur.nextNodes[index]; if (null == next) { next = new StateNode(); cur.nextNodes[index] = next; } cur = next; } if (null != outputSymbol) { if (null != cur.symbol && !cur.symbol.equals(outputSymbol)) { throw new IllegalStateException("conflicting symbols for sequence " + sequence); } cur.symbol = outputSymbol; } if (null != outputMode) { if (null != cur.mode && cur.mode != outputMode) { throw new IllegalArgumentException("conflicting output modes for sequence " + sequence); } cur.mode = outputMode; } if (null != outputModifier) { if (null != cur.modifier && cur.modifier != outputModifier) { throw new IllegalArgumentException("conflicting output modifiers for sequence " + sequence); } cur.modifier = outputModifier; } if (null != cur.mode && null != cur.symbol) { throw new IllegalStateException("sequence has been assigned both an output symbol and an output mode: " + sequence); } else if (null != cur.modifier && Modifier.None != cur.modifier && (null != cur.mode || null != cur.symbol)) { throw new IllegalStateException("sequence has output modifier and also output symbol or mode"); } } private void setupParser() { // TODO: we shouldn't assume the device powers up with no buttons pressed, although this is likely totalButtonsCurrentlyPressed = 0; lastInput = "00000".getBytes(); rootStates = new HashMap<Mode, StateNode>(); for (Mode m : Mode.values()) { rootStates.put(m, new StateNode()); } currentMode = Mode.LowercaseText; currentModifier = Modifier.None; currentButtonState = rootStates.get(currentMode); // how get back to default mode from anywhere other than mash mode for (Mode m : Mode.values()) { if (m != Mode.Mash) { addChord("11", Mode.LowercaseText, Modifier.None, null, m); } } // mode entry from default mode addChord("1221", null, Modifier.Control, null, Mode.LowercaseText); // 1212 unassigned addChord("1331", Mode.Punctuation, null, null, Mode.LowercaseText); addChord("1313", Mode.Numeric, null, null, Mode.LowercaseText); addChord("1441", Mode.UppercaseText, null, null, Mode.LowercaseText); addChord("1414", Mode.LowercaseText, null, null, Mode.LowercaseText); // a no-op addChord("1551", Mode.Mash, Modifier.None, null, Mode.LowercaseText); // 1515 unassigned // break out of mash mode addChord("1234554321", Mode.LowercaseText, Modifier.None, null, Mode.Mash); // space, newline, delete, escape available in all of the text-entry modes for (Mode m : new Mode[]{Mode.LowercaseText, Mode.UppercaseText, Mode.Punctuation, Mode.Numeric}) { addChord("22", null, null, "SPACE", m); addChord("33", null, null, "RET", m); addChord("44", null, null, "DEL", m); addChord("55", null, null, "ESC", m); } addChord("2112", null, null, "a", Mode.LowercaseText); addChord("2112", null, null, "A", Mode.UppercaseText); addChord("2112", null, null, "'", Mode.Punctuation); // 2121 unassigned addChord("2332", null, null, "e", Mode.LowercaseText); addChord("2332", null, null, "E", Mode.UppercaseText); addChord("2332", null, null, "=", Mode.Punctuation); addChord("2323", null, null, "w", Mode.LowercaseText); addChord("2323", null, null, "W", Mode.UppercaseText); addChord("2323", null, null, "@", Mode.Punctuation); addChord("2442", null, null, "i", Mode.LowercaseText); addChord("2442", null, null, "I", Mode.UppercaseText); addChord("2442", null, null, ":", Mode.Punctuation); addChord("2424", null, null, "y", Mode.LowercaseText); addChord("2424", null, null, "Y", Mode.UppercaseText); addChord("2424", null, null, "&", Mode.Punctuation); addChord("2552", null, null, "o", Mode.LowercaseText); addChord("2552", null, null, "O", Mode.UppercaseText); // no punctuation associated with "o" addChord("2525", null, null, "u", Mode.LowercaseText); addChord("2525", null, null, "U", Mode.UppercaseText); addChord("2525", null, null, "_", Mode.Punctuation); addChord("3113", null, null, "p", Mode.LowercaseText); addChord("3113", null, null, "P", Mode.UppercaseText); addChord("3113", null, null, "+", Mode.Punctuation); addChord("3131", null, null, "b", Mode.LowercaseText); addChord("3131", null, null, "B", Mode.UppercaseText); addChord("3131", null, null, "\\", Mode.Punctuation); addChord("3223", null, null, "t", Mode.LowercaseText); addChord("3223", null, null, "T", Mode.UppercaseText); addChord("3223", null, null, "~", Mode.Punctuation); addChord("3232", null, null, "d", Mode.LowercaseText); addChord("3232", null, null, "D", Mode.UppercaseText); addChord("3232", null, null, "$", Mode.Punctuation); addChord("3443", null, null, "k", Mode.LowercaseText); addChord("3443", null, null, "K", Mode.UppercaseText); addChord("3443", null, null, "*", Mode.Punctuation); addChord("3434", null, null, "g", Mode.LowercaseText); addChord("3434", null, null, "G", Mode.UppercaseText); addChord("3434", null, null, "`", Mode.Punctuation); addChord("3553", null, null, "q", Mode.LowercaseText); addChord("3553", null, null, "Q", Mode.UppercaseText); addChord("3553", null, null, "?", Mode.Punctuation); // 3535 unassigned addChord("4114", null, null, "f", Mode.LowercaseText); addChord("4114", null, null, "F", Mode.UppercaseText); addChord("4114", null, null, ".", Mode.Punctuation); addChord("4141", null, null, "v", Mode.LowercaseText); addChord("4141", null, null, "V", Mode.UppercaseText); addChord("4141", null, null, "|", Mode.Punctuation); addChord("4224", null, null, "c", Mode.LowercaseText); addChord("4224", null, null, "C", Mode.UppercaseText); addChord("4224", null, null, ",", Mode.Punctuation); addChord("4242", null, null, "j", Mode.LowercaseText); addChord("4242", null, null, "J", Mode.UppercaseText); addChord("4242", null, null, ";", Mode.Punctuation); addChord("4334", null, null, "s", Mode.LowercaseText); addChord("4334", null, null, "S", Mode.UppercaseText); addChord("4334", null, null, "/", Mode.Punctuation); addChord("4343", null, null, "z", Mode.LowercaseText); addChord("4343", null, null, "Z", Mode.UppercaseText); addChord("4343", null, null, "%", Mode.Punctuation); addChord("4554", null, null, "h", Mode.LowercaseText); addChord("4554", null, null, "H", Mode.UppercaseText); addChord("4554", null, null, "^", Mode.Punctuation); addChord("4545", null, null, "x", Mode.LowercaseText); addChord("4545", null, null, "X", Mode.UppercaseText); addChord("4545", null, null, "!", Mode.Punctuation); addChord("5115", null, null, "m", Mode.LowercaseText); addChord("5115", null, null, "M", Mode.UppercaseText); addChord("5115", null, null, "-", Mode.Punctuation); // 5151 unassigned addChord("5225", null, null, "n", Mode.LowercaseText); addChord("5225", null, null, "N", Mode.UppercaseText); addChord("5225", null, null, "#", Mode.Punctuation); // 5252 unassigned addChord("5335", null, null, "l", Mode.LowercaseText); addChord("5335", null, null, "L", Mode.UppercaseText); addChord("5335", null, null, "\"", Mode.Punctuation); // 5353 unassigned addChord("5445", null, null, "r", Mode.LowercaseText); addChord("5445", null, null, "R", Mode.UppercaseText); // no punctuation associated with "r" (reserved for right-handed quotes) // 5454 unassigned } // buttonIndex: 0 (thumb) through 4 (pinky) private void buttonEvent(int buttonIndex) { if (null != currentButtonState) { currentButtonState = currentButtonState.nextNodes[buttonIndex]; } } private void buttonPressed(int buttonIndex) { totalButtonsCurrentlyPressed++; buttonEvent(buttonIndex); } private String produceSymbol(final String symbol) { switch (currentModifier) { case Control: return symbol.length() == 1 ? "C-" + symbol : symbol; case None: return symbol; default: throw new IllegalStateException(); } } private void buttonReleased(int buttonIndex) { totalButtonsCurrentlyPressed buttonEvent(buttonIndex); // at present, events are triggered when the last key of a sequence is released if (0 == totalButtonsCurrentlyPressed) { if (null != currentButtonState) { String symbol = currentButtonState.symbol; if (null != symbol) { toaster.makeText("typed: " + produceSymbol(symbol)); } else { Mode mode = currentButtonState.mode; if (null != mode) { currentMode = mode; toaster.makeText("entered mode: " + mode); } Modifier modifier = currentButtonState.modifier; if (null != modifier) { currentModifier = modifier; toaster.makeText("using modifier: " + modifier); } } } currentButtonState = rootStates.get(currentMode); } } private void inputReceived(byte[] input) { for (int i = 0; i < 5; i++) { // Generally, at most one button should change per time step // However, if two buttons change state, it is an arbitrary choice w.r.t. which one changed first if (input[i] != lastInput[i]) { if ('1' == input[i]) { buttonPressed(i); } else { buttonReleased(i); } } } lastInput = input; } }
package net.mcft.copy.backpacks.misc.util; import java.lang.reflect.Method; import java.util.Arrays; import net.minecraft.item.ItemStack; import net.minecraftforge.fml.common.Loader; import net.mcft.copy.backpacks.WearableBackpacks; public final class IntermodUtils { private IntermodUtils() { } private static final int DEFAULT_ENCHANTMENT_COLOR = 0xFF8040CC; private static boolean getRuneColorCached = false; private static Method setTargetStackMethod = null; private static Method getColorMethod = null; /** Returns the Quark rune color for this item or the default enchant glint * color if Quark isn't present or the item doesn't have a custom rune color. */ public static int getRuneColor(ItemStack stack) { if (!getRuneColorCached) { if (Loader.isModLoaded("quark")) { try { Class<?> clazz = Class.forName("vazkii.quark.misc.feature.ColorRunes"); setTargetStackMethod = clazz.getMethod("setTargetStack", ItemStack.class); getColorMethod = Arrays.stream(clazz.getMethods()) .filter(m -> "getColor".equals(m.getName())) .findAny().orElse(null); } catch (ClassNotFoundException | NoSuchMethodException ex) { WearableBackpacks.LOG.error("Error while fetching Quark ColorRunes methods", ex); } } getRuneColorCached = true; } if ((setTargetStackMethod == null) || (getColorMethod == null)) return DEFAULT_ENCHANTMENT_COLOR; try { setTargetStackMethod.invoke(null, stack); return (getColorMethod.getParameterCount() == 0) ? (int)getColorMethod.invoke(null) : (int)getColorMethod.invoke(null, DEFAULT_ENCHANTMENT_COLOR); } catch (Exception ex) { WearableBackpacks.LOG.error("Error while invoking Quark ColorRunes methods", ex); setTargetStackMethod = null; getColorMethod = null; return DEFAULT_ENCHANTMENT_COLOR; } } }
package net.techcable.techutils.config; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.net.URL; import java.util.Set; import net.techcable.techutils.Reflection; import net.techcable.techutils.collect.Collections3; import net.techcable.techutils.config.seralizers.BooleanSerializer; import net.techcable.techutils.config.seralizers.ByteSeralizer; import net.techcable.techutils.config.seralizers.CharSerializer; import net.techcable.techutils.config.seralizers.DoubleSerializer; import net.techcable.techutils.config.seralizers.FloatSerializer; import net.techcable.techutils.config.seralizers.IntSeralizer; import net.techcable.techutils.config.seralizers.ListSerializer; import net.techcable.techutils.config.seralizers.LongSerializer; import net.techcable.techutils.config.seralizers.ShortSeralizer; import net.techcable.techutils.config.seralizers.StringSerializer; import org.bukkit.configuration.InvalidConfigurationException; import org.bukkit.configuration.file.YamlConfiguration; import com.google.common.primitives.Primitives; public class AnnotationConfig { private static final Set<ConfigSerializer> serializers = Collections3.newConcurrentHashSet(); public static void addSerializer(ConfigSerializer serializer) { serializers.add(serializer); } static { addSerializer(new BooleanSerializer()); addSerializer(new ByteSeralizer()); addSerializer(new CharSerializer()); addSerializer(new DoubleSerializer()); addSerializer(new FloatSerializer()); addSerializer(new IntSeralizer()); addSerializer(new ListSerializer()); addSerializer(new LongSerializer()); addSerializer(new ShortSeralizer()); addSerializer(new StringSerializer()); } public static ConfigSerializer getSerializer(Class<?> type) { for (ConfigSerializer serializer : serializers) { if (serializer.canHandle(type)) return serializer; } return null; } public void load(File configFile, URL defaultConfigUrl) throws IOException, InvalidConfigurationException { YamlConfiguration existingConfig; boolean shouldSave = false; if (configFile.exists()) { existingConfig = YamlConfiguration.loadConfiguration(configFile); } else { existingConfig = new YamlConfiguration(); shouldSave = true; } YamlConfiguration config = YamlConfiguration.loadConfiguration(defaultConfigUrl.openStream()); for (String key : config.getKeys(true)) { if (!existingConfig.contains(key)) { shouldSave = true; } else { config.set(key, existingConfig.get(key)); } } for (Field field : getClass().getDeclaredFields()) { if (!field.isAnnotationPresent(Setting.class)) continue; String key = field.getAnnotation(Setting.class).value(); if (!config.contains(key)) { throw new InvalidConfigurationException("Unknown key: " + key); } Object yaml = config.get(key); Class<?> yamlType = Primitives.isWrapperType(yaml.getClass()) ? Primitives.unwrap(yaml.getClass()) : yaml.getClass(); if (getSerializer(field.getType()) == null) throw new InvalidConfigurationException("No seralizer for the type " + field.getType().getSimpleName()); Object java = getSerializer(field.getType()).deserialize(yaml, field.getType()); Class<?> javaType = Primitives.isWrapperType(java.getClass()) ? Primitives.unwrap(java.getClass()) : java.getClass(); if (!field.getType().isAssignableFrom(javaType)) { throw new InvalidConfigurationException(key + " is not instanceof " + field.getType().getSimpleName()); } Reflection.setField(field, this, java); } if (shouldSave) config.save(configFile); } public void save(File configFile, URL defaultConfigUrl) throws IOException, InvalidConfigurationException { YamlConfiguration defaultConfig = YamlConfiguration.loadConfiguration(defaultConfigUrl.openStream()); for (Field field : getClass().getDeclaredFields()) { if (!field.isAnnotationPresent(Setting.class)) continue; String key = field.getAnnotation(Setting.class).value(); if (!defaultConfig.contains(key)) { throw new InvalidConfigurationException("Unknown key: " + key); } Object rawValue = Reflection.getField(field, this); Class<?> javaType = rawValue.getClass().isPrimitive() ? Primitives.wrap(rawValue.getClass()) : rawValue.getClass(); if (getSerializer(javaType) == null) throw new InvalidConfigurationException("No seralizer for the type " + rawValue.getClass().getSimpleName()); Object yamlValue = getSerializer(rawValue.getClass()).serialize(rawValue); defaultConfig.set(key, yamlValue); } defaultConfig.save(configFile); } }
package ly.count.android.sdk; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.util.Log; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.HashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; @SuppressWarnings("JavadocReference") public class Countly { /** * Current version of the Count.ly Android SDK as a displayable string. */ public static final String COUNTLY_SDK_VERSION_STRING = "20.04.2"; /** * Used as request meta data on every request */ protected static final String COUNTLY_SDK_NAME = "java-native-android"; /** * Default string used in the begin session metrics if the * app version cannot be found. */ protected static final String DEFAULT_APP_VERSION = "1.0"; /** * Tag used in all logging in the Count.ly SDK. */ public static final String TAG = "Countly"; /** * Broadcast sent when consent set is changed */ public static final String CONSENT_BROADCAST = "ly.count.android.sdk.Countly.CONSENT_BROADCAST"; /** * Determines how many custom events can be queued locally before * an attempt is made to submit them to a Count.ly server. */ private static int EVENT_QUEUE_SIZE_THRESHOLD = 10; /** * How often onTimer() is called. */ private static final long TIMER_DELAY_IN_SECONDS = 60; protected static List<String> publicKeyPinCertificates; protected static List<String> certificatePinCertificates; /** * Enum used in Countly.initMessaging() method which controls what kind of * app installation it is. Later (in Countly Dashboard or when calling Countly API method), * you'll be able to choose whether you want to send a message to test devices, * or to production ones. */ public enum CountlyMessagingMode { TEST, PRODUCTION, } private static class SingletonHolder { @SuppressLint("StaticFieldLeak") static final Countly instance = new Countly(); } ConnectionQueue connectionQueue_; private final ScheduledExecutorService timerService_; private ScheduledFuture<?> timerFuture = null; EventQueue eventQueue_; private int activityCount_; boolean disableUpdateSessionRequests_ = false;//todo, move to module after 'setDisableUpdateSessionRequests' is removed //w - warnings //e - errors //i - user accessible calls and important SDK internals //d - regular SDK internals //v - spammy SDK internals private boolean enableLogging_; private Countly.CountlyMessagingMode messagingMode_; Context context_; //Internal modules for functionality grouping List<ModuleBase> modules = new ArrayList<>(); ModuleCrash moduleCrash = null; ModuleEvents moduleEvents = null; ModuleViews moduleViews = null; ModuleRatings moduleRatings = null; ModuleSessions moduleSessions = null; ModuleRemoteConfig moduleRemoteConfig = null; ModuleAPM moduleAPM = null; ModuleConsent moduleConsent = null; ModuleDeviceId moduleDeviceId = null; //user data access public static UserData userData; //view related things boolean autoViewTracker = false;//todo, move to module after "setViewTracking" is removed boolean automaticTrackingShouldUseShortName = false;//flag for using short names | todo, move to module after setter is removed //if set to true, it will automatically download remote configs on module startup boolean remoteConfigAutomaticUpdateEnabled = false;//todo, move to module after setter is removed RemoteConfigCallback remoteConfigInitCallback = null;//todo, move to module after setter is removed //overrides private boolean isHttpPostForced = false;//when true, all data sent to the server will be sent using HTTP POST //app crawlers private boolean shouldIgnoreCrawlers = true;//ignore app crawlers by default private boolean deviceIsAppCrawler = false;//by default assume that device is not a app crawler @SuppressWarnings("ArraysAsListWithZeroOrOneArgument") private final List<String> appCrawlerNames = new ArrayList<>(Arrays.asList("Calypso AppCrawler"));//List against which device name is checked to determine if device is app crawler //push related private boolean addMetadataToPushIntents = false;// a flag that indicates if metadata should be added to push notification intents //internal flags private boolean calledAtLeastOnceOnStart = false;//flag for if the onStart function has been called at least once //attribution protected boolean isAttributionEnabled = true; protected boolean isBeginSessionSent = false; //custom request header fields Map<String, String> requestHeaderCustomValues; static long applicationStart = -1; //GDPR protected boolean requiresConsent = false; private final Map<String, Boolean> featureConsentValues = new HashMap<>(); private final Map<String, String[]> groupedFeatures = new HashMap<>(); final List<String> collectedConsentChanges = new ArrayList<>(); Boolean delayedPushConsent = null;//if this is set, consent for push has to be set before finishing init and sending push changes boolean delayedLocationErasure = false;//if location needs to be cleared at the end of init private boolean appLaunchDeepLink = true; CountlyConfig config_ = null; public static class CountlyFeatureNames { public static final String sessions = "sessions"; public static final String events = "events"; public static final String views = "views"; //public static final String scrolls = "scrolls"; //public static final String clicks = "clicks"; //public static final String forms = "forms"; public static final String location = "location"; public static final String crashes = "crashes"; public static final String attribution = "attribution"; public static final String users = "users"; public static final String push = "push"; public static final String starRating = "star-rating"; //public static final String accessoryDevices = "accessory-devices"; } //a list of valid feature names that are used for checking protected final String[] validFeatureNames = new String[] { CountlyFeatureNames.sessions, CountlyFeatureNames.events, CountlyFeatureNames.views, CountlyFeatureNames.location, CountlyFeatureNames.crashes, CountlyFeatureNames.attribution, CountlyFeatureNames.users, CountlyFeatureNames.push, CountlyFeatureNames.starRating }; /** * Returns the Countly singleton. */ public static Countly sharedInstance() { return SingletonHolder.instance; } /** * Constructs a Countly object. * Creates a new ConnectionQueue and initializes the session timer. */ Countly() { timerService_ = Executors.newSingleThreadScheduledExecutor(); staticInit(); } private void staticInit(){ connectionQueue_ = new ConnectionQueue(); Countly.userData = new UserData(connectionQueue_); startTimerService(timerService_, timerFuture, TIMER_DELAY_IN_SECONDS); } private void startTimerService(ScheduledExecutorService service, ScheduledFuture<?> previousTimer, long timerDelay) { if (previousTimer != null && !previousTimer.isCancelled()) { previousTimer.cancel(false); } //minimum delay of 1 second //maximum delay if 10 minutes if (timerDelay < 1) { timerDelay = 1; } else if (timerDelay > 600) { timerDelay = 600; } timerFuture = service.scheduleWithFixedDelay(new Runnable() { @Override public void run() { onTimer(); } }, timerDelay, timerDelay, TimeUnit.SECONDS); } public Countly init(final Context context, final String serverURL, final String appKey) { return init(context, serverURL, appKey, null, OpenUDIDAdapter.isOpenUDIDAvailable() ? DeviceId.Type.OPEN_UDID : DeviceId.Type.ADVERTISING_ID); } public Countly init(final Context context, final String serverURL, final String appKey, final String deviceID) { return init(context, serverURL, appKey, deviceID, null); } public synchronized Countly init(final Context context, final String serverURL, final String appKey, final String deviceID, DeviceId.Type idMode) { return init(context, serverURL, appKey, deviceID, idMode, -1, null, null, null, null); } public synchronized Countly init(final Context context, String serverURL, final String appKey, final String deviceID, DeviceId.Type idMode, int starRatingLimit, final CountlyStarRating.RatingCallback starRatingCallback, String starRatingTextTitle, String starRatingTextMessage, String starRatingTextDismiss) { CountlyConfig config = new CountlyConfig(); config.setContext(context).setServerURL(serverURL).setAppKey(appKey).setDeviceId(deviceID) .setStarRatingTextTitle(starRatingTextTitle).setStarRatingTextMessage(starRatingTextMessage) .setStarRatingTextDismiss(starRatingTextDismiss) .setIdMode(idMode).setStarRatingSessionLimit(starRatingLimit).setStarRatingCallback(new StarRatingCallback() { @Override public void onRate(int rating) { if (starRatingCallback != null) { starRatingCallback.onRate(rating); } } @Override public void onDismiss() { if (starRatingCallback != null) { starRatingCallback.onDismiss(); } } }); return init(config); } /** * Initializes the Countly SDK. Call from your main Activity's onCreate() method. * Must be called before other SDK methods can be used. * * @param config contains all needed information to init SDK */ public synchronized Countly init(CountlyConfig config) { //enable logging if (config.loggingEnabled) { //enable logging before any potential logging calls setLoggingEnabled(true); } if (isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] Initializing Countly SDk version " + COUNTLY_SDK_VERSION_STRING); } if (config.context == null) { throw new IllegalArgumentException("valid context is required in Countly init, but was provided 'null'"); } if (!UtilsNetworking.isValidURL(config.serverURL)) { throw new IllegalArgumentException("valid serverURL is required"); } //enable unhandled crash reporting if (config.enableUnhandledCrashReporting) { enableCrashReporting(); } //react to given consent if (config.shouldRequireConsent) { setRequiresConsent(true); setConsent(config.enabledFeatureNames, true); } if (config.serverURL.charAt(config.serverURL.length() - 1) == '/') { if (isLoggingEnabled()) { Log.v(Countly.TAG, "[Init] Removing trailing '/' from provided server url"); } config.serverURL = config.serverURL.substring(0, config.serverURL.length() - 1);//removing trailing '/' from server url } if (config.appKey == null || config.appKey.length() == 0) { throw new IllegalArgumentException("valid appKey is required, but was provided either 'null' or empty String"); } if (config.deviceID != null && config.deviceID.length() == 0) { //device ID is provided but it's a empty string throw new IllegalArgumentException("valid deviceID is required, but was provided as empty String"); } if (config.deviceID == null && config.idMode == null) { //device ID was not provided and no preferred mode specified. Choosing defaults if (OpenUDIDAdapter.isOpenUDIDAvailable()) { config.idMode = DeviceId.Type.OPEN_UDID; } else if (AdvertisingIdAdapter.isAdvertisingIdAvailable()) config.idMode = DeviceId.Type.ADVERTISING_ID; } if (config.deviceID == null && config.idMode == DeviceId.Type.OPEN_UDID && !OpenUDIDAdapter.isOpenUDIDAvailable()) { //choosing OPEN_UDID as ID type, but it's not available on this device throw new IllegalArgumentException("valid deviceID is required because OpenUDID is not available"); } if (config.deviceID == null && config.idMode == DeviceId.Type.ADVERTISING_ID && !AdvertisingIdAdapter.isAdvertisingIdAvailable()) { //choosing advertising ID as type, but it's available on this device throw new IllegalArgumentException("valid deviceID is required because Advertising ID is not available (you need to include Google Play services 4.0+ into your project)"); } if (eventQueue_ != null && (!connectionQueue_.getServerURL().equals(config.serverURL) || !connectionQueue_.getAppKey().equals(config.appKey) || !DeviceId.deviceIDEqualsNullSafe(config.deviceID, config.idMode, connectionQueue_.getDeviceId()))) { //not sure if this needed throw new IllegalStateException("Countly cannot be reinitialized with different values"); } if (isLoggingEnabled()) { Log.i(Countly.TAG, "[Init] Checking init parameters"); Log.i(Countly.TAG, "[Init] Is consent required? [" + requiresConsent + "]"); // Context class hierarchy // Context //|- ContextWrapper //|- - Application //|- - ContextThemeWrapper //|- - - - Activity //|- - Service //|- - - IntentService Class contextClass = config.context.getClass(); Class contextSuperClass = contextClass.getSuperclass(); String contextText = "[Init] Provided Context [" + config.context.getClass().getSimpleName() + "]"; if (contextSuperClass != null) { contextText += ", it's superclass: [" + contextSuperClass.getSimpleName() + "]"; } Log.i(Countly.TAG, contextText); } //set internal context, it's allowed to be changed on the second init call context_ = config.context.getApplicationContext(); // if we get here and eventQueue_ != null, init is being called again with the same values, // so there is nothing to do, because we are already initialized with those values if (eventQueue_ == null) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] About to init internal systems"); } config_ = config; if (config.sessionUpdateTimerDelay != null) { //if we need to change the timer delay, do that first startTimerService(timerService_, timerFuture, config.sessionUpdateTimerDelay); } final CountlyStore countlyStore; if (config.countlyStore != null) { //we are running a test and using a mock object countlyStore = config.countlyStore; } else { countlyStore = new CountlyStore(config.context); config.setCountlyStore(countlyStore); } //initialise modules moduleDeviceId = new ModuleDeviceId(this, config); moduleCrash = new ModuleCrash(this, config); moduleEvents = new ModuleEvents(this, config); moduleViews = new ModuleViews(this, config); moduleRatings = new ModuleRatings(this, config); moduleSessions = new ModuleSessions(this, config); moduleRemoteConfig = new ModuleRemoteConfig(this, config); moduleConsent = new ModuleConsent(this, config); moduleAPM = new ModuleAPM(this, config); modules.clear(); modules.add(moduleCrash); modules.add(moduleEvents); modules.add(moduleViews); modules.add(moduleRatings); modules.add(moduleSessions); modules.add(moduleRemoteConfig); modules.add(moduleConsent); modules.add(moduleAPM); modules.add(moduleDeviceId); if (isLoggingEnabled()) { Log.i(Countly.TAG, "[Init] Finished initialising modules"); } //init other things addCustomNetworkRequestHeaders(config.customNetworkRequestHeaders); setPushIntentAddMetadata(config.pushIntentAddMetadata); setRemoteConfigAutomaticDownload(config.enableRemoteConfigAutomaticDownload, config.remoteConfigCallback); setHttpPostForced(config.httpPostForced); enableParameterTamperingProtectionInternal(config.tamperingProtectionSalt); if (config.eventQueueSizeThreshold != null) { setEventQueueSizeToSend(config.eventQueueSizeThreshold); } if (config.publicKeyPinningCertificates != null) { enablePublicKeyPinning(Arrays.asList(config.publicKeyPinningCertificates)); } if (config.certificatePinningCertificates != null) { enableCertificatePinning(Arrays.asList(config.certificatePinningCertificates)); } if (config.enableAttribution != null) { setEnableAttribution(config.enableAttribution); } //app crawler check shouldIgnoreCrawlers = config.shouldIgnoreAppCrawlers; if (config.appCrawlerNames != null) { Collections.addAll(Arrays.asList(config.appCrawlerNames)); } checkIfDeviceIsAppCrawler(); boolean doingTemporaryIdMode = false; boolean customIDWasProvided = (config.deviceID != null); if (config.temporaryDeviceIdEnabled && !customIDWasProvided) { //if we want to use temporary ID mode and no developer custom ID is provided //then we override that custom ID to set the temporary mode config.deviceID = DeviceId.temporaryCountlyDeviceId; doingTemporaryIdMode = true; } DeviceId deviceIdInstance; if (config.deviceID != null) { //if the developer provided a ID deviceIdInstance = new DeviceId(countlyStore, config.deviceID); } else { //the dev provided only a type, generate a appropriate ID deviceIdInstance = new DeviceId(countlyStore, config.idMode); } if (isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] Currently cached advertising ID [" + countlyStore.getCachedAdvertisingId() + "]"); } AdvertisingIdAdapter.cacheAdvertisingID(config.context, countlyStore); deviceIdInstance.init(config.context, countlyStore, true); boolean temporaryDeviceIdWasEnabled = deviceIdInstance.temporaryIdModeEnabled(); if (isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] [TemporaryDeviceId] Previously was enabled: [" + temporaryDeviceIdWasEnabled + "]"); } if (temporaryDeviceIdWasEnabled) { //if we previously we're in temporary ID mode if (!config.temporaryDeviceIdEnabled || customIDWasProvided) { //if we don't set temporary device ID mode or //a custom device ID is explicitly provided //that means we have to exit temporary ID mode if (isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] [TemporaryDeviceId] Decided we have to exit temporary device ID mode, mode enabled: [" + config.temporaryDeviceIdEnabled + "], custom Device ID Set: [" + customIDWasProvided + "]"); } } else { //we continue to stay in temporary ID mode //no changes need to happen if (isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] [TemporaryDeviceId] Decided to stay in temporary ID mode"); } } } else { if (config.temporaryDeviceIdEnabled && config.deviceID == null) { //temporary device ID mode is enabled and //no custom device ID is provided //we can safely enter temporary device ID mode if (isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] [TemporaryDeviceId] Decided to enter temporary ID mode"); } } } //initialize networking queues connectionQueue_.setServerURL(config.serverURL); connectionQueue_.setAppKey(config.appKey); connectionQueue_.setCountlyStore(countlyStore); connectionQueue_.setDeviceId(deviceIdInstance); connectionQueue_.setRequestHeaderCustomValues(requestHeaderCustomValues); connectionQueue_.setContext(context_); eventQueue_ = new EventQueue(countlyStore); if (doingTemporaryIdMode) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] Trying to enter temporary ID mode"); } //if we are doing temporary ID, make sure it is applied //if it's not, change ID to it if (!deviceIdInstance.temporaryIdModeEnabled()) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] Temporary ID mode was not enabled, entering it"); } //temporary ID is not set changeDeviceId(DeviceId.temporaryCountlyDeviceId); } else { if (isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] Temporary ID mode was enabled previously, nothing to enter"); } } } //do star rating related things if (getConsent(CountlyFeatureNames.starRating)) { moduleRatings.registerAppSession(config.context, countlyStore, moduleRatings.starRatingCallback_); } //do location related things if (config.disableLocation) { disableLocation(); } else { //if we are not disabling location, check for other set values if (config.locationIpAddress != null || config.locationLocation != null || config.locationCity != null || config.locationCountyCode != null) { setLocation(config.locationCountyCode, config.locationCity, config.locationLocation, config.locationIpAddress); } } //update remote config_ values if automatic update is enabled and we are not in temporary id mode if (remoteConfigAutomaticUpdateEnabled && anyConsentGiven() && !doingTemporaryIdMode) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "[Init] Automatically updating remote config values"); } moduleRemoteConfig.updateRemoteConfigValues(null, null, connectionQueue_, false, remoteConfigInitCallback); } //set global application listeners if (config.application != null) { config.application.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() { @Override public void onActivityCreated(Activity activity, Bundle bundle) { if (isLoggingEnabled()) { String actName = activity.getClass().getSimpleName(); Log.d(Countly.TAG, "[Countly] onActivityCreated, " + actName); } for (ModuleBase module : modules) { module.callbackOnActivityCreated(activity); } } @Override public void onActivityStarted(Activity activity) { if (isLoggingEnabled()) { String actName = activity.getClass().getSimpleName(); Log.d(Countly.TAG, "[Countly] onActivityStarted, " + actName); } for (ModuleBase module : modules) { module.callbackOnActivityStarted(activity); } } @Override public void onActivityResumed(Activity activity) { if (isLoggingEnabled()) { String actName = activity.getClass().getSimpleName(); Log.d(Countly.TAG, "[Countly] onActivityResumed, " + actName); } for (ModuleBase module : modules) { module.callbackOnActivityResumed(activity); } } @Override public void onActivityPaused(Activity activity) { if (isLoggingEnabled()) { String actName = activity.getClass().getSimpleName(); Log.d(Countly.TAG, "[Countly] onActivityPaused, " + actName); } for (ModuleBase module : modules) { module.callbackOnActivityPaused(activity); } } @Override public void onActivityStopped(Activity activity) { if (isLoggingEnabled()) { String actName = activity.getClass().getSimpleName(); Log.d(Countly.TAG, "[Countly] onActivityStopped, " + actName); } for (ModuleBase module : modules) { module.callbackOnActivityStopped(activity); } } @Override public void onActivitySaveInstanceState(Activity activity, Bundle bundle) { if (isLoggingEnabled()) { String actName = activity.getClass().getSimpleName(); Log.d(Countly.TAG, "[Countly] onActivitySaveInstanceState, " + actName); } for (ModuleBase module : modules) { module.callbackOnActivitySaveInstanceState(activity); } } @Override public void onActivityDestroyed(Activity activity) { if (isLoggingEnabled()) { String actName = activity.getClass().getSimpleName(); Log.d(Countly.TAG, "[Countly] onActivityDestroyed, " + actName); } for (ModuleBase module : modules) { module.callbackOnActivityDestroyed(activity); } } }); /* config.application.registerComponentCallbacks(new ComponentCallbacks() { @Override public void onConfigurationChanged(Configuration configuration) { } @Override public void onLowMemory() { } }); */ } } else { //if this is not the first time we are calling init // context is allowed to be changed on the second init call connectionQueue_.setContext(context_); } for (ModuleBase module : modules) { module.initFinished(config); } return this; } /** * Checks whether Countly.init has been already called. * * @return true if Countly is ready to use */ @SuppressWarnings("BooleanMethodIsAlwaysInverted") public synchronized boolean isInitialized() { return eventQueue_ != null; } public synchronized void halt() { if (isLoggingEnabled()) { Log.i(Countly.TAG, "Halting Countly!"); } eventQueue_ = null; if(connectionQueue_ != null) { final CountlyStore countlyStore = connectionQueue_.getCountlyStore(); if (countlyStore != null) { countlyStore.clear(); } connectionQueue_.setContext(null); connectionQueue_.setServerURL(null); connectionQueue_.setAppKey(null); connectionQueue_.setCountlyStore(null); connectionQueue_ = null; } activityCount_ = 0; for (ModuleBase module : modules) { module.halt(); } modules.clear(); moduleCrash = null; moduleViews = null; moduleEvents = null; moduleRatings = null; moduleSessions = null; moduleRemoteConfig = null; moduleConsent = null; moduleAPM = null; moduleDeviceId = null; staticInit(); } synchronized void notifyDeviceIdChange() { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Notifying modules that device ID changed"); } for (ModuleBase module : modules) { module.deviceIdChanged(); } } public synchronized void onStart(Activity activity) { if (isLoggingEnabled()) { String activityName = "NULL ACTIVITY PROVIDED"; if (activity != null) { activityName = activity.getClass().getSimpleName(); } Log.d(Countly.TAG, "Countly onStart called, name:[" + activityName + "], [" + activityCount_ + "] -> [" + (activityCount_ + 1) + "] activities now open"); } appLaunchDeepLink = false; if (!isInitialized()) { throw new IllegalStateException("init must be called before onStart"); } ++activityCount_; if (activityCount_ == 1 && !moduleSessions.manualSessionControlEnabled) { //if we open the first activity //and we are not using manual session control, //begin a session moduleSessions.beginSessionInternal(); } //check if there is an install referrer data String referrer = ReferrerReceiver.getReferrer(context_); if (isLoggingEnabled()) { Log.d(Countly.TAG, "Checking referrer: " + referrer); } if (referrer != null) { connectionQueue_.sendReferrerData(referrer); ReferrerReceiver.deleteReferrer(context_); } CrashDetails.inForeground(); for (ModuleBase module : modules) { module.onActivityStarted(activity); } calledAtLeastOnceOnStart = true; } public synchronized void onStop() { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Countly onStop called, [" + activityCount_ + "] -> [" + (activityCount_ - 1) + "] activities now open"); } if (!isInitialized()) { throw new IllegalStateException("init must be called before onStop"); } if (activityCount_ == 0) { throw new IllegalStateException("must call onStart before onStop"); } --activityCount_; if (activityCount_ == 0 && !moduleSessions.manualSessionControlEnabled) { // if we don't use manual session control // Called when final Activity is stopped. // Sends an end session event to the server, also sends any unsent custom events. moduleSessions.endSessionInternal(null); } CrashDetails.inBackground(); for (ModuleBase module : modules) { module.onActivityStopped(); } } public synchronized void onConfigurationChanged(Configuration newConfig) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Calling [onConfigurationChanged]"); } if (!isInitialized()) { throw new IllegalStateException("init must be called before onConfigurationChanged"); } for (ModuleBase module : modules) { module.onConfigurationChanged(newConfig); } } /** * DON'T USE THIS!!!! */ public void onRegistrationId(String registrationId, CountlyMessagingMode mode) { if (!getConsent(CountlyFeatureNames.push)) { return; } connectionQueue_.tokenSession(registrationId, mode); } /** * Changes current device id type to the one specified in parameter. Closes current session and * reopens new one with new id. Doesn't merge user profiles on the server * * @param type Device ID type to change to * @param deviceId Optional device ID for a case when type = DEVELOPER_SPECIFIED */ public void changeDeviceIdWithoutMerge(DeviceId.Type type, String deviceId) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Calling [changeDeviceIdWithoutMerge] with type and ID"); } if (!isInitialized()) { throw new IllegalStateException("init must be called before changeDeviceIdWithoutMerge"); } moduleDeviceId.changeDeviceIdWithoutMerge(type, deviceId); } /** * Changes current device id to the one specified in parameter. Merges user profile with new id * (if any) with old profile. * * @param deviceId new device id */ public void changeDeviceIdWithMerge(String deviceId) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Calling [changeDeviceIdWithMerge] only with ID"); } if (!isInitialized()) { throw new IllegalStateException("init must be called before changeDeviceIdWithMerge"); } moduleDeviceId.changeDeviceIdWithMerge(deviceId); } /** * Changes current device id type to the one specified in parameter. Closes current session and * reopens new one with new id. Doesn't merge user profiles on the server * * @param type Device ID type to change to * @param deviceId Optional device ID for a case when type = DEVELOPER_SPECIFIED * @deprecated use 'changeDeviceIdWithoutMerge' */ public void changeDeviceId(DeviceId.Type type, String deviceId) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Calling [changeDeviceId] with type and ID"); } if (!isInitialized()) { throw new IllegalStateException("init must be called before changeDeviceId"); } moduleDeviceId.changeDeviceIdWithoutMerge(type, deviceId); } /** * Changes current device id to the one specified in parameter. Merges user profile with new id * (if any) with old profile. * * @param deviceId new device id * @deprecated use 'changeDeviceIdWithMerge' */ public void changeDeviceId(String deviceId) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Calling [changeDeviceId] only with ID"); } if (!isInitialized()) { throw new IllegalStateException("init must be called before changeDeviceId"); } moduleDeviceId.changeDeviceIdWithMerge(deviceId); } public void recordEvent(final String key) { recordEvent(key, null, 1, 0); } public void recordEvent(final String key, final int count) { recordEvent(key, null, count, 0); } public void recordEvent(final String key, final int count, final double sum) { recordEvent(key, null, count, sum); } public void recordEvent(final String key, final Map<String, String> segmentation, final int count) { recordEvent(key, segmentation, count, 0); } public synchronized void recordEvent(final String key, final Map<String, String> segmentation, final int count, final double sum) { recordEvent(key, segmentation, count, sum, 0); } public synchronized void recordEvent(final String key, final Map<String, String> segmentation, final int count, final double sum, final double dur) { recordEvent(key, segmentation, null, null, count, sum, dur); } public synchronized void recordEvent(final String key, final Map<String, String> segmentation, final Map<String, Integer> segmentationInt, final Map<String, Double> segmentationDouble, final int count, final double sum, final double dur) { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before recordEvent"); } Map<String, Object> segmentationGroup = new HashMap<>(); if (segmentation != null) { segmentationGroup.putAll(segmentation); } if (segmentationInt != null) { segmentationGroup.putAll(segmentationInt); } if (segmentationDouble != null) { segmentationGroup.putAll(segmentationDouble); } events().recordEvent(key, segmentationGroup, count, sum, dur); } /** * Enable or disable automatic view tracking * * @param enable boolean for the state of automatic view tracking * @return Returns link to Countly for call chaining * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setViewTracking(boolean enable) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Enabling automatic view tracking"); } autoViewTracker = enable; return this; } /** * Check state of automatic view tracking * * @return boolean - true if enabled, false if disabled * @deprecated use 'Countly.sharedInstance().views().isAutomaticViewTrackingEnabled()' */ public synchronized boolean isViewTrackingEnabled() { return autoViewTracker; } /** * Record a view manually, without automatic tracking * or track view that is not automatically tracked * like fragment, Message box or transparent Activity * * @param viewName String - name of the view * @return Returns link to Countly for call chaining * @deprecated use 'Countly.sharedInstance().views().recordView()' */ public synchronized Countly recordView(String viewName) { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before recordView"); } return recordView(viewName, null); } /** * Record a view manually, without automatic tracking * or track view that is not automatically tracked * like fragment, Message box or transparent Activity * * @param viewName String - name of the view * @param viewSegmentation Map<String, Object> - segmentation that will be added to the view, set 'null' if none should be added * @return Returns link to Countly for call chaining * @deprecated use 'Countly.sharedInstance().views().recordView()' */ public synchronized Countly recordView(String viewName, Map<String, Object> viewSegmentation) { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before recordView"); } return moduleViews.recordViewInternal(viewName, viewSegmentation); } /** * Disable sending of location data * * @return Returns link to Countly for call chaining */ public synchronized Countly disableLocation() { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Disabling location"); } if (!isInitialized()) { if (isLoggingEnabled()) { Log.w(Countly.TAG, "The use of this before init is deprecated, use CountlyConfig instead of this"); } } if (!getConsent(CountlyFeatureNames.location)) { //can't send disable location request if no consent given return this; } resetLocationValues(); connectionQueue_.getCountlyStore().setLocationDisabled(true); connectionQueue_.sendLocation(); return this; } private synchronized void resetLocationValues() { connectionQueue_.getCountlyStore().setLocationCountryCode(null); connectionQueue_.getCountlyStore().setLocationCity(null); connectionQueue_.getCountlyStore().setLocationGpsCoordinates(null); connectionQueue_.getCountlyStore().setLocationIpAddress(null); } /** * Set location parameters. If they are set before begin_session, they will be sent as part of it. * If they are set after, then they will be sent as a separate request. * If this is called after disabling location, it will enable it. * * @param country_code ISO Country code for the user's country * @param city Name of the user's city * @param gpsCoordinates comma separate lat and lng values. For example, "56.42345,123.45325" * @return Returns link to Countly for call chaining */ public synchronized Countly setLocation(String country_code, String city, String gpsCoordinates, String ipAddress) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Setting location parameters, cc[" + country_code + "] cy[" + city + "] gps[" + gpsCoordinates + "] ip[" + ipAddress + "]"); } if (!isInitialized()) { if (isLoggingEnabled()) { Log.w(Countly.TAG, "The use of this before init is deprecated, use CountlyConfig instead of this"); } } if (!getConsent(CountlyFeatureNames.location)) { return this; } if (country_code != null) { connectionQueue_.getCountlyStore().setLocationCountryCode(country_code); } if (city != null) { connectionQueue_.getCountlyStore().setLocationCity(city); } if (gpsCoordinates != null) { connectionQueue_.getCountlyStore().setLocationGpsCoordinates(gpsCoordinates); } if (ipAddress != null) { connectionQueue_.getCountlyStore().setLocationIpAddress(ipAddress); } if ((country_code == null && city != null) || (city == null && country_code != null)) { if (isLoggingEnabled()) { Log.w(Countly.TAG, "In \"setLocation\" both city and country code need to be set at the same time to be sent"); } } if (country_code != null || city != null || gpsCoordinates != null || ipAddress != null) { connectionQueue_.getCountlyStore().setLocationDisabled(false); } if (isBeginSessionSent || !Countly.sharedInstance().getConsent(Countly.CountlyFeatureNames.sessions)) { //send as a separate request if either begin session was already send and we missed our first opportunity //or if consent for sessions is not given and our only option to send this is as a separate request connectionQueue_.sendLocation(); } else { //will be sent a part of begin session } return this; } /** * Sets custom segments to be reported with crash reports * In custom segments you can provide any string key values to segments crashes by * * @param segments Map&lt;String, String&gt; key segments and their values * @return Returns link to Countly for call chaining * @deprecated set this through CountlyConfig during init */ public synchronized Countly setCustomCrashSegments(Map<String, String> segments) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Calling setCustomCrashSegments"); } if (segments == null) { return this; } Map<String, Object> segm = new HashMap<>(); segm.putAll(segments); setCustomCrashSegmentsInternal(segm); return this; } /** * Sets custom segments to be reported with crash reports * In custom segments you can provide any string key values to segments crashes by * * @param segments Map&lt;String, Object&gt; key segments and their values * todo move to module after 'setCustomCrashSegments' is removed */ synchronized void setCustomCrashSegmentsInternal(Map<String, Object> segments) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "[ModuleCrash] Calling setCustomCrashSegmentsInternal"); } if (!getConsent(Countly.CountlyFeatureNames.crashes)) { return; } if (segments != null) { Utils.removeKeysFromMap(segments, ModuleEvents.reservedSegmentationKeys); Utils.removeUnsupportedDataTypes(segments); CrashDetails.setCustomSegments(segments); } } /** * Add crash breadcrumb like log record to the log that will be send together with crash report * * @param record String a bread crumb for the crash report * @return Returns link to Countly for call chaining * @deprecated use crashes().addCrashBreadcrumb */ public synchronized Countly addCrashBreadcrumb(String record) { return crashes().addCrashBreadcrumb(record); } /** * Log handled exception to report it to server as non fatal crash * * @param exception Exception to log * @return Returns link to Countly for call chaining * @deprecated use crashes().recordHandledException */ public synchronized Countly recordHandledException(Exception exception) { return moduleCrash.recordExceptionInternal(exception, true); } /** * Log handled exception to report it to server as non fatal crash * * @param exception Throwable to log * @return Returns link to Countly for call chaining * @deprecated use crashes().recordHandledException */ public synchronized Countly recordHandledException(Throwable exception) { return moduleCrash.recordExceptionInternal(exception, true); } /** * Log unhandled exception to report it to server as fatal crash * * @param exception Exception to log * @return Returns link to Countly for call chaining * @deprecated use crashes().recordUnhandledException */ public synchronized Countly recordUnhandledException(Exception exception) { return moduleCrash.recordExceptionInternal(exception, false); } /** * Log unhandled exception to report it to server as fatal crash * * @param exception Throwable to log * @return Returns link to Countly for call chaining * @deprecated use crashes().recordUnhandledException */ public synchronized Countly recordUnhandledException(Throwable exception) { return moduleCrash.recordExceptionInternal(exception, false); } /** * Enable crash reporting to send unhandled crash reports to server * * @return Returns link to Countly for call chaining * @deprecated use CountlyConfig during init to set this */ public synchronized Countly enableCrashReporting() { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Enabling unhandled crash reporting"); } //get default handler final Thread.UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Uncaught crash handler triggered"); } if (getConsent(CountlyFeatureNames.crashes)) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); //add other threads if (moduleCrash.recordAllThreads) { moduleCrash.addAllThreadInformationToCrash(pw); } String exceptionString = sw.toString(); //check if it passes the crash filter if (!moduleCrash.crashFilterCheck(exceptionString)) { Countly.sharedInstance().connectionQueue_.sendCrashReport(exceptionString, false, false); } } //if there was another handler before if (oldHandler != null) { //notify it also oldHandler.uncaughtException(t, e); } } }; Thread.setDefaultUncaughtExceptionHandler(handler); return this; } /** * Start timed event with a specified key * * @param key name of the custom event, required, must not be the empty string or null * @return true if no event with this key existed before and event is started, false otherwise * @deprecated use events().startEvent */ public synchronized boolean startEvent(final String key) { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before recordEvent"); } return events().startEvent(key); } /** * End timed event with a specified key * * @param key name of the custom event, required, must not be the empty string or null * @return true if event with this key has been previously started, false otherwise * @deprecated use events().endEvent */ public synchronized boolean endEvent(final String key) { return endEvent(key, null, 1, 0); } public synchronized boolean endEvent(final String key, final Map<String, String> segmentation, final int count, final double sum) { return endEvent(key, segmentation, null, null, count, sum); } public synchronized boolean endEvent(final String key, final Map<String, String> segmentation, final Map<String, Integer> segmentationInt, final Map<String, Double> segmentationDouble, final int count, final double sum) { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before recordEvent"); } Map<String, Object> segmentationGroup = new HashMap<>(); if (segmentation != null) { segmentationGroup.putAll(segmentation); } if (segmentationInt != null) { segmentationGroup.putAll(segmentationInt); } if (segmentationDouble != null) { segmentationGroup.putAll(segmentationDouble); } return events().endEvent(key, segmentationGroup, count, sum); } /** * Disable periodic session time updates. * By default, Countly will send a request to the server each 30 seconds with a small update * containing session duration time. This method allows you to disable such behavior. * Note that event updates will still be sent every 10 events or 30 seconds after event recording. * * @param disable whether or not to disable session time updates * @return Countly instance for easy method chaining * @deprecated set through countlyConfig */ public synchronized Countly setDisableUpdateSessionRequests(final boolean disable) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Disabling periodic session time updates"); } disableUpdateSessionRequests_ = disable; return this; } /** * Sets whether debug logging is turned on or off. Logging is disabled by default. * * @param enableLogging true to enable logging, false to disable logging * @return Countly instance for easy method chaining * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setLoggingEnabled(final boolean enableLogging) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Enabling logging"); } enableLogging_ = enableLogging; return this; } /** * Check if logging has been enabled internally in the SDK * * @return true means "yes" */ public synchronized boolean isLoggingEnabled() { return enableLogging_; } /** * @param salt * @return * @deprecated use CountlyConfig (setParameterTamperingProtectionSalt) during init to set this */ public synchronized Countly enableParameterTamperingProtection(String salt) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Enabling tamper protection"); } enableParameterTamperingProtectionInternal(salt); return this; } /** * Use by both the external call and config call * * @param salt */ private synchronized void enableParameterTamperingProtectionInternal(String salt) { ConnectionProcessor.salt = salt; } /** * Returns if the countly sdk onStart function has been called at least once * * @return true - yes, it has, false - no it has not */ public synchronized boolean hasBeenCalledOnStart() { return calledAtLeastOnceOnStart; } /** * @param size * @return * @deprecated use countly config to set this */ public synchronized Countly setEventQueueSizeToSend(int size) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Setting event queue size: [" + size + "]"); } if (size < 1) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "[setEventQueueSizeToSend] queue size can't be less than zero"); } size = 1; } EVENT_QUEUE_SIZE_THRESHOLD = size; return this; } public static void onCreate(Activity activity) { Intent launchIntent = activity.getPackageManager().getLaunchIntentForPackage(activity.getPackageName()); if (sharedInstance().isLoggingEnabled()) { String mainClassName = "[VALUE NULL]"; if (launchIntent != null && launchIntent.getComponent() != null) { mainClassName = launchIntent.getComponent().getClassName(); } Log.d(Countly.TAG, "Activity created: " + activity.getClass().getName() + " ( main is " + mainClassName + ")"); } Intent intent = activity.getIntent(); if (intent != null) { Uri data = intent.getData(); if (data != null) { if (sharedInstance().isLoggingEnabled()) { Log.d(Countly.TAG, "Data in activity created intent: " + data + " (appLaunchDeepLink " + sharedInstance().appLaunchDeepLink + ") "); } if (sharedInstance().appLaunchDeepLink) { DeviceInfo.deepLink = data.toString(); } } } } /** * Send events if any of them are stored */ protected void sendEventsIfExist() { if (eventQueue_.size() > 0) { connectionQueue_.recordEvents(eventQueue_.events()); } } /** * Submits all of the locally queued events to the server if there are more than 10 of them. */ protected void sendEventsIfNeeded() { if (eventQueue_.size() >= EVENT_QUEUE_SIZE_THRESHOLD) { connectionQueue_.recordEvents(eventQueue_.events()); } } /** * Immediately sends all stored events */ protected void sendEventsForced() { connectionQueue_.recordEvents(eventQueue_.events()); } /** * Called every 60 seconds to send a session heartbeat to the server. Does nothing if there * is not an active application session. */ synchronized void onTimer() { if (isLoggingEnabled()) { Log.v(Countly.TAG, "[onTimer] Calling heartbeat, Activity count:[" + activityCount_ + "]"); } if (isInitialized()) { final boolean hasActiveSession = activityCount_ > 0; if (hasActiveSession) { if (!moduleSessions.manualSessionControlEnabled) { moduleSessions.updateSessionInternal(); } if (eventQueue_.size() > 0) { connectionQueue_.recordEvents(eventQueue_.events()); } } connectionQueue_.tick(); } } public static Countly enablePublicKeyPinning(List<String> certificates) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.i(Countly.TAG, "Enabling public key pinning"); } publicKeyPinCertificates = certificates; return Countly.sharedInstance(); } public static Countly enableCertificatePinning(List<String> certificates) { if (Countly.sharedInstance().isLoggingEnabled()) { Log.i(Countly.TAG, "Enabling certificate pinning"); } certificatePinCertificates = certificates; return Countly.sharedInstance(); } /** * Shows the star rating dialog * * @param activity the activity that will own the dialog * @param callback callback for the star rating dialog "rate" and "dismiss" events * @deprecated call this trough 'Countly.sharedInstance().remoteConfig()' */ public void showStarRating(Activity activity, final CountlyStarRating.RatingCallback callback) { if (!isInitialized()) { if (isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return; } } if (callback == null) { ratings().showStarRating(activity, null); } else { ratings().showStarRating(activity, new StarRatingCallback() { @Override public void onRate(int rating) { callback.onRate(rating); } @Override public void onDismiss() { callback.onDismiss(); } }); } } /** * Set's the text's for the different fields in the star rating dialog. Set value null if for some field you want to keep the old value * * @param starRatingTextTitle dialog's title text * @param starRatingTextMessage dialog's message text * @param starRatingTextDismiss dialog's dismiss buttons text * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setStarRatingDialogTexts(String starRatingTextTitle, String starRatingTextMessage, String starRatingTextDismiss) { if (!isInitialized()) { if (isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return this; } } if (isLoggingEnabled()) { Log.d(Countly.TAG, "Setting star rating texts"); } moduleRatings.setStarRatingInitConfig(connectionQueue_.getCountlyStore(), -1, starRatingTextTitle, starRatingTextMessage, starRatingTextDismiss); return this; } /** * Set if the star rating should be shown automatically * * @param IsShownAutomatically set it true if you want to show the app star rating dialog automatically for each new version after the specified session amount * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setIfStarRatingShownAutomatically(boolean IsShownAutomatically) { if (!isInitialized()) { if (isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return this; } } if (isLoggingEnabled()) { Log.d(Countly.TAG, "Setting to show star rating automatically: [" + IsShownAutomatically + "]"); } moduleRatings.setShowDialogAutomatically(connectionQueue_.getCountlyStore(), IsShownAutomatically); return this; } /** * Set if the star rating is shown only once per app lifetime * * @param disableAsking set true if you want to disable asking the app rating for each new app version (show it only once per apps lifetime) * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setStarRatingDisableAskingForEachAppVersion(boolean disableAsking) { if (!isInitialized()) { if (isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return this; } } if (isLoggingEnabled()) { Log.d(Countly.TAG, "Setting to disable showing of star rating for each app version:[" + disableAsking + "]"); } moduleRatings.setStarRatingDisableAskingForEachAppVersion(connectionQueue_.getCountlyStore(), disableAsking); return this; } /** * Set after how many sessions the automatic star rating will be shown for each app version * * @param limit app session amount for the limit * @return Returns link to Countly for call chaining * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setAutomaticStarRatingSessionLimit(int limit) { if (!isInitialized()) { if (isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return this; } } if (isLoggingEnabled()) { Log.d(Countly.TAG, "Setting automatic star rating session limit: [" + limit + "]"); } moduleRatings.setStarRatingInitConfig(connectionQueue_.getCountlyStore(), limit, null, null, null); return this; } /** * Returns the session limit set for automatic star rating * * @deprecated use 'Countly.sharedInstance().ratings().getAutomaticStarRatingSessionLimit()' */ public int getAutomaticStarRatingSessionLimit() { if (!isInitialized()) { if (isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return -1; } } int sessionLimit = ModuleRatings.getAutomaticStarRatingSessionLimitInternal(connectionQueue_.getCountlyStore()); if (isLoggingEnabled()) { Log.d(Countly.TAG, "Getting automatic star rating session limit: [" + sessionLimit + "]"); } return sessionLimit; } /** * Returns how many sessions has star rating counted internally for the current apps version * * @deprecated use 'Countly.sharedInstance().ratings().getCurrentVersionsSessionCount()' */ public int getStarRatingsCurrentVersionsSessionCount() { if (!isInitialized()) { if (isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return -1; } } return ratings().getCurrentVersionsSessionCount(); } /** * Set the automatic star rating session count back to 0 * * @deprecated use 'Countly.sharedInstance().ratings().getCurrentVersionsSessionCount()' to get achieve this */ public void clearAutomaticStarRatingSessionCount() { if (!isInitialized()) { if (isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return; } } ratings().clearAutomaticStarRatingSessionCount(); } /** * Set if the star rating dialog is cancellable * * @param isCancellable set this true if it should be cancellable * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setIfStarRatingDialogIsCancellable(boolean isCancellable) { if (!isInitialized()) { if (isLoggingEnabled()) { Log.e(Countly.TAG, "Can't call this function before init has been called"); return this; } } if (isLoggingEnabled()) { Log.d(Countly.TAG, "Setting if star rating is cancellable: [" + isCancellable + "]"); } moduleRatings.setIfRatingDialogIsCancellableInternal(connectionQueue_.getCountlyStore(), isCancellable); return this; } /** * Set the override for forcing to use HTTP POST for all connections to the server * * @param isItForced the flag for the new status, set "true" if you want it to be forced * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setHttpPostForced(boolean isItForced) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Setting if HTTP POST is forced: [" + isItForced + "]"); } isHttpPostForced = isItForced; return this; } /** * Get the status of the override for HTTP POST * * @return return "true" if HTTP POST ir forced */ public boolean isHttpPostForced() { return isHttpPostForced; } private void checkIfDeviceIsAppCrawler() { String deviceName = DeviceInfo.getDevice(); for (int a = 0; a < appCrawlerNames.size(); a++) { if (deviceName.equals(appCrawlerNames.get(a))) { deviceIsAppCrawler = true; return; } } } /** * Set if Countly SDK should ignore app crawlers * * @param shouldIgnore if crawlers should be ignored * @deprecated use CountlyConfig to set this */ public synchronized Countly setShouldIgnoreCrawlers(boolean shouldIgnore) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Setting if should ignore app crawlers: [" + shouldIgnore + "]"); } shouldIgnoreCrawlers = shouldIgnore; return this; } /** * Add app crawler device name to the list of names that should be ignored * * @param crawlerName the name to be ignored * @deprecated use CountlyConfig to set this */ public void addAppCrawlerName(String crawlerName) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Adding app crawler name: [" + crawlerName + "]"); } if (crawlerName != null && !crawlerName.isEmpty()) { appCrawlerNames.add(crawlerName); } } /** * Return if current device is detected as a app crawler * * @return returns if devices is detected as a app crawler */ public boolean isDeviceAppCrawler() { return deviceIsAppCrawler; } /** * Return if the countly sdk should ignore app crawlers */ public boolean ifShouldIgnoreCrawlers() { if (!isInitialized()) { throw new IllegalStateException("init must be called before ifShouldIgnoreCrawlers"); } return shouldIgnoreCrawlers; } /** * Returns the device id used by countly for this device * * @return device ID */ public synchronized String getDeviceID() { if (!isInitialized()) { throw new IllegalStateException("init must be called before getDeviceID"); } return connectionQueue_.getDeviceId().getId(); } /** * Returns the type of the device ID used by countly for this device. * * @return device ID type */ public synchronized DeviceId.Type getDeviceIDType() { if (!isInitialized()) { throw new IllegalStateException("init must be called before getDeviceID"); } return connectionQueue_.getDeviceId().getType(); } /** * @param shouldAddMetadata * @return * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setPushIntentAddMetadata(boolean shouldAddMetadata) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Setting if adding metadata to push intents: [" + shouldAddMetadata + "]"); } addMetadataToPushIntents = shouldAddMetadata; return this; } /** * Set if automatic activity tracking should use short names * * @param shouldUseShortName set true if you want short names * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setAutoTrackingUseShortName(boolean shouldUseShortName) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Setting if automatic view tracking should use short names: [" + shouldUseShortName + "]"); } automaticTrackingShouldUseShortName = shouldUseShortName; return this; } /** * Set if attribution should be enabled * * @param shouldEnableAttribution set true if you want to enable it, set false if you want to disable it * @deprecated use CountlyConfig to set this */ public synchronized Countly setEnableAttribution(boolean shouldEnableAttribution) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Setting if attribution should be enabled"); } isAttributionEnabled = shouldEnableAttribution; return this; } /** * @param shouldRequireConsent * @return * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setRequiresConsent(boolean shouldRequireConsent) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Setting if consent should be required, [" + shouldRequireConsent + "]"); } requiresConsent = shouldRequireConsent; return this; } /** * Initiate all things related to consent */ private void initConsent() { //groupedFeatures.put("activity", new String[]{CountlyFeatureNames.sessions, CountlyFeatureNames.events, CountlyFeatureNames.views}); //groupedFeatures.put("interaction", new String[]{CountlyFeatureNames.sessions, CountlyFeatureNames.events, CountlyFeatureNames.views}); } /** * Special things needed to be done during setting push consent * * @param consentValue The value of push consent */ void doPushConsentSpecialAction(boolean consentValue) { if (isLoggingEnabled()) { Log.d(TAG, "Doing push consent special action: [" + consentValue + "]"); } connectionQueue_.getCountlyStore().setConsentPush(consentValue); } /** * Actions needed to be done for the consent related location erasure */ void doLocationConsentSpecialErasure() { resetLocationValues(); connectionQueue_.sendLocation(); } /** * Check if the given name is a valid feature name * * @param name the name of the feature to be tested if it is valid * @return returns true if value is contained in feature name array */ private boolean isValidFeatureName(String name) { for (String fName : validFeatureNames) { if (fName.equals(name)) { return true; } } return false; } /** * Prepare features into json format * * @param features the names of features that are about to be changed * @param consentValue the value for the new consent * @return provided consent changes in json format */ private String formatConsentChanges(String[] features, boolean consentValue) { StringBuilder preparedConsent = new StringBuilder(); preparedConsent.append("{"); for (int a = 0; a < features.length; a++) { if (a != 0) { preparedConsent.append(","); } preparedConsent.append('"'); preparedConsent.append(features[a]); preparedConsent.append('"'); preparedConsent.append(':'); preparedConsent.append(consentValue); } preparedConsent.append("}"); return preparedConsent.toString(); } /** * Group multiple features into a feature group * * @param groupName name of the consent group * @param features array of feature to be added to the consent group * @return Returns link to Countly for call chaining * @deprecated use 'Countly.sharedInstance().consent().createFeatureGroup' */ public synchronized Countly createFeatureGroup(String groupName, String[] features) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Creating a feature group with the name: [" + groupName + "]"); } if (isLoggingEnabled() && !isInitialized()) { Log.w(Countly.TAG, "Calling this before initialising the SDK is deprecated!"); } groupedFeatures.put(groupName, features); return this; } /** * Set the consent of a feature group * * @param groupName name of the consent group * @param isConsentGiven the value that should be set for this consent group * @return Returns link to Countly for call chaining * @deprecated use 'Countly.sharedInstance().consent().setConsent' */ public synchronized Countly setConsentFeatureGroup(String groupName, boolean isConsentGiven) { if (isLoggingEnabled()) { Log.v(Countly.TAG, "Setting consent for feature group: [" + groupName + "] with value: [" + isConsentGiven + "]"); } if (isLoggingEnabled() && !isInitialized()) { Log.w(Countly.TAG, "Calling this before initialising the SDK is deprecated!"); } if (!groupedFeatures.containsKey(groupName)) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Trying to set consent for a unknown feature group: [" + groupName + "]"); } return this; } setConsent(groupedFeatures.get(groupName), isConsentGiven); return this; } /** * Set the consent of a feature * * @param featureNames feature names for which consent should be changed * @param isConsentGiven the consent value that should be set * @return Returns link to Countly for call chaining * @deprecated use 'Countly.sharedInstance().consent().setConsent' or set consent through CountlyConfig */ public synchronized Countly setConsent(String[] featureNames, boolean isConsentGiven) { if (isLoggingEnabled() && !isInitialized()) { Log.w(Countly.TAG, "Calling this before initialising the SDK is deprecated!"); } final boolean isInit = isInitialized();//is the SDK initialized if (!requiresConsent) { //if consent is not required, ignore all calls to it return this; } if(featureNames == null) { if (isLoggingEnabled()) { Log.w(Countly.TAG, "Calling setConsent with null featureNames!"); } return this; } boolean previousSessionsConsent = false; if (featureConsentValues.containsKey(CountlyFeatureNames.sessions)) { previousSessionsConsent = featureConsentValues.get(CountlyFeatureNames.sessions); } boolean previousLocationConsent = false; if (featureConsentValues.containsKey(CountlyFeatureNames.location)) { previousLocationConsent = featureConsentValues.get(CountlyFeatureNames.location); } boolean currentSessionConsent = previousSessionsConsent; for (String featureName : featureNames) { if (Countly.sharedInstance() != null && isLoggingEnabled()) { Log.d(Countly.TAG, "Setting consent for feature: [" + featureName + "] with value: [" + isConsentGiven + "]"); } if (!isValidFeatureName(featureName)) { Log.d(Countly.TAG, "Given feature: [" + featureName + "] is not a valid name, ignoring it"); continue; } featureConsentValues.put(featureName, isConsentGiven); //special actions for each feature switch (featureName) { case CountlyFeatureNames.push: if (isInit) { //if the SDK is already initialized, do the special action now doPushConsentSpecialAction(isConsentGiven); } else { //do the special action later delayedPushConsent = isConsentGiven; } break; case CountlyFeatureNames.sessions: currentSessionConsent = isConsentGiven; break; case CountlyFeatureNames.location: if (previousLocationConsent && !isConsentGiven) { //if consent is about to be removed if (isInit) { doLocationConsentSpecialErasure(); } else { delayedLocationErasure = true; } } break; } } String formattedChanges = formatConsentChanges(featureNames, isConsentGiven); if (isInit && (collectedConsentChanges.size() == 0)) { //if countly is initialized and collected changes are already sent, send consent now connectionQueue_.sendConsentChanges(formattedChanges); context_.sendBroadcast(new Intent(CONSENT_BROADCAST)); //if consent has changed and it was set to true if ((previousSessionsConsent != currentSessionConsent) && currentSessionConsent) { //if consent was given, we need to begin the session if (isBeginSessionSent) { //if the first timing for a beginSession call was missed, send it again if (!moduleSessions.manualSessionControlEnabled) { moduleSessions.beginSessionInternal(); } } } } else { // if countly is not initialized, collect and send it after it is collectedConsentChanges.add(formattedChanges); } return this; } /** * Give the consent to a feature * * @param featureNames the names of features for which consent should be given * @return Returns link to Countly for call chaining * @deprecated use 'Countly.sharedInstance().consent().giveConsent(featureNames)' or set consent through CountlyConfig */ public synchronized Countly giveConsent(String[] featureNames) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Giving consent for features named: [" + Arrays.toString(featureNames) + "]"); } if (isLoggingEnabled() && !isInitialized()) { Log.w(Countly.TAG, "Calling this before initialising the SDK is deprecated!"); } setConsent(featureNames, true); return this; } /** * Remove the consent of a feature * * @param featureNames the names of features for which consent should be removed * @return Returns link to Countly for call chaining * @deprecated use 'Countly.sharedInstance().consent().removeConsent(featureNames)' */ public synchronized Countly removeConsent(String[] featureNames) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Removing consent for features named: [" + Arrays.toString(featureNames) + "]"); } if (isLoggingEnabled() && !isInitialized()) { Log.w(Countly.TAG, "Calling this before initialising the SDK is deprecated!"); } setConsent(featureNames, false); return this; } /** * Remove consent for all features * * @return Returns link to Countly for call chaining * @deprecated use 'Countly.sharedInstance().consent().removeConsentAll()' */ public synchronized Countly removeConsentAll() { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Removing consent for all features"); } if (isLoggingEnabled() && !isInitialized()) { Log.w(Countly.TAG, "Calling this before initialising the SDK is deprecated!"); } removeConsent(validFeatureNames); return this; } /** * Get the current consent state of a feature * * @param featureName the name of a feature for which consent should be checked * @return the consent value * @deprecated use 'Countly.sharedInstance().consent().getConsent(featureName)' */ public synchronized boolean getConsent(String featureName) { if (!requiresConsent) { //return true silently return true; } Boolean returnValue = featureConsentValues.get(featureName); if (returnValue == null) { if (featureName.equals(CountlyFeatureNames.push)) { //if the feature is 'push", set it with the value from preferences boolean storedConsent = connectionQueue_.getCountlyStore().getConsentPush(); if (isLoggingEnabled()) { Log.d(Countly.TAG, "Push consent has not been set this session. Setting the value found stored in preferences:[" + storedConsent + "]"); } featureConsentValues.put(featureName, storedConsent); returnValue = storedConsent; } else { returnValue = false; } } if (isLoggingEnabled()) { Log.v(Countly.TAG, "Returning consent for feature named: [" + featureName + "] [" + returnValue + "]"); } return returnValue; } /** * Print the consent values of all features * * @return Returns link to Countly for call chaining * @deprecated use 'Countly.sharedInstance().consent().checkAllConsent()' */ public synchronized Countly checkAllConsent() { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Checking and printing consent for All features"); } if (isLoggingEnabled()) { Log.d(Countly.TAG, "Is consent required? [" + requiresConsent + "]"); } //make sure push consent has been added to the feature map getConsent(CountlyFeatureNames.push); StringBuilder sb = new StringBuilder(); for (String key : featureConsentValues.keySet()) { sb.append("Feature named [").append(key).append("], consent value: [").append(featureConsentValues.get(key)).append("]\n"); } if (isLoggingEnabled()) { Log.d(Countly.TAG, sb.toString()); } return this; } /** * Returns true if any consent has been given * * @return true - any consent has been given, false - no consent has been given * todo move to module */ protected boolean anyConsentGiven() { if (!requiresConsent) { //no consent required - all consent given return true; } for (String key : featureConsentValues.keySet()) { if (featureConsentValues.get(key)) { return true; } } return false; } /** * Show the rating dialog to the user * * @param widgetId ID that identifies this dialog * @return * @deprecated use 'Countly.sharedInstance().ratings().showFeedbackPopup' */ public synchronized Countly showFeedbackPopup(final String widgetId, final String closeButtonText, final Activity activity, final CountlyStarRating.FeedbackRatingCallback feedbackCallback) { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before showFeedbackPopup"); } if (feedbackCallback == null) { ratings().showFeedbackPopup(widgetId, closeButtonText, activity, null); } else { ratings().showFeedbackPopup(widgetId, closeButtonText, activity, new FeedbackRatingCallback() { @Override public void callback(String error) { feedbackCallback.callback(error); } }); } return this; } /** * If enable, will automatically download newest remote config_ values on init. * * @param enabled set true for enabling it * @param feedbackCallback callback called after the update was done * @return * @deprecated use CountlyConfig during init to set this */ public synchronized Countly setRemoteConfigAutomaticDownload(boolean enabled, final RemoteConfig.RemoteConfigCallback feedbackCallback) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Setting if remote config_ Automatic download will be enabled, " + enabled); } remoteConfigAutomaticUpdateEnabled = enabled; if (feedbackCallback != null) { remoteConfigInitCallback = new RemoteConfigCallback() { @Override public void callback(String error) { feedbackCallback.callback(error); } }; } return this; } /** * Manually update remote config_ values * * @param providedCallback * @deprecated use 'Countly.sharedInstance().remoteConfig().update(callback)' */ public void remoteConfigUpdate(final RemoteConfig.RemoteConfigCallback providedCallback) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Manually calling to updateRemoteConfig"); } if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before remoteConfigUpdate"); } if (providedCallback == null) { remoteConfig().update(null); } else { remoteConfig().update(new RemoteConfigCallback() { @Override public void callback(String error) { providedCallback.callback(error); } }); } } /** * Manual remote config_ update call. Will only update the keys provided. * * @param keysToInclude * @param providedCallback * @deprecated use 'Countly.sharedInstance().remoteConfig().updateForKeysOnly(keys, callback)' */ public void updateRemoteConfigForKeysOnly(String[] keysToInclude, final RemoteConfig.RemoteConfigCallback providedCallback) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Manually calling to updateRemoteConfig with include keys"); } if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before updateRemoteConfigForKeysOnly"); } if (providedCallback == null) { remoteConfig().updateForKeysOnly(keysToInclude, null); } else { remoteConfig().updateForKeysOnly(keysToInclude, new RemoteConfigCallback() { @Override public void callback(String error) { providedCallback.callback(error); } }); } } /** * Manual remote config_ update call. Will update all keys except the ones provided * * @param keysToExclude * @param providedCallback * @deprecated use 'Countly.sharedInstance().remoteConfig().updateExceptKeys(keys, callback)' */ public void updateRemoteConfigExceptKeys(String[] keysToExclude, final RemoteConfig.RemoteConfigCallback providedCallback) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Manually calling to updateRemoteConfig with exclude keys"); } if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before updateRemoteConfigExceptKeys"); } if (providedCallback == null) { remoteConfig().updateExceptKeys(keysToExclude, null); } else { remoteConfig().updateExceptKeys(keysToExclude, new RemoteConfigCallback() { @Override public void callback(String error) { providedCallback.callback(error); } }); } } /** * Get the stored value for the provided remote config_ key * * @param key * @return * @deprecated use 'Countly.sharedInstance().remoteConfig().getValueForKey(key)' */ public Object getRemoteConfigValueForKey(String key) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Calling remoteConfigValueForKey"); } if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before remoteConfigValueForKey"); } return remoteConfig().getValueForKey(key); } /** * Clear all stored remote config_ values * * @deprecated use 'Countly.sharedInstance().remoteConfig().clearStoredValues();' */ public void remoteConfigClearValues() { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Calling remoteConfigClearValues"); } if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before remoteConfigClearValues"); } remoteConfig().clearStoredValues(); } /** * Allows you to add custom header key/value pairs to each request * * @deprecated use CountlyConfig during init to set this */ public void addCustomNetworkRequestHeaders(Map<String, String> headerValues) { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Calling addCustomNetworkRequestHeaders"); } requestHeaderCustomValues = headerValues; if (connectionQueue_ != null) { connectionQueue_.setRequestHeaderCustomValues(requestHeaderCustomValues); } } /** * Deletes all stored requests to server. * This includes events, crashes, views, sessions, etc * Call only if you don't need that information */ public void flushRequestQueues() { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Calling flushRequestQueues"); } if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before flushRequestQueues"); } CountlyStore store = connectionQueue_.getCountlyStore(); int count = 0; while (true) { final String[] storedEvents = store.connections(); if (storedEvents == null || storedEvents.length == 0) { // currently no data to send, we are done for now break; } //remove stored data store.removeConnection(storedEvents[0]); count++; } if (isLoggingEnabled()) { Log.d(Countly.TAG, "flushRequestQueues removed [" + count + "] requests"); } } /** * Countly will attempt to fulfill all stored requests on demand */ public void doStoredRequests() { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Calling doStoredRequests"); } if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before doStoredRequests"); } connectionQueue_.tick(); } public Countly enableTemporaryIdMode() { if (isLoggingEnabled()) { Log.d(Countly.TAG, "Calling enableTemporaryIdMode"); } if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before enableTemporaryIdMode"); } changeDeviceId(DeviceId.temporaryCountlyDeviceId); return this; } public ModuleCrash.Crashes crashes() { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before accessing crashes"); } return moduleCrash.crashesInterface; } public ModuleEvents.Events events() { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before accessing events"); } return moduleEvents.eventsInterface; } public ModuleViews.Views views() { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before accessing views"); } return moduleViews.viewsInterface; } public ModuleRatings.Ratings ratings() { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before accessing ratings"); } return moduleRatings.ratingsInterface; } public ModuleSessions.Sessions sessions() { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before accessing sessions"); } return moduleSessions.sessionInterface; } public ModuleRemoteConfig.RemoteConfig remoteConfig() { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before accessing remote config"); } return moduleRemoteConfig.remoteConfigInterface; } public ModuleAPM.Apm apm() { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before accessing apm"); } return moduleAPM.apmInterface; } public ModuleConsent.Consent consent() { if (!isInitialized()) { throw new IllegalStateException("Countly.sharedInstance().init must be called before accessing consent"); } return moduleConsent.consentInterface; } public static void applicationOnCreate() { applicationStart = UtilsTime.currentTimestampMs(); } // for unit testing ConnectionQueue getConnectionQueue() { return connectionQueue_; } void setConnectionQueue(final ConnectionQueue connectionQueue) { connectionQueue_ = connectionQueue; } ExecutorService getTimerService() { return timerService_; } EventQueue getEventQueue() { return eventQueue_; } void setEventQueue(final EventQueue eventQueue) { eventQueue_ = eventQueue; } long getPrevSessionDurationStartTime() { return moduleSessions.prevSessionDurationStartTime_; } void setPrevSessionDurationStartTime(final long prevSessionDurationStartTime) { moduleSessions.prevSessionDurationStartTime_ = prevSessionDurationStartTime; } int getActivityCount() { return activityCount_; } synchronized boolean getDisableUpdateSessionRequests() { return disableUpdateSessionRequests_; } }
package nl.hsac.fitnesse.fixture.slim.web; import nl.hsac.fitnesse.fixture.slim.StopTestException; import nl.hsac.fitnesse.fixture.util.NgClientSideScripts; import nl.hsac.fitnesse.slim.interaction.ReflectionHelper; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; /** * Browser Test targeted to test AngularJs apps. */ public class NgBrowserTest extends BrowserTest { private final static Set<String> METHODS_NO_WAIT; private String angularRoot = null; static { METHODS_NO_WAIT = ReflectionHelper.validateMethodNames( NgBrowserTest.class, "open", "takeScreenshot", "openInNewTab", "ensureActiveTabIsNotClosed", "currentTabIndex", "tabCount", "ensureOnlyOneTab", "closeTab", "setAngularRoot", "switchToNextTab", "switchToPreviousTab", "waitForAngularRequestsToFinish", "secondsBeforeTimeout", "waitForPage", "waitForTagWithText", "waitForClassWithText", "waitForClass", "waitSeconds", "waitMilliseconds", "waitMilliSecondAfterScroll", "screenshotBaseDirectory", "screenshotShowHeight", "setBrowserWidth", "setBrowserHeight", "setBrowserSizeToBy", "setGlobalValueTo", "globalValue", "setAngularRoot", "getAngularRoot"); } @Override protected void beforeInvoke(Method method, Object[] arguments) { if (requiresWaitForAngular(method)) { waitForAngularRequestsToFinish(); } super.beforeInvoke(method, arguments); } /** * Determines whether method requires waiting for all Angular requests to finish * before it is invoked. * @param method method to be invoked. * @return true, if waiting for Angular is required, false otherwise. */ protected boolean requiresWaitForAngular(Method method) { String methodName = method.getName(); return !METHODS_NO_WAIT.contains(methodName); } @Override public boolean open(String address) { boolean result = super.open(address); if (result) { waitForAngularRequestsToFinish(); } return result; } public void waitForAngularRequestsToFinish() { String root = getAngularRoot(); if (root == null) { root = "body"; } Object result = waitForJavascriptCallback(NgClientSideScripts.WaitForAngular, root); if (result != null) { String msg = getSlimFixtureExceptionMessage("angular", result.toString(), null); throw new StopTestException(false, msg); } } @Override public String valueFor(String place) { String result; WebElement angularModelBinding = getAngularElement(place); if (angularModelBinding == null) { result = super.valueFor(place); } else { result = valueFor(angularModelBinding); } return result; } @Override public boolean selectFor(String value, String place) { boolean result; WebElement angularModelSelect = findSelect(place); if (angularModelSelect == null) { result = super.selectFor(value, place); } else { result = clickSelectOption(angularModelSelect, value); } return result; } @Override public boolean enterAs(String value, String place) { boolean result; WebElement angularModelInput = getAngularElementToEnterIn(place); if (angularModelInput == null) { result = super.enterAs(value, place); } else { angularModelInput.clear(); sendValue(angularModelInput, value); result = true; } return result; } public int numberOf(String repeater) { waitForAngularRequestsToFinish(); return findRepeaterRows(repeater).size(); } public String valueOfColumnNumberInRowNumberOf(int columnIndex, int rowIndex, String repeater) { return getTextInRepeaterColumn(Integer.toString(columnIndex), rowIndex, repeater); } public String valueOfInRowNumberOf(String columnName, int rowIndex, String repeater) { String columnIndex = getXPathForColumnIndex(columnName); return getTextInRepeaterColumn(columnIndex, rowIndex, repeater); } public String valueOfInRowWhereIsOf(String requestedColumnName, String selectOnColumn, String selectOnValue, String repeater) { String result = null; String compareIndex = getXPathForColumnIndex(selectOnColumn); List<WebElement> rows = findRepeaterRows(repeater); for (WebElement row : rows) { String compareValue = getColumnText(row, compareIndex); if ((selectOnValue == null && compareValue == null) || selectOnValue != null && selectOnValue.equals(compareValue)) { String requestedIndex = getXPathForColumnIndex(requestedColumnName); result = getColumnText(row, requestedIndex); break; } } return result; } protected String getTextInRepeaterColumn(String columnIndexXPath, int rowIndex, String repeater) { String result = null; List<WebElement> rows = findRepeaterRows(repeater); if (rows.size() >= rowIndex) { WebElement row = rows.get(rowIndex - 1); result = getColumnText(row, columnIndexXPath); } return result; } private String getColumnText(WebElement row, String columnIndexXPath) { By xPath = getSeleniumHelper().byXpath("td[%s]", columnIndexXPath); WebElement cell = row.findElement(xPath); return getElementText(cell); } protected WebElement getAngularElementToEnterIn(String place) { return findElement(place); } protected WebElement getAngularElement(String place) { WebElement element = findBinding(place); if (element == null) { element = findElement(place); } return element; } protected WebElement findBinding(String place) { return findNgElementByJavascript(NgClientSideScripts.FindBindings, place, true, null); } protected WebElement findSelect(String place) { return findNgElementByJavascript(NgClientSideScripts.FindSelects, place); } protected WebElement findElement(String place) { return findNgElementByJavascript(NgClientSideScripts.FindElements, place, null); } protected List<WebElement> findRepeaterRows(String repeater) { return findNgElementsByJavascript(NgClientSideScripts.FindAllRepeaterRows, repeater, true); } protected List<WebElement> findNgElementsByJavascript(String script, Object... parameters) { Object[] arguments = getFindArguments(parameters); return findAllByJavascript(script, arguments); } protected WebElement findNgElementByJavascript(String script, Object... parameters) { Object[] arguments = getFindArguments(parameters); return findByJavascript(script, arguments); } private Object[] getFindArguments(Object[] parameters) { List<Object> params = new ArrayList<Object>(parameters.length + 1); params.addAll(Arrays.asList(parameters)); params.add(getAngularRoot()); return params.toArray(); } public String getAngularRoot() { return angularRoot; } public void setAngularRoot(String anAngularRoot) { angularRoot = anAngularRoot; } }
package nl.jqno.equalsverifier.internal.reflection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; public final class Util { private Util() { // Do not instantiate } /** * Helper method to resolve a Class of a given name. * * @param className The fully qualified name of the class to resolve. * @return The corresponding class if it exists, null otherwise. */ public static Class<?> classForName(String className) { try { return Class.forName(className); } catch (ClassNotFoundException | VerifyError e) { // Catching VerifyError fixes issue #147. I don't know how to unit test it. return null; } } /** * Helper method to create an array of Classes. * * @param classes The classes to construct an array out of. * @return An array with the given classes. */ public static Class<?>[] classes(Class<?>... classes) { return classes; } /** * Helper method to create an array of Objects. * * @param objects The objects to construct an array out of. * @return An array with the given objects. */ public static Object[] objects(Object... objects) { return objects; } /** * Helper method to create simple LRU cache implementation. * * @param maxSize maximum size of map * @return simple thread-safe map with maximum-size eviction by LRU algorithm */ public static <K, V> Map<K, V> newLruCache(final int maxSize) { LinkedHashMap<K, V> map = new LinkedHashMap<K, V>(16, 0.75f, true) { @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > maxSize; } }; return Collections.synchronizedMap(map); } }
package org.adridadou.ethereum.propeller; import org.adridadou.ethereum.propeller.converters.future.FutureConverter; import org.adridadou.ethereum.propeller.event.EthereumEventHandler; import org.adridadou.ethereum.propeller.exception.EthereumApiException; import org.adridadou.ethereum.propeller.solidity.*; import org.adridadou.ethereum.propeller.solidity.abi.AbiParam; import org.adridadou.ethereum.propeller.solidity.EvmVersion; import org.adridadou.ethereum.propeller.solidity.converters.SolidityTypeGroup; import org.adridadou.ethereum.propeller.solidity.converters.decoders.list.CollectionDecoder; import org.adridadou.ethereum.propeller.solidity.converters.decoders.SolidityTypeDecoder; import org.adridadou.ethereum.propeller.solidity.converters.encoders.list.CollectionEncoder; import org.adridadou.ethereum.propeller.solidity.converters.encoders.SolidityTypeEncoder; import org.adridadou.ethereum.propeller.swarm.SwarmHash; import org.adridadou.ethereum.propeller.swarm.SwarmService; import org.adridadou.ethereum.propeller.values.*; import io.reactivex.Observable; import org.web3j.abi.datatypes.Event; import org.web3j.protocol.core.DefaultBlockParameter; import org.web3j.protocol.core.DefaultBlockParameterName; import org.web3j.protocol.core.methods.response.Log; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import static java.lang.reflect.Proxy.newProxyInstance; public class EthereumFacade { public static final Charset CHARSET = StandardCharsets.UTF_8; private final EthereumContractInvocationHandler handler; private final EthereumProxy ethereumProxy; private final SwarmService swarmService; private final SolidityCompiler solidityCompiler; EthereumFacade(EthereumProxy ethereumProxy, SwarmService swarmService, SolidityCompiler solidityCompiler) { this.swarmService = swarmService; this.solidityCompiler = solidityCompiler; this.handler = new EthereumContractInvocationHandler(ethereumProxy); this.ethereumProxy = ethereumProxy; } /** * This method defines a new type as void. This means that for this type, no decoder will be used and null will be returned. * This is used usually by wrapper projects to define language specific void types, for example Unit in Scala * * @param cls the class that needs to be seen as Void * @return The EthereumFacade object itself */ public EthereumFacade addVoidType(Class<?> cls) { ethereumProxy.addVoidClass(cls); return this; } /** * This method adds a converter from CompletableFuture to another future type. This is useful if you wnat to integrate a library with its own * Future type or for a wrapper project that wants to convert CompletableFuture to another Future type. for example scala Future * @param futureConverter the future converter to add * @return The EthereumFacade object itself */ public EthereumFacade addFutureConverter(FutureConverter futureConverter) { handler.addFutureConverter(futureConverter); return this; } /** * Creates a proxy object representing the interface with the smart contract. * This method reads the swarm url from the deployed code and then tries to download the smart contract metadata from Swarm. * It then reads the ABI from the smart contract's metadata to create the proxy. * @param address the address of the smart contract * @param account the account to use to send transactions * @param contractInterface The interface representing the smart contract * @param <T> the proxy object type * @return The contract proxy object */ public <T> T createContractProxy(EthAddress address, EthAccount account, Class<T> contractInterface) { return createContractProxy(getDetails(address), address, account, contractInterface); } public SmartContract createSmartContract(SolidityContractDetails contract, EthAddress address, EthAccount account) { return ethereumProxy.getSmartContract(contract, address, account); } public SmartContract createSmartContract(EthAddress address, EthAccount account) { return createSmartContract(getDetails(address), address, account); } public SmartContract createSmartContract(EthAbi abi, EthAddress address, EthAccount account) { return createSmartContract(new SolcSolidityContractDetails(abi.getAbi(), null, null), address, account); } /** * Creates a proxy object representing the interface with the smart contract. * @param abi The ABI of the smart contract * @param address The address of the smart contract * @param account The account to use to send transactions * @param contractInterface The interface representing the smart contract * @param <T> the proxy object type * @return The contract proxy object */ public <T> T createContractProxy(EthAbi abi, EthAddress address, EthAccount account, Class<T> contractInterface) { T proxy = (T) newProxyInstance(contractInterface.getClassLoader(), new Class[]{contractInterface}, handler); handler.register(proxy, contractInterface, new SolcSolidityContractDetails(abi.getAbi(), null, null), address, account); return proxy; } /** * Creates a proxy object representing the interface with the smart contract. * @param details The compiled smart contract * @param address The address of the smart contract * @param account The account to use to send transactions * @param contractInterface The interface representing the smart contract * @param <T> the proxy object type * @return The contract proxy object */ public <T> T createContractProxy(SolidityContractDetails details, EthAddress address, EthAccount account, Class<T> contractInterface) { T proxy = (T) newProxyInstance(contractInterface.getClassLoader(), new Class[]{contractInterface}, handler); handler.register(proxy, contractInterface, details, address, account); return proxy; } /** * Publishes the contract * @param contract The compiled contract to publish * @param account The account that publishes it * @param constructorArgs The constructor arguments * @return The future address of the newly created smart contract */ public CompletableFuture<EthAddress> publishContract(SolidityContractDetails contract, EthAccount account, Object... constructorArgs) { return ethereumProxy.publish(contract, account, constructorArgs); } /** * Publishes the contract and sends ether at the same time * @param contract The compiled contract to publish * @param account The account that publishes it * @param value How much ether to send while publishing the smart contract * @param constructorArgs The constructor arguments * @return The future address of the newly created smart contract */ public CompletableFuture<EthAddress> publishContractWithValue(SolidityContractDetails contract, EthAccount account, EthValue value, Object... constructorArgs) { return ethereumProxy.publishWithValue(contract, account, value, constructorArgs); } /** * Publishes the smart contract metadata to Swarm * @param contract The compiled contract * @return The swarm hash */ public SwarmHash publishMetadataToSwarm(SolidityContractDetails contract) { return swarmService.publish(contract.getMetadata()); } /** * Checks if an address exists * @param address The address to check * @return Whether it exists or not */ public boolean addressExists(EthAddress address) { return ethereumProxy.addressExists(address); } /** * Gets the balance at an address * @param addr The address to check * @return The current balance */ public EthValue getBalance(EthAddress addr) { return ethereumProxy.getBalance(addr); } /** * Gets the balance of an account * @param account The account to check * @return The current balance */ public EthValue getBalance(EthAccount account) { return ethereumProxy.getBalance(account.getAddress()); } /** * Returns the event handler object * This object is used to observe transactions and blocks * @return The event handler */ public EthereumEventHandler events() { return ethereumProxy.events(); } /** * Returns the current best block number * @return The best block number */ public long getCurrentBlockNumber() { return ethereumProxy.getCurrentBlockNumber(); } /** * Sends ether * @param fromAccount The account that sends ether * @param to The target address * @param value The value to send * @return The future details of the call */ public CompletableFuture<CallDetails> sendEther(EthAccount fromAccount, EthAddress to, EthValue value) { return ethereumProxy.sendTx(value, EthData.empty(), fromAccount, to); } /** * Sends the transaction * @param value The value to send * @param data The data to send * @param account The account that sends ether * @param address The target address * @return The future details of the call */ public CompletableFuture<CallDetails> sendTx(EthValue value, EthData data, EthAccount account, EthAddress address) { return ethereumProxy.sendTx(value, data, account, address); } /** * Returns the current Nonce of an address. * It takes into account pending transactions as well * @param address The address from which we want the Nonce * @return The Nonce */ public Nonce getNonce(EthAddress address) { return ethereumProxy.getNonce(address); } /** * Returns the GasUsage of the transaction data. * It takes into account additional gas usage for contract creation * @param value The value to send * @param data The data to send * @param account The account that sends ether * @param address The target address * @return The GasUsage */ public GasUsage estimateGas(EthValue value, EthData data, EthAccount account, EthAddress address) { return ethereumProxy.estimateGas(value, data, account, address); } /** * Returns the set of transactions that are being sent by propeller and but not added to the chain yet * @param address The transaction sender * @return the set of transaction hashes */ public Set<EthHash> getPendingTransactions(EthAddress address) { return ethereumProxy.getPendingTransactions(address); } /** * Returns the binary code from a deployed smart contract * @param address The smart contract's address * @return The code */ public SmartContractByteCode getCode(EthAddress address) { return ethereumProxy.getCode(address); } /** * Downloads and returns the smart contract's metadata * @param swarmMetadaLink Swarm url * @return The metadata */ public SmartContractMetadata getMetadata(SwarmMetadaLink swarmMetadaLink) { try { return swarmService.getMetadata(swarmMetadaLink.getHash()); } catch (IOException e) { throw new EthereumApiException("error while getting metadata", e); } } /** * Compiles the solidity file * @param src the source file * @return The compilation result */ public CompilationResult compile(SoliditySourceFile src, Optional<EvmVersion> evmVersion) { return solidityCompiler.compileSrc(src, evmVersion); } public CompilationResult compile(SoliditySourceFile src) { return solidityCompiler.compileSrc(src, Optional.empty()); } /** * Search an event definition from the ABI * @param contract The compiled contract * @param eventName The event name * @param eventEntity The entity that will represent the event * @param <T> The event entity tpye * @return The solidity event definition if found */ public <T> Optional<TypedSolidityEvent<T>> findEventDefinition(SolidityContractDetails contract, String eventName, Class<T> eventEntity) { return contract.getAbi().stream() .filter(entry -> entry.getType().equals("event")) .filter(entry -> entry.getName().equals(eventName)) .filter(entry -> { List<List<SolidityTypeDecoder>> decoders = entry.getInputs().stream().map(ethereumProxy::getDecoders).collect(Collectors.toList()); return entry.findConstructor(decoders, eventEntity).isPresent(); }) .map(entry -> { List<List<SolidityTypeDecoder>> decoders = entry.getInputs().stream().map(ethereumProxy::getDecoders).collect(Collectors.toList()); return new TypedSolidityEvent<>(entry, decoders, eventEntity); }).findFirst(); } /** * Search an event definition from the ABI * @param contract The compiled contract * @param eventName The event name * @param eventParams the type of each parameter in the event. Useful when you don't want to map it to a class * @return The solidity event definition if found */ public Optional<RawSolidityEvent> findEventDefinitionForParameters(SolidityContractDetails contract, String eventName, List<Class<?>> eventParams) { return contract.getAbi().stream() .filter(entry -> entry.getType().equals("event")) .filter(entry -> entry.getName().equals(eventName)) .filter(entry -> { List<List<SolidityTypeDecoder>> decoders = entry.getInputs().stream().map(ethereumProxy::getDecoders).collect(Collectors.toList()); if(decoders.size() != eventParams.size()) { return false; } for(int i = 0; i < decoders.size(); i++) { Class<?> cls = eventParams.get(i); if (decoders.get(i).stream().noneMatch(decoder -> decoder.canDecode(cls))) { return false; } } return true; }) .map(entry -> { List<List<SolidityTypeDecoder>> decoders = entry.getInputs().stream().map(ethereumProxy::getDecoders).collect(Collectors.toList()); return new RawSolidityEvent(entry, decoders, eventParams); }).findFirst(); } /** * Search an event definition from the ABI * * @param abi The ABI * @param eventName The event name * @param eventParameters The types of each parameter in the event. Useful when you don't want to map the event to a class * @return The solidity event definition if found */ public Optional<RawSolidityEvent> findEventDefinitionForParametersByAbi(EthAbi abi, String eventName, List<Class<?>> eventParameters) { return findEventDefinitionForParameters(new SolcSolidityContractDetails(abi.getAbi(), "", ""), eventName, eventParameters); } /** * Search an event definition from the ABI * * @param abi The ABI * @param eventName The event name * @param eventEntity The entity that will represent the event * @param <T> The event entity * @return The solidity event definition if found */ public <T> Optional<TypedSolidityEvent<T>> findEventDefinition(EthAbi abi, String eventName, Class<T> eventEntity) { return findEventDefinition(new SolcSolidityContractDetails(abi.getAbi(), "", ""), eventName, eventEntity); } /** * Observe an event from a smart contract * @param eventDefiniton The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The event observable */ public <T> Observable<T> observeEvents(SolidityEvent<T> eventDefiniton, EthAddress address) { return ethereumProxy.observeEvents(eventDefiniton, address); } /** * Observe an event from a smart contract and returns not only the event but the transaction info as well * * @param eventDefiniton The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The event observable with the info */ public <T> Observable<EventInfo<T>> observeEventsWithInfo(SolidityEvent<T> eventDefiniton, EthAddress address) { return ethereumProxy.observeEventsWithInfo(eventDefiniton, address); } /** * Returns all the events that happened at a specific block * * @param blockNumber The block number * @param eventDefinition The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The list of events */ public <T> List<T> getEventsAtBlock(Long blockNumber, SolidityEvent<T> eventDefinition, EthAddress address) { return ethereumProxy.getEventsAtBlock(eventDefinition, address, blockNumber); } /** * Returns all the events that happened at a specific block * * @param blockHash The block hash * @param eventDefinition The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The list of events */ public <T> List<T> getEventsAtBlock(EthHash blockHash, SolidityEvent<T> eventDefinition, EthAddress address) { return ethereumProxy.getEventsAtBlock(eventDefinition, address, blockHash); } /** * Returns all the events that happened at a specific block * * @param transactionHash The transactionHash hash * @param eventDefinition The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The list of events */ public <T> List<T> getEventsAtTransaction(EthHash transactionHash, SolidityEvent<T> eventDefinition, EthAddress address) { return ethereumProxy.getEventsAtTransaction(eventDefinition, address, transactionHash); } /** * Returns all the events that happened at a specific block * * @param blockNumber The block number * @param eventDefinition The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The list of events */ public <T> List<EventInfo<T>> getEventsAtBlockWithInfo(Long blockNumber, SolidityEvent<T> eventDefinition, EthAddress address) { return ethereumProxy.getEventsAtBlockWithInfo(eventDefinition, address, blockNumber); } /** * Returns all the events that happened at a specific block * * @param blockHash The block hash * @param eventDefinition The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The list of events */ public <T> List<EventInfo<T>> getEventsAtBlockWithInfo(EthHash blockHash, SolidityEvent<T> eventDefinition, EthAddress address) { return ethereumProxy.getEventsAtBlockWithInfo(eventDefinition, address, blockHash); } /** * Returns all the events that happened at a specific block * * @param transactionHash The transactionHash hash * @param eventDefinition The event definition * @param address The smart contract's address * @param <T> The event entity type * @return The list of events */ public <T> List<EventInfo<T>> getEventsAtTransactionWithInfo(EthHash transactionHash, SolidityEvent<T> eventDefinition, EthAddress address) { return ethereumProxy.getEventsAtTransactionWithInfo(eventDefinition, address, transactionHash); } /** * Returns all the events that happened at a smart contract matching an event signature and indexed parameters * * @param fromBlock From which block to search from for the events * @param toBlock Latest block which should be searched from for the events * @param eventDefiniton Event definition that should be matched * @param address address of the smart contract that emits the events * @param optionalTopics Optional indexed event parameters, passed as 64 character hexidecimal string */ public List<EventData> getLogs(Optional<DefaultBlockParameter> fromBlock, Optional<DefaultBlockParameter> toBlock, SolidityEvent eventDefiniton, EthAddress address, String... optionalTopics) { return ethereumProxy.getLogs(fromBlock.orElse(DefaultBlockParameterName.EARLIEST), toBlock.orElse(DefaultBlockParameterName.LATEST), eventDefiniton, address, optionalTopics); } /** * Encodes an argument manually. This can be useful when you need to send a value to a bytes or bytes32 input * @param arg The argument to encode * @param solidityType Which solidity type is the argument represented * @return The Encoded result */ public EthData encode(Object arg, SolidityType solidityType) { return Optional.of(arg).map(argument -> { SolidityTypeEncoder encoder = ethereumProxy.getEncoders(new AbiParam(false, "", solidityType.name())) .stream().filter(enc -> enc.canConvert(arg.getClass())) .findFirst().orElseThrow(() -> new EthereumApiException("cannot convert the type " + argument.getClass() + " to the solidty type " + solidityType)); return encoder.encode(arg, solidityType); }).orElseGet(EthData::empty); } public <T> T decode(EthData data, SolidityType solidityType, Class<T> cls) { return decode(0, data, solidityType, cls); } /** * Decodes an ouput. This is useful when a function returns bytes or bytes32 and you want to cast it to a specific type * @param index It can be that more than one value has been encoded in the data. This is the index of this value. It starts with 0 * @param data The data to decode * @param solidityType The target solidity type * @param cls The target class * @param <T> The value type * @return The decoded value */ public <T> T decode(Integer index, EthData data, SolidityType solidityType, Class<T> cls) { if (ethereumProxy.isVoidType(cls)) { return null; } SolidityTypeDecoder decoder = ethereumProxy.getDecoders(new AbiParam(false, "", solidityType.name())) .stream() .filter(dec -> dec.canDecode(cls)) .findFirst().orElseThrow(() -> new EthereumApiException("cannot decode " + solidityType.name() + " to " + cls.getTypeName())); return (T) decoder.decode(index, data, cls); } public ChainId getChainId() { return ethereumProxy.getChainId(); } /** * Gets info for the transaction with the specific hash * * @param hash The hash of the transaction * @return the info */ public Optional<TransactionInfo> getTransactionInfo(EthHash hash) { return ethereumProxy.getTransactionInfo(hash); } public EthereumFacade addDecoder(SolidityTypeGroup solidityTypeGroup, SolidityTypeDecoder decoder) { ethereumProxy.addDecoder(solidityTypeGroup, decoder); return this; } public EthereumFacade addEncoder(SolidityTypeGroup solidityTypeGroup, SolidityTypeEncoder encoder) { ethereumProxy.addEncoder(solidityTypeGroup, encoder); return this; } public EthereumFacade addListDecoder(final Class<? extends CollectionDecoder> decoder) { ethereumProxy.addListDecoder(decoder); return this; } public EthereumFacade addListEncoder(final Class<? extends CollectionEncoder> encoder) { ethereumProxy.addListEncoder(encoder); return this; } private SolidityContractDetails getDetails(final EthAddress address) { SmartContractByteCode code = ethereumProxy.getCode(address); SmartContractMetadata metadata = getMetadata(code.getMetadaLink().orElseThrow(() -> new EthereumApiException("no metadata link found for smart contract on address " + address.toString()))); return new SolcSolidityContractDetails(metadata.getAbi(), "", ""); } }
package org.apache.camel.component.cm.client; public interface Translator<T> { public SMSMessage translate(T t); }
package tests.pages; import org.fluentlenium.core.FluentPage; import org.openqa.selenium.WebDriver; import static org.fest.assertions.Assertions.assertThat; /** * Provides test scaffolding for the showMagicians page. */ public class ShowMagiciansPage extends FluentPage { private String url; /** * Create the showMagicians Page. * * @param webDriver The driver. * @param port The port. */ public ShowMagiciansPage(WebDriver webDriver, int port) { super(webDriver); this.url = "http://localhost:" + port + "/showMagicians"; } /** * Get the URL for this page. * * @return The page's URL. */ @Override public String getUrl() { return this.url; } /** * A test to ensure the rendered page displays the correct content. */ @Override public void isAt() { assertThat(pageSource().contains("<body id=\"showMagician\">")); } /** * Checks that the NewMagician page contains a given magician, with only Name, Stage Name, Skill Level, and Interests. * * @param fullName The combined first and last name of the magician. * @param stageName The stage name of the magician. * @param interests User's interests in magic. * @param experienceLevel User's experience level; pre-set values. */ public void hasMagician(String fullName, String stageName, String interests, String experienceLevel) { assertThat(pageSource()).contains(fullName); assertThat(pageSource()).contains(stageName); assertThat(pageSource()).contains(experienceLevel); assertThat(pageSource()).contains(interests); } }
package io.spacedog.server; import java.io.IOException; import java.util.Collections; import java.util.concurrent.ExecutionException; import org.elasticsearch.analysis.common.CommonAnalysisPlugin; import org.elasticsearch.cli.Terminal; import org.elasticsearch.common.logging.LogConfigurator; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings.Builder; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.env.Environment; import org.elasticsearch.index.reindex.ReindexPlugin; import org.elasticsearch.node.InternalSettingsPreparer; import org.elasticsearch.node.NodeValidationException; import org.elasticsearch.transport.Netty4Plugin; import org.joda.time.DateTimeZone; import io.spacedog.utils.ClassResources; import io.spacedog.utils.DateTimeZones; import io.spacedog.utils.Exceptions; import io.spacedog.utils.Json; import net.codestory.http.AbstractWebServer; import net.codestory.http.Request; import net.codestory.http.Response; import net.codestory.http.internal.Handler; import net.codestory.http.internal.HttpServerWrapper; import net.codestory.http.internal.SimpleServerWrapper; import net.codestory.http.payload.Payload; import net.codestory.http.routes.Routes; import net.codestory.http.websockets.WebSocketHandler; public class Server { public static final String CLUSTER_NAME = "spacedog-v1-cluster"; private ElasticNode elasticNode; private ElasticClient elasticClient; private FluentServer fluent; private ServerConfiguration config; private Info info; public ElasticClient elasticClient() { return elasticClient; } public ElasticNode elasticNode() { return elasticNode; } public ServerConfiguration configuration() { return config; } public static void main(String[] args) { DateTimeZone.setDefault(DateTimeZones.PARIS); Server server = new Server(); server.start(); } public void start() { try { init(); startElastic(); elasticIsStarted(); startFluent(); fluentIsStarted(); } catch (Throwable t) { t.printStackTrace(); if (fluent != null) fluent.stop(); if (elasticClient != null) elasticClient.close(); if (elasticNode != null) elasticClient.close(); System.exit(-1); } } protected void init() { this.config = new ServerConfiguration(); System.setProperty("http.agent", configuration().serverUserAgent()); String string = ClassResources.loadAsString(Server.class, "info.json"); info = Json.toPojo(string, Info.class); } protected void startElastic() throws InterruptedException, ExecutionException, IOException, NodeValidationException { Builder builder = Settings.builder() .put(Environment.PATH_HOME_SETTING.getKey(), config.homePath().toAbsolutePath().toString()); // .put(Node.NODE_MASTER_SETTING.getKey(), true)// // .put(Node.NODE_DATA_SETTING.getKey(), true)// // .put(DiscoveryModule.DISCOVERY_TYPE_SETTING.getKey(), "single-node")// // // .put(NetworkModule.TRANSPORT_TYPE_SETTING.getKey(), "netty4") // // .put(ClusterName.CLUSTER_NAME_SETTING.getKey(), CLUSTER_NAME)// // // disable automatic index creation // .put(AutoCreateIndex.AUTO_CREATE_INDEX_SETTING.getKey(), false)// // // disable dynamic indexing // // .put("index.mapper.dynamic", false)// // // .put("index.max_result_window", 5000)// // // disable rebalance to avoid automatic rebalance // // when a temporary second node appears // .put("cluster.routing.rebalance.enable", "none")// // .put(NetworkModule.HTTP_ENABLED.getKey(), // // config.elasticIsHttpEnabled())// // .put(NetworkService.GLOBAL_NETWORK_HOST_SETTING.getKey(), // // config.elasticNetworkHost())// // .put(Environment.PATH_LOGS_SETTING.getKey(), // // config.elasticLogsPath().toAbsolutePath().toString()) // .put(Environment.PATH_DATA_SETTING.getKey(), // // config.elasticDataPath().toAbsolutePath().toString()); // if (config.elasticSnapshotsPath().isPresent()) // builder.put(Environment.PATH_REPO_SETTING.getKey(), // // config.elasticSnapshotsPath().get().toAbsolutePath().toString()); Settings settings = builder.build(); Environment environment = InternalSettingsPreparer.prepareEnvironment( settings, Terminal.DEFAULT, Collections.emptyMap(), config.elasticConfigPath()); try { LogConfigurator.configure(environment); } catch (Exception e) { throw Exceptions.runtime(e, "error configuring elastic log"); } elasticNode = new ElasticNode(environment, Netty4Plugin.class, CommonAnalysisPlugin.class, ReindexPlugin.class); // S3RepositoryPlugin.class); elasticNode.start(); this.elasticClient = new ElasticClient(elasticNode.client()); // wait for cluster to fully initialize and turn asynchronously from // RED status to GREEN before to initialize anything else // wait for 60 seconds maximum by default // configurable with spacedog.server.green.check and timeout properties elasticClient.ensureAllIndicesAreGreen(); } protected void elasticIsStarted() { // init templates this.elasticClient.internal().admin().indices() .preparePutTemplate("data") .setSource( ClassResources.loadAsBytes(Server.class, "data-template.json"), XContentType.JSON) .get(); // init root backend indices String backendId = config.apiBackend().backendId(); AdminService.get().initBackendIndices(backendId); } protected void startFluent() { fluent = new FluentServer(); fluent.configure(routes -> configure(routes)); fluent.start(config.serverPort()); } protected void fluentIsStarted() { } protected void configure(Routes routes) { routes.add(AdminService.get()) .add(DataService.get()) .add(SchemaService.get()) .add(CredentialsService.get()) .add(LinkedinService.get()) .add(BatchService.get()) .add(EmailService.get()) .add(SmsService.get()) .add(LogService.get()) .add(PushService.get()) .add(ApplicationService.get()) .add(StripeService.get()) .add(SettingsService.get()) .add(SearchService.get()); routes.filter(new CrossOriginFilter()) .filter(SpaceContext.filter()) .filter(LogService.filter()) .filter(SpaceContext.checkAuthorizationFilter()) // web filter before error filter // so web errors are html pages .filter(WebService.get().filter()) .filter(new ServiceErrorFilter()) .filter(FileService.get().filter()); } public static class Info { public String version; public String baseline; } public Info info() { return info; } public Payload executeRequest(Request request, Response response) throws Exception { return fluent.executeRequest(request, response); } // Implementation private static class FluentServer extends AbstractWebServer<FluentServer> { @Override protected HttpServerWrapper createHttpServer(Handler httpHandler, WebSocketHandler webSocketHandler) { return new SimpleServerWrapper(httpHandler, webSocketHandler, 12, 1, 1); } public Payload executeRequest(Request request, Response response) throws Exception { return routesProvider.get().apply(request, response); } } // Singleton private static Server singleton; public static Server get() { return singleton; } protected Server() { if (singleton != null) throw Exceptions.runtime("server already running"); singleton = this; } }
package org.apache.mesos.offer; import org.apache.mesos.Protos; import org.apache.mesos.Protos.Offer; import org.apache.mesos.Protos.OfferID; import org.apache.mesos.SchedulerDriver; import java.util.*; /** * This scheduler performs UNRESERVE and DESTROY operations on resources which are identified * as unexpected by the ResourceCleaner. */ public class ResourceCleanerScheduler { private ResourceCleaner resourceCleaner; private OfferAccepter offerAccepter; public ResourceCleanerScheduler( ResourceCleaner resourceCleaner, OfferAccepter offerAccepter) { this.resourceCleaner = resourceCleaner; this.offerAccepter = offerAccepter; } public List<OfferID> resourceOffers(SchedulerDriver driver, List<Offer> offers) { final List<OfferRecommendation> recommendations = resourceCleaner.evaluate(offers); // Recommendations should be grouped by agent, as Mesos enforces processing of acceptOffers Operations // that belong to a single agent. final Map<Protos.SlaveID, List<OfferRecommendation>> recommendationsGroupedByAgents = groupRecommendationsByAgent(recommendations); final List<OfferID> processedOffers = new ArrayList<>(offers.size()); for (Map.Entry<Protos.SlaveID, List<OfferRecommendation>> entry : recommendationsGroupedByAgents.entrySet()) { processedOffers.addAll(offerAccepter.accept(driver, recommendationsGroupedByAgents.get(entry.getKey()))); } return processedOffers; } /** * Groups recommendations by agent. * * Visibility is protected to enable testing. */ protected Map<Protos.SlaveID, List<OfferRecommendation>> groupRecommendationsByAgent( List<OfferRecommendation> recommendations) { final Map<Protos.SlaveID, List<OfferRecommendation>> recommendationsGroupedByAgents = new HashMap<>(); for (OfferRecommendation recommendation : recommendations) { final Protos.SlaveID agentId = recommendation.getOffer().getSlaveId(); if (!recommendationsGroupedByAgents.containsKey(agentId)) { recommendationsGroupedByAgents.put(agentId, new ArrayList<>()); } final List<OfferRecommendation> agentRecommendations = recommendationsGroupedByAgents.get(agentId); agentRecommendations.add(recommendation); recommendationsGroupedByAgents.put(agentId, agentRecommendations); } return recommendationsGroupedByAgents; } }
package org.dstadler.commoncrawl.index; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.google.common.base.Preconditions; import com.google.common.io.CountingInputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.util.EntityUtils; import org.archive.util.zip.GZIPMembersInputStream; import org.dstadler.commoncrawl.Extensions; import org.dstadler.commoncrawl.MimeTypes; import org.dstadler.commoncrawl.Utils; import org.dstadler.commons.collections.MappedCounter; import org.dstadler.commons.collections.MappedCounterImpl; import org.dstadler.commons.http.HttpClientWrapper; import org.dstadler.commons.logging.jdk.LoggerFactory; import java.io.*; import java.util.logging.Logger; public class DownloadURLIndex { private static final Logger log = LoggerFactory.make(); public static final String CURRENT_CRAWL = "CC-MAIN-2021-49"; public static final File COMMON_CRAWL_FILE = new File("commoncrawl-" + CURRENT_CRAWL + ".txt"); private static final int START_INDEX = 0; private static final int END_INDEX = 299; private static final String URL_FORMAT = "https://commoncrawl.s3.amazonaws.com/cc-index/collections/" + CURRENT_CRAWL + "/indexes/cdx-%05d.gz"; private static final JsonFactory JSON_FACTORY = new JsonFactory(); private static final MappedCounter<String> FOUND_MIME_TYPES = new MappedCounterImpl<>(); private static int index = START_INDEX; public static void main(String[] args) throws Exception { LoggerFactory.initLogging(); log.info("Processing index files starting from index " + index + " with pattern " + URL_FORMAT); for(; index <= END_INDEX; index++) { try { try (HttpClientWrapper client = new HttpClientWrapper("", null, 600_000)) { handleCDXFile(client.getHttpClient(), index); } } catch (IOException e) { log.info("Retry once starting at file " + index + ": " + e); Thread.sleep(10_000); try (HttpClientWrapper client = new HttpClientWrapper("", null, 600_000)) { handleCDXFile(client.getHttpClient(), index); } } } } private static void handleCDXFile(CloseableHttpClient httpClient, int index) throws IOException { String url = String.format(URL_FORMAT, index); log.info("Loading file " + index + " from " + url); final HttpGet httpGet = new HttpGet(url); try (CloseableHttpResponse response = httpClient.execute(httpGet)) { HttpEntity entity = Utils.checkAndFetch(response, url); log.info("File " + index + " has " + entity.getContentLength() + " bytes"); try { handleInputStream(url, entity.getContent(), index, entity.getContentLength()); } catch (Exception e) { // try to stop processing in case of Exceptions in order to not download the whole file // in the implicit close() httpClient.close(); throw e; } finally { // ensure all content is taken out to free resources EntityUtils.consume(entity); } } FileUtils.writeStringToFile(new File("mimetypes.txt"), FOUND_MIME_TYPES.sortedMap().toString().replace(",", "\n"), "UTF-8"); } @SuppressWarnings("UnstableApiUsage") protected static void handleInputStream(String url, InputStream stream, int index, long length) throws IOException { // use buffered reading to read large chunks of data at once try (CountingInputStream content = new CountingInputStream(new BufferedInputStream(stream, 10*1024*1024)); CountingInputStream uncompressedStream = new CountingInputStream(new GZIPMembersInputStream(content)); BufferedReader reader = new BufferedReader(new InputStreamReader(uncompressedStream), 1024*1024)) { int count = 0; long lastLog = System.currentTimeMillis(); while(true) { String line = reader.readLine(); if(line == null) { log.info("End of stream reached for " + url + " after " + count + " lines, "); // log.info(content.available() + " available, " // + content.getCount() + " compressed bytes, " // + content.read() + " read, " // + uncompressedStream.available() + " available, " // + uncompressedStream.getCount() + " uncompressed bytes, " // + uncompressedStream.read() + " read, " break; } int endOfUrl = line.indexOf(' '); Preconditions.checkState(endOfUrl != -1, "could not find end of url"); int endOfTimestamp = line.indexOf(' ', endOfUrl+1); Preconditions.checkState(endOfTimestamp != -1, "could not find end of timestamp"); String json = line.substring(endOfTimestamp+1); handleJSON(json); count++; if(count % 100000 == 0 || lastLog < (System.currentTimeMillis() - 10000)) { log.info("File " + index + ": " + count + " lines, compressed bytes: " + content.getCount() + " of " + length + "(" + String.format("%.2f", ((double)content.getCount())/length*100) + "%), bytes: " + uncompressedStream.getCount() + ": " + StringUtils.abbreviate(FOUND_MIME_TYPES.sortedMap().toString(), 95)); lastLog = System.currentTimeMillis(); } } } } private static void handleJSON(String json) throws IOException { try (JsonParser jp = JSON_FACTORY.createParser(json)) { while(jp.nextToken() != JsonToken.END_OBJECT) { if(jp.getCurrentToken() == JsonToken.VALUE_STRING) { /* JSON: url, mime, mime-detected, status, digest, length, offset, filename, charset, language */ if("mime".equals(jp.getCurrentName())) { String mimeType = jp.getValueAsString().toLowerCase(); FOUND_MIME_TYPES.addInt(mimeType, 1); if(MimeTypes.matches(mimeType)) { log.info("Found-Mimetype: " + json); FileUtils.writeStringToFile(COMMON_CRAWL_FILE, json + "\n", "UTF-8", true); } } else if("url".equals(jp.getCurrentName())) { String url = jp.getValueAsString().toLowerCase(); if(Extensions.matches(url)) { log.info("Found-URL: " + json); FileUtils.writeStringToFile(COMMON_CRAWL_FILE, json + "\n", "UTF-8", true); } } } } } } }
package org.g_node.reporter.LKTLogbook; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryExecution; import com.hp.hpl.jena.query.QueryExecutionFactory; import com.hp.hpl.jena.query.QueryFactory; import com.hp.hpl.jena.query.ResultSet; import com.hp.hpl.jena.rdf.model.Model; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.log4j.Logger; import org.g_node.micro.commons.AppUtils; import org.g_node.micro.commons.CliToolController; import org.g_node.micro.commons.RDFService; import org.g_node.srv.CliOptionService; import org.g_node.srv.CtrlCheckService; /** * Class handling how to fetch reports from an RDF file specific to the LKT Logbook use case of Kay Thurley. * * @author Michael Sonntag (sonntag@bio.lmu.de) */ public class LktCliController implements CliToolController { /** * Access to the main LOGGER. */ private static final Logger LOGGER = Logger.getLogger(LktCliController.class.getName()); /** * Reports available to the reporter tool specific for the LKT Logbook use case. */ private Map<String, String> reports; /** * Constructor populates the Map of queries available to this reporter. * Entries have to be be upper case. */ public LktCliController() { final String queryPrefixes = String.join("", "prefix lkt: <https://orcid.org/0000-0003-4857-1083 "prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns "prefix gn: <https://github.com/G-Node/neuro-ontology/>", "prefix rdfs: <http://www.w3.org/2000/01/rdf-schema "prefix xs: <http://www.w3.org/2001/XMLSchema "prefix foaf: <http://xmlns.com/foaf/0.1/>", "prefix dc: <http://purl.org/dc/terms/>" ); final String experimentsQuery = String.join("", queryPrefixes, "SELECT ?Project ?Experiment ?ExperimentDate ?Paradigm ?ParadigmSpecifics ", "?Experimenter ?ExperimentComment ?SubjectId ?BirthDate ?Sex ?WithdrawalDate ", "?PermitNumber ?ExperimentId ", " WHERE {", "{", "?node a gn:Project ;", "rdfs:label ?Project ;", "gn:hasExperiment ?ExperimentId ;", "gn:hasProvenance ?ProvenanceId .", "}", " OPTIONAL {", "?ExperimentId rdfs:comment ?ExperimentComment .", "?ExperimentId gn:hasParadigm ?Paradigm .", "?ExperimentId gn:hasParadigmSpecifics ?ParadigmSpecifics .", "}", "?ExperimentId rdfs:label ?Experiment .", "?ExperimentId gn:startedAt ?ExperimentDate .", "?ExperimentId gn:hasSubject ?Subject .", "?ExperimentId gn:hasExperimenter ?ExperimenterId .", "?ExperimenterId foaf:name ?Experimenter .", "?Subject gn:hasSubjectID ?SubjectId .", "?Subject gn:hasPermit ?PermitId .", "?Subject gn:hasBirthDate ?BirthDate .", "?Subject gn:hasSex ?Sex .", "?Subject gn:hasWithdrawalDate ?WithdrawalDate .", "?PermitId gn:hasNumber ?PermitNumber .", "}", " ORDER BY ?Project ?SubjectId ?ExperimentDate" ); final String subjectsQuery = String.join("", queryPrefixes, "SELECT ?SubjectID ?PermitNumber ?SpeciesName ?ScientificName ?Sex ?BirthDate ?WithdrawalDate ", " ?FirstLogEntry ?FirstExperimenter ?LastLogEntry ?LastExperimenter ?ExitComment ?ExitLogEntry ?ExCom ", " WHERE ", "{", "{", "?node a gn:Subject ;", "gn:hasSubjectID ?SubjectID ;", "gn:hasSpeciesName ?SpeciesName ;", "gn:hasScientificName ?ScientificName ;", "gn:hasSex ?Sex ;", "gn:hasBirthDate ?BirthDate ;", "gn:hasWithdrawalDate ?WithdrawalDate ;", "gn:hasPermit ?PermitID .", "}", "?PermitID gn:hasNumber ?PermitNumber .", "{", "SELECT ?node (MIN(?date) as ?FirstLogEntry)", " WHERE { ", "?node a gn:Subject ; gn:hasSubjectLogEntry ?sl . ?sl gn:startedAt ?date . ", "} GROUP BY ?node ?FirstLogEntry", "}", "{", "SELECT ?node (MAX(?date) as ?LastLogEntry)", " WHERE { ", "?node a gn:Subject ; gn:hasSubjectLogEntry ?sl . ?sl gn:startedAt ?date . ", "} GROUP BY ?node ?LastLogEntry", "}", "{", "SELECT ?node (MIN(?date) as ?ExitLogEntry)", " WHERE { ", "?node a gn:Subject ; gn:hasSubjectLogEntry ?sl . ?sl gn:startedAt ?date ; rdfs:comment ?c . ", " FILTER regex(?c, \".*(Euthanasie|Ausgeschleust).*\", \"i\") ", "} GROUP BY ?node ?ExitLogEntry", "}", "OPTIONAL { ?node gn:hasSubjectLogEntry ?l2 . ?l2 gn:startedAt ?FirstLogEntry ; ", "gn:hasExperimenter ?expUUID . ?expUUID foaf:name ?FirstExperimenter . }", "OPTIONAL { ?node gn:hasSubjectLogEntry ?l3 . ?l3 gn:startedAt ?LastLogEntry ; ", "gn:hasExperimenter ?expUUID2 ; rdfs:comment ?ExitComment . ?expUUID2 foaf:name ?LastExperimenter . }", "OPTIONAL { ?node gn:hasSubjectLogEntry ?l4 . ?l4 gn:startedAt ?ExitLogEntry ; rdfs:comment ?ExCom . }", "}", " ORDER BY ?SubjectID ?EntryDate" ); this.reports = new HashMap<String, String>() { { put("EXPERIMENTS", experimentsQuery); put("SUBJECTS", subjectsQuery); put("CUSTOM", ""); } }; } /** * Method returning the commandline options of the LKT reporter tool. * * @return Available {@link CommandLine} {@link Options}. */ public final Options options() { final Options options = new Options(); final Option opHelp = CliOptionService.getHelpOption(""); final Option opInRdfFile = CliOptionService.getInFileOption(""); final Option opReport = CliOptionService.getReportOption("", this.reports.keySet()); final Option opOutFile = CliOptionService.getOutFileOption(""); final Option opOutFormat = CliOptionService.getOutFormatOption("", RDFService.QUERY_RESULT_FILE_FORMATS.keySet()); final Option opQueryFile = Option.builder("c") .longOpt("custom-query-file") .desc(String.join("", "Optional: SPARQL query file. ", "-r CUSTOM requires option -c with a file containing a valid SPARQL query.")) .hasArg() .valueSeparator() .build(); options.addOption(opHelp); options.addOption(opInRdfFile); options.addOption(opReport); options.addOption(opOutFile); options.addOption(opOutFormat); options.addOption(opQueryFile); return options; } /** * Method to check input file, available report, output file format and to facilitate the * delegation of creating the report and saving it an output file. * * @param cmd User provided {@link CommandLine} input. */ public final void run(final CommandLine cmd) { final String inFile = cmd.getOptionValue("i"); if (!CtrlCheckService.isExistingFile(inFile)) { return; } if (!CtrlCheckService.isValidRdfFile(inFile)) { return; } if (!CtrlCheckService.isSupportedCliArgValue(cmd.getOptionValue("r"), this.reports.keySet(), "-r/-report")) { return; } final String outputFormat = cmd.getOptionValue("f", "CSV"); if (!CtrlCheckService.isSupportedOutputFormat(outputFormat, RDFService.QUERY_RESULT_FILE_FORMATS.keySet())) { return; } String queryString = this.reports.get(cmd.getOptionValue("r").toUpperCase(Locale.ENGLISH)); if ("CUSTOM".equals(cmd.getOptionValue("r").toUpperCase(Locale.ENGLISH))) { final String customQueryFile = cmd.getOptionValue("c", ""); LktCliController.LOGGER.info( String.join("", "Using custom query option -c...\t(", customQueryFile , ")") ); if ("".equals(cmd.getOptionValue("c", ""))) { LktCliController.LOGGER.error( String.join("", "Missing required option: c") ); return; } else if (!CtrlCheckService.isExistingFile(cmd.getOptionValue("c", ""))) { return; } else { try { queryString = new String(Files.readAllBytes(Paths.get(cmd.getOptionValue("c", "")))); } catch (IOException exc) { LktCliController.LOGGER.error(exc.getMessage()); exc.printStackTrace(); return; } } } final String defaultOutputFile = String.join("", AppUtils.getTimeStamp("yyyyMMddHHmm"), "_out"); this.runQuery(inFile, queryString, cmd.getOptionValue("o", defaultOutputFile), outputFormat); } /** * Method to run a sparql query on an RDF model and save the results to an output file. * @param inFile Path and filename of an RDF file that is to be queried. * @param queryString SPARQL query. * @param outFile Path and filename where the results of the query are saved to. * @param outputFormat Format of the output file. */ private void runQuery(final String inFile, final String queryString, final String outFile, final String outputFormat) { final Model queryModel = RDFService.openModelFromFile(inFile); final Query query = QueryFactory.create(queryString); LktCliController.LOGGER.info("Start query..."); try (QueryExecution qexec = QueryExecutionFactory.create(query, queryModel)) { final ResultSet result = qexec.execSelect(); RDFService.saveResultsToSupportedFile(result, outputFormat, outFile); } } }
package org.gsonformat.intellij.entity; import com.intellij.openapi.project.Project; import com.intellij.psi.*; import com.intellij.psi.search.GlobalSearchScope; import org.apache.http.util.TextUtils; import org.gsonformat.intellij.config.Config; import org.gsonformat.intellij.config.Strings; import org.gsonformat.intellij.utils.CheckUtil; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class InnerClassEntity extends FieldEntity { private PsiClass psiClass; private String fieldTypeSuffix; private String className; private List<? extends FieldEntity> fields; private String packName; /** * comment */ private String extra; private String autoCreateClassName; public String getExtra() { return extra; } public void setExtra(String extra) { this.extra = extra; } public String getAutoCreateClassName() { return autoCreateClassName; } public void setAutoCreateClassName(String autoCreateClassName) { this.autoCreateClassName = autoCreateClassName; } public <T extends FieldEntity> void setFields(List<T> fields) { this.fields = fields; } public String getPackName() { return packName; } public void setPackName(String packName) { this.packName = packName; } public String getRealType() { return String.format(super.getType(), className); } public void checkAndSetType(String s) { String regex = getType().replaceAll("%s", "(\\\\w+)").replaceAll("\\.", "\\\\."); Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(s); if (matcher.find() && matcher.groupCount() > 0) { String temp = matcher.group(1); if (TextUtils.isEmpty(temp)) { setClassName(getAutoCreateClassName()); } else { setClassName(matcher.group(1)); } } } public String getFieldTypeSuffix() { return fieldTypeSuffix; } public void setFieldTypeSuffix(String fieldTypeSuffix) { this.fieldTypeSuffix = fieldTypeSuffix; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public List<? extends FieldEntity> getFields() { return fields; } public PsiClass getPsiClass() { return psiClass; } public void setPsiClass(PsiClass psiClass) { this.psiClass = psiClass; } public String getClassFieldType() { String fullClassName; if (!TextUtils.isEmpty(getFieldTypeSuffix())) { fullClassName = getFieldTypeSuffix() + "." + getClassName(); } else { fullClassName = getClassName(); } if (TextUtils.isEmpty(getType())) { return fullClassName; } String string = getType().replaceAll("List<", "java.util.List<"); return String.format(string, fullClassName); } private PsiClass getPsiClassByName(Project project, String cls) { GlobalSearchScope searchScope = GlobalSearchScope.allScope(project); JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project); return javaPsiFacade.findClass(cls, searchScope); } // public void addImportClass(PsiClass mClass,PsiElementFactory mFactory,Project project){ // mClass.addBefore(mFactory.createImportStatement(getPsiClassByName(project, "java.util.List")),mClass); public void generateField(Project project, PsiElementFactory mFactory, PsiClass mClass) { try { if (Config.getInstant().getAnnotationStr().equals(Strings.fastAnnotation)) { // PsiModifierList modifierList = mClass.getModifierList(); // PsiElement firstChild = modifierList.getFirstChild(); // Pattern pattern = Pattern.compile("@.*?JsonIgnoreProperties"); // if (!pattern.matcher(firstChild.getText()).find()) { // PsiAnnotation annotationFromText = // mFactory.createAnnotationFromText("@com.fasterxml.jackson.annotation.JsonIgnoreProperties(ignoreUnknown = true)", mClass); // modifierList.addBefore(annotationFromText, firstChild); } else if (Config.getInstant().getAnnotationStr().equals(Strings.loganSquareAnnotation)) { PsiModifierList modifierList = mClass.getModifierList(); PsiElement firstChild = modifierList.getFirstChild(); Pattern pattern = Pattern.compile("@.*?JsonObject"); if (firstChild != null && !pattern.matcher(firstChild.getText()).find()) { PsiAnnotation annotationFromText = mFactory.createAnnotationFromText("@com.bluelinelabs.logansquare.annotation.JsonObject", mClass); modifierList.addBefore(annotationFromText, firstChild); } } } catch (Throwable e) { } for (FieldEntity fieldEntity : getFields()) { if (fieldEntity instanceof InnerClassEntity) { ((InnerClassEntity) fieldEntity).generateSupperFiled(mFactory, mClass); ((InnerClassEntity) fieldEntity).generateClass(mFactory, mClass); } else { fieldEntity.generateFiled(mFactory, mClass, this); } } configGetterAndSetter(mFactory, mClass); createExtraMethod(mFactory, mClass); } private void configGetterAndSetter(PsiElementFactory mFactory, PsiClass mClass) { if (!Config.getInstant().getAnnotationStr().equals(Strings.autoValueAnnotation)) { if (Config.getInstant().isFieldPrivateMode()) { createGetAndSetMethod(mFactory, getFields(), mClass); } } } private void createExtraMethod(PsiElementFactory mFactory, PsiClass mClass) { if (Config.getInstant().isObjectFromData()) { createMethod(mFactory, Config.getInstant().getObjectFromDataStr().replace("$ClassName$", mClass.getName()).trim(), mClass); } if (Config.getInstant().isObjectFromData1()) { createMethod(mFactory, Config.getInstant().getObjectFromDataStr1().replace("$ClassName$", mClass.getName()).trim(), mClass); } if (Config.getInstant().isArrayFromData()) { createMethod(mFactory, Config.getInstant().getArrayFromDataStr().replace("$ClassName$", mClass.getName()).trim(), mClass); } if (Config.getInstant().isArrayFromData1()) { createMethod(mFactory, Config.getInstant().getArrayFromData1Str().replace("$ClassName$", mClass.getName()).trim(), mClass); } if (Config.getInstant().getAnnotationStr().equals(Strings.autoValueAnnotation)) { createMethod(mFactory, Strings.autoValueMethodTemplate.replace("$className$", mClass.getName()).trim(), mClass); } } public void generateClass(PsiElementFactory mFactory, PsiClass parentClass) { if (isGenerate()) { String classContent = "public static class " + className + "{}"; if (Config.getInstant().getAnnotationStr().equals(Strings.autoValueAnnotation)) { classContent = "public abstract static class " + className + "{}"; } PsiClass subClass = mFactory.createClassFromText(classContent, null).getInnerClasses()[0]; for (FieldEntity fieldEntity : getFields()) { if (fieldEntity instanceof InnerClassEntity) { ((InnerClassEntity) fieldEntity).generateSupperFiled(mFactory, subClass); ((InnerClassEntity) fieldEntity).setFieldTypeSuffix(getClassFieldType()); ((InnerClassEntity) fieldEntity).generateClass(mFactory, subClass); } else { fieldEntity.generateFiled(mFactory, subClass, this); } } configGetterAndSetter(mFactory, subClass); createExtraMethod(mFactory, subClass); parentClass.add(subClass); if (Config.getInstant().getAnnotationStr().equals(Strings.jackAnnotation)) { // subClass = parentClass.findInnerClassByName(className, false); // if (subClass != null) { // PsiModifierList modifierList = subClass.getModifierList(); // PsiAnnotation annotationFromText = // mFactory.createAnnotationFromText("@com.fasterxml.jackson.annotation.JsonIgnoreProperties(ignoreUnknown = true)", subClass); // PsiElement firstChild = modifierList.getFirstChild(); // modifierList.addBefore(annotationFromText, firstChild); } else if (Config.getInstant().getAnnotationStr().equals(Strings.loganSquareAnnotation)) { subClass = parentClass.findInnerClassByName(className, false); if (subClass != null) { PsiModifierList modifierList = subClass.getModifierList(); PsiAnnotation annotationFromText = mFactory.createAnnotationFromText("@com.bluelinelabs.logansquare.annotation.JsonObject", subClass); PsiElement firstChild = modifierList.getFirstChild(); modifierList.addBefore(annotationFromText, firstChild); } } } } public void generateSupperFiled(PsiElementFactory mFactory, PsiClass prentClass) { if (isGenerate()) { StringBuilder filedSb = new StringBuilder(); String filedName = getGenerateFieldName(); if (CheckUtil.getInstant().checkKeyWord(filedName)) { filedName = filedName + "X"; } if (!TextUtils.isEmpty(this.getExtra())) { filedSb.append(this.getExtra()).append("\n"); this.setExtra(null); } if (!filedName.equals(getKey()) || Config.getInstant().isUseSerializedName()) { filedSb.append(Config.getInstant().geFullNameAnnotation().replaceAll("\\{filed\\}", getKey())); } if (Config.getInstant().isFieldPrivateMode()) { filedSb.append("private "); } else { filedSb.append("public "); } filedSb.append(getClassFieldType()).append(" ").append(filedName).append(" ; "); prentClass.add(mFactory.createFieldFromText(filedSb.toString(), prentClass)); } } private void createMethod(PsiElementFactory mFactory, String method, PsiClass cla) { cla.add(mFactory.createMethodFromText(method, cla)); } public String captureName(String name) { if (name.length() > 0) { name = name.substring(0, 1).toUpperCase() + name.substring(1); } return name; } private void createGetAndSetMethod(PsiElementFactory mFactory, List<? extends FieldEntity> fields, PsiClass mClass) { for (FieldEntity field1 : fields) { if (field1.isGenerate()) { String field = field1.getGenerateFieldName(); String typeStr = field1.getRealType(); if (Config.getInstant().isUseFiledNamePrefix()) { String temp = field.replaceAll("^" + Config.getInstant().getFiledNamePreFixStr(), ""); if (!TextUtils.isEmpty(temp)) { field = temp; } } if (typeStr.equals("boolean") || typeStr.equals("Boolean")) { String method = "public ".concat(typeStr).concat(" is").concat( captureName(field)).concat("() { return ").concat( field1.getGenerateFieldName()).concat(" ;} "); mClass.add(mFactory.createMethodFromText(method, mClass)); } else { String method = "public " .concat(typeStr).concat( " get").concat( captureName(field)).concat( "() { return ").concat( field1.getGenerateFieldName()).concat(" ;} "); mClass.add(mFactory.createMethodFromText(method, mClass)); } String arg = field; if (Config.getInstant().isUseFiledNamePrefix()) { String temp = field.replaceAll("^" + Config.getInstant().getFiledNamePreFixStr(), ""); if (!TextUtils.isEmpty(temp)) { field = temp; arg = field; if (arg.length() > 0) { if (arg.length() > 1) { arg = (arg.charAt(0) + "").toLowerCase() + arg.substring(1); } else { arg = arg.toLowerCase(); } } } } String method = "public void set".concat(captureName(field)).concat("( ").concat(typeStr).concat(" ").concat(arg).concat(") { "); if (field1.getGenerateFieldName().equals(arg)) { method = method.concat("this.").concat(field1.getGenerateFieldName()).concat(" = ").concat(arg).concat(";} "); } else { method = method.concat(field1.getGenerateFieldName()).concat(" = ").concat(arg).concat(";} "); } mClass.add(mFactory.createMethodFromText(method, mClass)); } } } }
package org.jabref.logic.importer.fetcher; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Optional; import org.jabref.logic.importer.EntryBasedFetcher; import org.jabref.logic.importer.FetcherException; import org.jabref.logic.importer.ParserResult; import org.jabref.logic.importer.fileformat.MrDLibImporter; import org.jabref.logic.l10n.Localization; import org.jabref.logic.net.URLDownload; import org.jabref.logic.util.Version; import org.jabref.model.database.BibDatabase; import org.jabref.model.entry.BibEntry; import org.jabref.model.entry.FieldName; import org.jabref.preferences.JabRefPreferences; import org.apache.http.client.utils.URIBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class is responsible for getting the recommendations from Mr. DLib */ public class MrDLibFetcher implements EntryBasedFetcher { private static final Logger LOGGER = LoggerFactory.getLogger(MrDLibFetcher.class); private static final String NAME = "MDL_FETCHER"; private static final String MDL_JABREF_PARTNER_ID = "1"; private static final String MDL_URL = "api.mr-dlib.org"; private static final String DEFAULT_MRDLIB_ERROR_MESSAGE = Localization.lang("Error while fetching recommendations from Mr.DLib."); private final String LANGUAGE; private final Version VERSION; private String heading; private String description; private String recommendationSetId; public MrDLibFetcher(String language, Version version) { LANGUAGE = language; VERSION = version; } @Override public String getName() { return NAME; } @Override public List<BibEntry> performSearch(BibEntry entry) throws FetcherException { Optional<String> title = entry.getLatexFreeField(FieldName.TITLE); if (title.isPresent()) { String response = makeServerRequest(title.get()); MrDLibImporter importer = new MrDLibImporter(); ParserResult parserResult; try { if (importer.isRecognizedFormat(response)) { parserResult = importer.importDatabase(response); heading = importer.getRecommendationsHeading(); description = importer.getRecommendationsDescription(); recommendationSetId = importer.getRecommendationSetId(); } else { // For displaying An ErrorMessage description = DEFAULT_MRDLIB_ERROR_MESSAGE; BibDatabase errorBibDataBase = new BibDatabase(); parserResult = new ParserResult(errorBibDataBase); } } catch (IOException e) { LOGGER.error(e.getMessage(), e); throw new FetcherException("JSON Parser IOException."); } return parserResult.getDatabase().getEntries(); } else { // without a title there is no reason to ask MrDLib return new ArrayList<>(0); } } public String getHeading() { return heading; } public String getDescription() { return description; } /** * Contact the server with the title of the selected item * * @param queryByTitle: The query holds the title of the selected entry. Used to make a query to the MDL Server * @return Returns the server response. This is an XML document as a String. */ private String makeServerRequest(String queryByTitle) throws FetcherException { try { URLDownload urlDownload = new URLDownload(constructQuery(queryByTitle)); URLDownload.bypassSSLVerification(); String response = urlDownload.asString(); //Conversion of < and > response = response.replaceAll("&gt;", ">"); response = response.replaceAll("&lt;", "<"); return response; } catch (IOException e) { throw new FetcherException("Problem downloading", e); } } /** * Constructs the query based on title of the BibEntry. Adds statistical stuff to the url. * * @param queryWithTitle: the title of the bib entry. * @return the string used to make the query at mdl server */ private String constructQuery(String queryWithTitle) { // The encoding does not work for / so we convert them by our own queryWithTitle = queryWithTitle.replaceAll("/", " "); URIBuilder builder = new URIBuilder(); builder.setScheme("http"); builder.setHost(MDL_URL); builder.setPath("/v2/documents/" + queryWithTitle + "/related_documents"); builder.addParameter("partner_id", MDL_JABREF_PARTNER_ID); builder.addParameter("app_id", "jabref_desktop"); builder.addParameter("app_version", VERSION.getFullVersion()); JabRefPreferences prefs = JabRefPreferences.getInstance(); if (prefs.getBoolean(JabRefPreferences.SEND_LANGUAGE_DATA)) { builder.addParameter("app_lang", LANGUAGE); } if (prefs.getBoolean(JabRefPreferences.SEND_OS_DATA)) { builder.addParameter("os", System.getProperty("os.name")); } if (prefs.getBoolean(JabRefPreferences.SEND_TIMEZONE_DATA)) { builder.addParameter("timezone", Calendar.getInstance().getTimeZone().getID()); } try { URI uri = builder.build(); LOGGER.trace("Request: " + uri.toString()); return uri.toString(); } catch (URISyntaxException e) { LOGGER.error(e.getMessage(), e); } return ""; } }
package org.jboss.netty.handler.timeout; import java.util.concurrent.TimeUnit; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.LifeCycleAwareChannelHandler; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.channel.WriteCompletionEvent; import org.jboss.netty.util.ExternalResourceReleasable; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev$, $Date$ */ @ChannelPipelineCoverage("one") public class IdlenessHandler extends SimpleChannelUpstreamHandler implements LifeCycleAwareChannelHandler, ExternalResourceReleasable { static final ReadTimeoutException EXCEPTION = new ReadTimeoutException(); final Timer timer; final long readerIdleTimeMillis; volatile Timeout readerIdleTimeout; private volatile ReaderIdleTimeoutTask readerIdleTimeoutTask; volatile long lastReadTime; final long writerIdleTimeMillis; volatile Timeout writerIdleTimeout; private volatile WriterIdleTimeoutTask writerIdleTimeoutTask; volatile long lastWriteTime; public IdlenessHandler( Timer timer, long readerIdleTimeMillis, long writerIdleTimeMillis) { this(timer, readerIdleTimeMillis, writerIdleTimeMillis, TimeUnit.MILLISECONDS); } public IdlenessHandler( Timer timer, long readerIdleTime, long writerIdleTime, TimeUnit unit) { if (timer == null) { throw new NullPointerException("timer"); } if (unit == null) { throw new NullPointerException("unit"); } if (readerIdleTime < 0) { throw new IllegalArgumentException( "readerIdleTime must not be less than 0: " + readerIdleTime); } if (writerIdleTime < 0) { throw new IllegalArgumentException( "writerIdleTime must not be less than 0: " + writerIdleTime); } this.timer = timer; readerIdleTimeMillis = unit.toMillis(readerIdleTime); writerIdleTimeMillis = unit.toMillis(writerIdleTime); } public void releaseExternalResources() { timer.stop(); } public void beforeAdd(ChannelHandlerContext ctx) throws Exception { initialize(ctx); } public void afterAdd(ChannelHandlerContext ctx) throws Exception { // NOOP } public void beforeRemove(ChannelHandlerContext ctx) throws Exception { destroy(); } public void afterRemove(ChannelHandlerContext ctx) throws Exception { // NOOP } @Override public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { initialize(ctx); ctx.sendUpstream(e); } @Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { destroy(); ctx.sendUpstream(e); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { lastReadTime = System.currentTimeMillis(); ctx.sendUpstream(e); } @Override public void writeComplete(ChannelHandlerContext ctx, WriteCompletionEvent e) throws Exception { if (e.getWrittenAmount() > 0) { lastWriteTime = System.currentTimeMillis(); } ctx.sendUpstream(e); } private void initialize(ChannelHandlerContext ctx) { lastReadTime = lastWriteTime = System.currentTimeMillis(); readerIdleTimeoutTask = new ReaderIdleTimeoutTask(ctx); writerIdleTimeoutTask = new WriterIdleTimeoutTask(ctx); readerIdleTimeout = timer.newTimeout(readerIdleTimeoutTask, readerIdleTimeMillis, TimeUnit.MILLISECONDS); writerIdleTimeout = timer.newTimeout(writerIdleTimeoutTask, writerIdleTimeMillis, TimeUnit.MILLISECONDS); } private void destroy() { if (readerIdleTimeout != null) { readerIdleTimeout.cancel(); } if (writerIdleTimeout != null) { writerIdleTimeout.cancel(); } readerIdleTimeout = null; readerIdleTimeoutTask = null; writerIdleTimeout = null; writerIdleTimeoutTask = null; } private final class ReaderIdleTimeoutTask implements TimerTask { private final ChannelHandlerContext ctx; ReaderIdleTimeoutTask(ChannelHandlerContext ctx) { this.ctx = ctx; } public void run(Timeout timeout) throws Exception { if (timeout.isCancelled()) { return; } if (!ctx.getChannel().isOpen()) { return; } long currentTime = System.currentTimeMillis(); long lastReadTime = IdlenessHandler.this.lastReadTime; long nextDelay = readerIdleTimeMillis - (currentTime - lastReadTime); if (nextDelay <= 0) { // Reader is idle - set a new timeout and notify the callback. readerIdleTimeout = timer.newTimeout(this, readerIdleTimeMillis, TimeUnit.MILLISECONDS); ctx.sendUpstream(new DefaultIdlenessEvent( ctx.getChannel(), lastReadTime, lastWriteTime, readerIdleTimeMillis, writerIdleTimeMillis)); } else { // Read occurred before the timeout - set a new timeout with shorter delay. readerIdleTimeout = timer.newTimeout(this, nextDelay, TimeUnit.MILLISECONDS); } } } private final class WriterIdleTimeoutTask implements TimerTask { private final ChannelHandlerContext ctx; WriterIdleTimeoutTask(ChannelHandlerContext ctx) { this.ctx = ctx; } public void run(Timeout timeout) throws Exception { if (timeout.isCancelled()) { return; } if (!ctx.getChannel().isOpen()) { return; } long currentTime = System.currentTimeMillis(); long lastWriteTime = IdlenessHandler.this.lastWriteTime; long nextDelay = writerIdleTimeMillis - (currentTime - lastWriteTime); if (nextDelay <= 0) { // Writer is idle - set a new timeout and notify the callback. writerIdleTimeout = timer.newTimeout(this, writerIdleTimeMillis, TimeUnit.MILLISECONDS); ctx.sendUpstream(new DefaultIdlenessEvent( ctx.getChannel(), lastReadTime, lastWriteTime, readerIdleTimeMillis, writerIdleTimeMillis)); } else { // Write occurred before the timeout - set a new timeout with shorter delay. writerIdleTimeout = timer.newTimeout(this, nextDelay, TimeUnit.MILLISECONDS); } } } }
package org.mitre.synthea.modules; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.mitre.synthea.helpers.Config; import org.mitre.synthea.modules.HealthRecord.CarePlan; import org.mitre.synthea.modules.HealthRecord.Code; import org.mitre.synthea.modules.HealthRecord.Encounter; import org.mitre.synthea.modules.HealthRecord.Medication; import org.mitre.synthea.modules.HealthRecord.Procedure; import org.mitre.synthea.world.Location; import org.mitre.synthea.world.Provider; public class CommunityHealthWorker extends Provider { public static final String LUNG_CANCER_SCREENING = "Lung cancer screening"; public static final String TOBACCO_SCREENING = "Tobacco screening"; public static final String ALCOHOL_SCREENING = "Alcohol screening"; public static final String OBESITY_SCREENING = "Obesity screening"; public static final String BLOOD_PRESSURE_SCREENING = "Blood pressure screening"; public static final String DIABETES_SCREENING = "Diabetes screening"; public static final String COLORECTAL_CANCER_SCREENING = "Colorectal cancer screening"; public static final String PREECLAMPSIA_SCREENING = "Preeclampsia screening"; public static final String OSTEOPOROSIS_SCREENING = "Osteoporosis screening"; public static final String ASPIRIN_MEDICATION = "Aspirin Medication"; public static final String PREECLAMPSIA_ASPIRIN = "Preeclampsia aspirin"; public static final String EXERCISE_PT_INJURY_SCREENING = "Fall prevention in older adults: Exercise or physical therapy"; public static final String VITAMIN_D_INJURY_SCREENING = "Fall prevention in older adults: Vitamin D"; public static final String DIET_PHYSICAL_ACTIVITY = "Diet and physical activity counseling"; public static final String STATIN_MEDICATION = "Statin preventive medication"; public static final String CITY = "city"; public static final String DEPLOYMENT = "deployment"; public static final String DEPLOYMENT_COMMUNITY = "community"; public static final String DEPLOYMENT_EMERGENCY = "emergency"; public static final String DEPLOYMENT_POSTDISCHARGE = "postdischarge"; public static int cost = Integer.parseInt(Config.get("generate.chw.cost")); public static int budget = Integer.parseInt(Config.get("generate.chw.budget")); public static double community = Double.parseDouble(Config.get("generate.chw.community", "0.50")); public static double emergency = Double.parseDouble(Config.get("generate.chw.emergency", "0.25")); public static double postdischarge = Double.parseDouble(Config.get("generate.chw.postdischarge", "0.25")); public static int yearIntroduced = Integer.parseInt(Config.get("generate.chw.year_introduced")); public static Map<String,List<CommunityHealthWorker>> workers = generateWorkers(); private CommunityHealthWorker(String deploymentType) { // don't allow anyone else to instantiate this attributes.put(CommunityHealthWorker.ALCOHOL_SCREENING, Boolean.parseBoolean(Config.get("chw.alcohol_screening"))); attributes.put(CommunityHealthWorker.ASPIRIN_MEDICATION, Boolean.parseBoolean(Config.get("chw.aspirin_medication"))); attributes.put(CommunityHealthWorker.BLOOD_PRESSURE_SCREENING, Boolean.parseBoolean(Config.get("chw.blood_pressure_screening"))); attributes.put(CommunityHealthWorker.COLORECTAL_CANCER_SCREENING, Boolean.parseBoolean(Config.get("chw.colorectal_cancer_screening"))); attributes.put(CommunityHealthWorker.DIABETES_SCREENING, Boolean.parseBoolean(Config.get("chw.diabetes_screening"))); attributes.put(CommunityHealthWorker.DIET_PHYSICAL_ACTIVITY, Boolean.parseBoolean(Config.get("chw.diet_physical_activity"))); attributes.put(CommunityHealthWorker.EXERCISE_PT_INJURY_SCREENING, Boolean.parseBoolean(Config.get("chw.exercise_pt_injury_screening"))); attributes.put(CommunityHealthWorker.LUNG_CANCER_SCREENING, Boolean.parseBoolean(Config.get("chw.lung_cancer_screening"))); attributes.put(CommunityHealthWorker.OBESITY_SCREENING, Boolean.parseBoolean(Config.get("chw.obesity_screening"))); attributes.put(CommunityHealthWorker.OSTEOPOROSIS_SCREENING, Boolean.parseBoolean(Config.get("chw.osteoporosis_screening"))); attributes.put(CommunityHealthWorker.PREECLAMPSIA_ASPIRIN, Boolean.parseBoolean(Config.get("chw.preeclampsia_aspirin"))); attributes.put(CommunityHealthWorker.PREECLAMPSIA_SCREENING, Boolean.parseBoolean(Config.get("chw.preeclampsia_screening"))); attributes.put(CommunityHealthWorker.STATIN_MEDICATION, Boolean.parseBoolean(Config.get("chw.statin_medication"))); attributes.put(CommunityHealthWorker.TOBACCO_SCREENING, Boolean.parseBoolean(Config.get("chw.tobacco_screening"))); attributes.put(CommunityHealthWorker.VITAMIN_D_INJURY_SCREENING, Boolean.parseBoolean(Config.get("chw.vitamin_d_injury_screening"))); Location.assignCity(this); attributes.put(DEPLOYMENT, deploymentType); //resourceID so that it's the same as Provider. attributes.put("resourceID", UUID.randomUUID().toString()); attributes.put("name", "CHW providing " + deploymentType + " services in " + attributes.get(CITY)); } private static Map<String,List<CommunityHealthWorker>> generateWorkers() { Map<String,List<CommunityHealthWorker>> workers = new HashMap<String,List<CommunityHealthWorker>>(); int numWorkers = budget / cost; int numWorkersGenerated = 0; CommunityHealthWorker worker; for(int i=0; i < Math.round(numWorkers * community); i++) { worker = new CommunityHealthWorker(DEPLOYMENT_COMMUNITY); String city = (String) worker.attributes.get(CITY); if(!workers.containsKey(city)) { workers.put(city, new ArrayList<CommunityHealthWorker>()); } workers.get(city).add(worker); numWorkersGenerated++; } for(int i=0; i < Math.round(numWorkers * emergency); i++) { worker = new CommunityHealthWorker(DEPLOYMENT_EMERGENCY); String city = (String) worker.attributes.get(CITY); if(!workers.containsKey(city)) { workers.put(city, new ArrayList<CommunityHealthWorker>()); } workers.get(city).add(worker); numWorkersGenerated++; } for(int i=numWorkersGenerated; i < numWorkers; i++) { worker = new CommunityHealthWorker(DEPLOYMENT_POSTDISCHARGE); String city = (String) worker.attributes.get(CITY); if(!workers.containsKey(city)) { workers.put(city, new ArrayList<CommunityHealthWorker>()); } workers.get(city).add(worker); } return workers; } public static CommunityHealthWorker findNearbyCHW(Person person, long time, String deploymentType) { int year = Utilities.getYear(time); if (year < yearIntroduced) { // CHWs not introduced to the system yet return null; } CommunityHealthWorker worker = null; String city = (String) person.attributes.get(Person.CITY); double probability = 0.0; switch(deploymentType) { case DEPLOYMENT_COMMUNITY: if(workers.containsKey(city)) { probability = (double)(workers.get(city).size()) / (double)Location.getPopulation(city); } break; case DEPLOYMENT_EMERGENCY: probability = 0.9; break; case DEPLOYMENT_POSTDISCHARGE: probability = 0.9; break; } if(person.rand() < probability && workers.containsKey(city)) { List<CommunityHealthWorker> candidates = workers.get(city).stream() .filter(p -> p.attributes.get(DEPLOYMENT).equals(deploymentType)) .collect(Collectors.toList()); if(!candidates.isEmpty()) { worker = candidates.get((int)person.rand(0, candidates.size()-1)); } } return worker; } /** * Check whether this CHW offers the given service. * @param service Service name * * @return true if the service is offered by this CHW */ public boolean offers(String service) { return (boolean) this.attributes.getOrDefault(service, false); } public void performEncounter(Person person, long time, String deploymentType) { // encounter class doesn't fit into the FHIR-prescribed set // so we use our own "community" encounter class Encounter enc = person.record.encounterStart(time, "community"); enc.chw = this; // TODO - different codes based on different services offered? enc.codes.add( new Code("SNOMED-CT","389067005","Community health procedure") ); this.incrementEncounters(deploymentType, Utilities.getYear(time)); int chw_interventions = (int) person.attributes.getOrDefault(Person.CHW_INTERVENTION, 0); chw_interventions++; person.attributes.put(Person.CHW_INTERVENTION, chw_interventions); tobaccoScreening(person, time); alcoholScreening(person, time); lungCancerScreening(person, time); bloodPressureScreening(person, time); dietPhysicalActivityCounseling(person, time); obesityScreening(person, time); aspirinMedication(person, time); statinMedication(person, time); fallsPreventionExercise(person, time); fallsPreventionVitaminD(person, time); osteoporosisScreening(person, time); double adherence_chw_delta = Double.parseDouble( Config.get("lifecycle.aherence.chw_delta", "0.3")); double probability = (double) person.attributes.get(LifecycleModule.ADHERENCE_PROBABILITY); probability += (adherence_chw_delta); person.attributes.put(LifecycleModule.ADHERENCE_PROBABILITY, probability); enc.stop = time + TimeUnit.MINUTES.toMillis(35); // encounter lasts 35 minutes on avg } // INDIVIDUAL SCREENINGS // //TODO published studies and numbers to support impact of CHW on various conditions //The USPSTF recommends that clinicians ask all adults about tobacco use, advise them to stop using tobacco, and provide private void tobaccoScreening(Person person, long time) { int age = person.ageInYears(time); if(this.offers(TOBACCO_SCREENING) && age >= 18) { Procedure ct = person.record.procedure(time, "Tobacco usage screening (procedure)"); ct.codes.add(new Code("SNOMED-CT","171209009","Tobacco usage screening (procedure)")); double quit_smoking_chw_delta = Double.parseDouble( Config.get("lifecycle.quit_smoking.chw_delta", "0.3")); double smoking_duration_factor_per_year = Double.parseDouble( Config.get("lifecycle.quit_smoking.smoking_duration_factor_per_year", "1.0")); double probability = (double) person.attributes.get(LifecycleModule.QUIT_SMOKING_PROBABILITY); int numberOfYearsSmoking = (int) person.ageInYears(time) - 15; probability += (quit_smoking_chw_delta / (smoking_duration_factor_per_year * numberOfYearsSmoking)); person.attributes.put(LifecycleModule.QUIT_SMOKING_PROBABILITY, probability); if(person.attributes.containsKey("cardio_risk")){ double cardioRisk = (double) person.attributes.get("cardio_risk"); cardioRisk = cardioRisk / (4 + quit_smoking_chw_delta); person.attributes.put("cardio_risk", Utilities.convertRiskToTimestep(cardioRisk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("atrial_fibrillation_risk")){ double af_risk = (double) person.attributes.get("atrial_fibrillation_risk"); af_risk = af_risk / (4 + quit_smoking_chw_delta); person.attributes.put("atrial_fibrillation_risk", Utilities.convertRiskToTimestep(af_risk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("stroke_risk")){ double stroke_risk = (double) person.attributes.get("stroke_risk"); stroke_risk = stroke_risk / (4 + quit_smoking_chw_delta); person.attributes.put("stroke_risk", Utilities.convertRiskToTimestep(stroke_risk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("stroke_points")){ int stroke_points = (int) person.attributes.get("stroke_points"); stroke_points = stroke_points - 2; person.attributes.put("stroke_points", Math.max(0, stroke_points)); } } } //The USPSTF recommends that clinicians screen adults age 18 years or older for alcohol misuse and provide persons engaged //in risky or hazardous drinking with brief behavioral counseling interventions to reduce alcohol misuse. private void alcoholScreening(Person person, long time) { int age = person.ageInYears(time); if(this.offers(ALCOHOL_SCREENING) && age >= 18) { Procedure ct = person.record.procedure(time, "Screening for alcohol abuse (procedure)"); ct.codes.add(new Code("SNOMED-CT","713107002","Screening for alcohol abuse (procedure)")); double quit_alcoholism_chw_delta = Double.parseDouble( Config.get("lifecycle.quit_alcoholism.chw_delta", "0.3")); double alcoholism_duration_factor_per_year = Double.parseDouble( Config.get("lifecycle.quit_alcoholism.alcoholism_duration_factor_per_year", "1.0")); if(person.attributes.containsKey("cardio_risk")){ double cardioRisk = (double) person.attributes.get("cardio_risk"); cardioRisk = cardioRisk / (4 + quit_alcoholism_chw_delta); person.attributes.put("cardio_risk", Utilities.convertRiskToTimestep(cardioRisk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("atrial_fibrillation_risk")){ double af_risk = (double) person.attributes.get("atrial_fibrillation_risk"); af_risk = af_risk / (4 + quit_alcoholism_chw_delta); person.attributes.put("atrial_fibrillation_risk", Utilities.convertRiskToTimestep(af_risk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("stroke_risk")){ double stroke_risk = (double) person.attributes.get("stroke_risk"); stroke_risk = stroke_risk / (4 + quit_alcoholism_chw_delta); person.attributes.put("stroke_risk", Utilities.convertRiskToTimestep(stroke_risk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("stroke_points")){ int stroke_points = (int) person.attributes.get("stroke_points"); stroke_points = stroke_points - 2; person.attributes.put("stroke_points", Math.max(0, stroke_points)); } if((boolean) person.attributes.getOrDefault(Person.ALCOHOLIC, false)){ Procedure ct2 = person.record.procedure(time, "Alcoholism counseling (procedure)"); ct2.codes.add(new Code("SNOMED-CT","24165007","Alcoholism counseling (procedure)")); double probability = (double) person.attributes.get(LifecycleModule.QUIT_ALCOHOLISM_PROBABILITY); int numberOfYearsAlcoholic = (int) person.ageInYears(time) - 25; probability += (quit_alcoholism_chw_delta / (alcoholism_duration_factor_per_year * numberOfYearsAlcoholic)); person.attributes.put(LifecycleModule.QUIT_ALCOHOLISM_PROBABILITY, probability); } } } // The USPSTF recommends annual screening for lung cancer with low-dose computed tomography // in adults ages 55 to 80 years who have a 30 pack-year smoking history and currently smoke // or have quit within the past 15 years. // Screening should be discontinued once a person has not smoked for 15 years or // develops a health problem that substantially limits life expectancy or the ability or willingness to have curative lung surgery. private void lungCancerScreening(Person person, long time) { int age = person.ageInYears(time); boolean isSmoker = (boolean) person.attributes.getOrDefault(Person.SMOKER, false); int quitSmokingAge = (int)person.attributes.getOrDefault(LifecycleModule.QUIT_SMOKING_AGE, 0); int yearsSinceQuitting = age - quitSmokingAge; // TODO: 30-year pack history if (this.offers(LUNG_CANCER_SCREENING) && age >= 55 && age <= 80 && (isSmoker || yearsSinceQuitting <= 15)) { Procedure ct = person.record.procedure(time, "Low dose computed tomography of thorax (procedure)"); ct.codes.add(new Code("SNOMED-CT","16334891000119106","Low dose computed tomography of thorax")); if((boolean) person.attributes.getOrDefault("lung_cancer", false)) { person.attributes.put("probability_of_lung_cancer_treatment", 1.0); // screening caught lung cancer, send them to treatment } } } //The USPSTF recommends screening for high blood pressure in adults aged 18 years or older. //The USPSTF recommends obtaining measurements outside of the clinical setting for diagnostic //confirmation before starting treatment. private void bloodPressureScreening(Person person, long time){ if (this.offers(BLOOD_PRESSURE_SCREENING)){ //TODO metabolic syndrome module Procedure ct = person.record.procedure(time, "Blood pressure screening - first call (procedure)"); ct.codes.add(new Code("SNOMED-CT","185665008","Blood pressure screening - first call (procedure)")); double blood_pressure_chw_delta = Double.parseDouble( Config.get("lifecycle.blood_pressure.chw_delta", "0.1")); if(person.attributes.containsKey("cardio_risk")){ double cardioRisk = (double) person.attributes.get("cardio_risk"); cardioRisk = cardioRisk / (4 + blood_pressure_chw_delta); person.attributes.put("cardio_risk", Utilities.convertRiskToTimestep(cardioRisk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("atrial_fibrillation_risk")){ double af_risk = (double) person.attributes.get("atrial_fibrillation_risk"); af_risk = af_risk / (4 + blood_pressure_chw_delta); person.attributes.put("atrial_fibrillation_risk", Utilities.convertRiskToTimestep(af_risk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("stroke_risk")){ double stroke_risk = (double) person.attributes.get("stroke_risk"); stroke_risk = stroke_risk / (4 + blood_pressure_chw_delta); person.attributes.put("stroke_risk", Utilities.convertRiskToTimestep(stroke_risk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("stroke_points")){ int stroke_points = (int) person.attributes.get("stroke_points"); stroke_points = stroke_points - 2; person.attributes.put("stroke_points", Math.max(0, stroke_points)); } } } //The USPSTF recommends offering or referring adults who are overweight or obese and have //additional cardiovascular disease (CVD) risk factors to intensive behavioral counseling //interventions to promote a healthful diet and physical activity for CVD prevention. private void dietPhysicalActivityCounseling(Person person, long time){ int age = person.ageInYears(time); if (this.offers(DIET_PHYSICAL_ACTIVITY) && age >=18 && person.getVitalSign(VitalSign.BMI) >= 25.0){ //TODO metabolic syndrome module, colorectal cancer module // only for adults who have CVD risk factors // the exact threshold for CVD risk factors can be determined later double diet_physical_activity_chw_delta = Double.parseDouble( Config.get("lifecycle.diet_physical_activity.chw_delta", "0.1")); if(person.attributes.containsKey("cardio_risk")){ if( person.attributes.get(Person.GENDER).equals("M") && (double)person.attributes.get("cardio_risk") > .0000002){ Procedure ct = person.record.procedure(time, "Referral to physical activity program (procedure)"); ct.codes.add(new Code("SNOMED-CT","390893007","Referral to physical activity program (procedure)")); Procedure ct2 = person.record.procedure(time, "Healthy eating education (procedure)"); ct2.codes.add(new Code("SNOMED-CT","699849008","Healthy eating education (procedure)")); double cardioRisk = (double) person.attributes.get("cardio_risk"); cardioRisk = cardioRisk / (4 + diet_physical_activity_chw_delta); person.attributes.put("cardio_risk", Utilities.convertRiskToTimestep(cardioRisk, TimeUnit.DAYS.toMillis(3650))); } if( person.attributes.get(Person.GENDER).equals("F") && (double)person.attributes.get("cardio_risk") > .0000004){ Procedure ct = person.record.procedure(time, "Referral to physical activity program (procedure)"); ct.codes.add(new Code("SNOMED-CT","390893007","Referral to physical activity program (procedure)")); Procedure ct2 = person.record.procedure(time, "Healthy eating education (procedure)"); ct2.codes.add(new Code("SNOMED-CT","699849008","Healthy eating education (procedure)")); double cardioRisk = (double) person.attributes.get("cardio_risk"); cardioRisk = cardioRisk / (4 + diet_physical_activity_chw_delta); person.attributes.put("cardio_risk", Utilities.convertRiskToTimestep(cardioRisk, TimeUnit.DAYS.toMillis(3650))); } } if(person.attributes.containsKey("atrial_fibrillation_risk") && (double) person.attributes.get("atrial_fibrillation_risk") > .00000003){ Procedure ct = person.record.procedure(time, "Referral to physical activity program (procedure)"); ct.codes.add(new Code("SNOMED-CT","390893007","Referral to physical activity program (procedure)")); Procedure ct2 = person.record.procedure(time, "Healthy eating education (procedure)"); ct2.codes.add(new Code("SNOMED-CT","699849008","Healthy eating education (procedure)")); double af_risk = (double) person.attributes.get("atrial_fibrillation_risk"); af_risk = af_risk / (4 + diet_physical_activity_chw_delta); person.attributes.put("atrial_fibrillation_risk", Utilities.convertRiskToTimestep(af_risk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("stroke_risk") && (double)person.attributes.get("stroke_risk") > .00000003){ Procedure ct = person.record.procedure(time, "Referral to physical activity program (procedure)"); ct.codes.add(new Code("SNOMED-CT","390893007","Referral to physical activity program (procedure)")); Procedure ct2 = person.record.procedure(time, "Healthy eating education (procedure)"); ct2.codes.add(new Code("SNOMED-CT","699849008","Healthy eating education (procedure)")); double stroke_risk = (double) person.attributes.get("stroke_risk"); stroke_risk = stroke_risk / (4 + diet_physical_activity_chw_delta); person.attributes.put("stroke_risk", Utilities.convertRiskToTimestep(stroke_risk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("stroke_points") && (int)person.attributes.get("stroke_points") > 3){ Procedure ct = person.record.procedure(time, "Referral to physical activity program (procedure)"); ct.codes.add(new Code("SNOMED-CT","390893007","Referral to physical activity program (procedure)")); Procedure ct2 = person.record.procedure(time, "Healthy eating education (procedure)"); ct2.codes.add(new Code("SNOMED-CT","699849008","Healthy eating education (procedure)")); int stroke_points = (int) person.attributes.get("stroke_points"); stroke_points = stroke_points - 2; person.attributes.put("stroke_points", Math.max(0, stroke_points)); } } } //The USPSTF recommends screening all adults for obesity. Clinicians should offer or refer //patients with a body mass index of 30 kg/m2 or higher to intensive, multicomponent behavioral interventions. private void obesityScreening(Person person, long time){ int age = person.ageInYears(time); if (this.offers(OBESITY_SCREENING) && age >= 18){ //TODO metabolic syndrome module, diabetes Procedure ct = person.record.procedure(time, "Obesity screening (procedure)"); ct.codes.add(new Code("SNOMED-CT","268551005","Obesity screening (procedure)")); double obesity_chw_delta = Double.parseDouble( Config.get("lifecycle.obesity_screening.chw_delta", "0.1")); if(person.attributes.containsKey("cardio_risk")){ double cardioRisk = (double) person.attributes.get("cardio_risk"); cardioRisk = cardioRisk / (4 + obesity_chw_delta); person.attributes.put("cardio_risk", Utilities.convertRiskToTimestep(cardioRisk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("atrial_fibrillation_risk")){ double af_risk = (double) person.attributes.get("atrial_fibrillation_risk"); af_risk = af_risk / (4 + obesity_chw_delta); person.attributes.put("atrial_fibrillation_risk", Utilities.convertRiskToTimestep(af_risk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("stroke_risk")){ double stroke_risk = (double) person.attributes.get("stroke_risk"); stroke_risk = stroke_risk / (4 + obesity_chw_delta); person.attributes.put("stroke_risk", Utilities.convertRiskToTimestep(stroke_risk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("stroke_points")){ int stroke_points = (int) person.attributes.get("stroke_points"); stroke_points = stroke_points - 2; person.attributes.put("stroke_points", Math.max(0, stroke_points)); } if(person.getVitalSign(VitalSign.BMI) >= 30.0){ //"Clinicians should offer or refer patients with a body mass index of 30 kg/m2 or higher to intensive, multicomponent behavioral interventions."(USPSTF) Procedure ct2 = person.record.procedure(time, "Obesity monitoring invitation (procedure)"); ct2.codes.add(new Code("SNOMED-CT","310428009","Obesity monitoring invitation (procedure)")); } } } //The USPSTF recommends initiating low-dose aspirin use for the primary prevention of cardiovascular disease //and colorectal cancer in adults aged 50 to 59 years who have a 10% or greater 10-year cardiovascular risk, //are not at increased risk for bleeding, have a life expectancy of at least 10 years, and are willing to take low-dose aspirin daily for at least 10 years. private void aspirinMedication(Person person, long time){ int age = person.ageInYears(time); // From QualityofLifeModule: // life expectancy equation derived from IHME GBD 2015 Reference Life Table // 6E-5x^3 - 0.0054x^2 - 0.8502x + 86.16 // R^2 = 0.99978 double lifeExpectancy = ((0.00006 * Math.pow(age, 3)) - (0.0054 * Math.pow(age, 2)) - (0.8502 * age) + 86.16); double tenYearStrokeRisk = (double) person.attributes.get("cardio_risk") * 3650; if(this.offers(ASPIRIN_MEDICATION) && age >= 50 && age < 60 && tenYearStrokeRisk >= .1 && lifeExpectancy >= 10){ Procedure ct = person.record.procedure(time, "Administration of aspirin (procedure)"); ct.codes.add(new Code("SNOMED-CT","431463004","Administration of aspirin (procedure)")); double aspirin_chw_delta = Double.parseDouble( Config.get("lifecycle.aspirin_medication.chw_delta", "0.1")); if(person.attributes.containsKey("cardio_risk")){ double cardioRisk = (double) person.attributes.get("cardio_risk"); cardioRisk = cardioRisk / (4 + aspirin_chw_delta); person.attributes.put("cardio_risk", Utilities.convertRiskToTimestep(cardioRisk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("atrial_fibrillation_risk")){ double af_risk = (double) person.attributes.get("atrial_fibrillation_risk"); af_risk = af_risk / (4 + aspirin_chw_delta); person.attributes.put("atrial_fibrillation_risk", Utilities.convertRiskToTimestep(af_risk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("stroke_risk")){ double stroke_risk = (double) person.attributes.get("stroke_risk"); stroke_risk = stroke_risk / (4 + aspirin_chw_delta); person.attributes.put("stroke_risk", Utilities.convertRiskToTimestep(stroke_risk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("stroke_points")){ int stroke_points = (int) person.attributes.get("stroke_points"); stroke_points = stroke_points - 2; person.attributes.put("stroke_points", Math.max(0, stroke_points)); } } } //The USPSTF recommends that adults without a history of cardiovascular disease (CVD) (i.e., symptomatic coronary artery disease or ischemic stroke) //use a low- to moderate-dose statin for the prevention of CVD events and mortality when all of the following criteria are met: //1) they are ages 40 to 75 years; 2) they have 1 or more CVD risk factors (i.e., dyslipidemia, diabetes, hypertension, or smoking); //and 3) they have a calculated 10-year risk of a cardiovascular event of 10% or greater. Identification of dyslipidemia and calculation //of 10-year CVD event risk requires universal lipids screening in adults ages 40 to 75 years. private void statinMedication(Person person, long time){ int age = person.ageInYears(time); double tenYearStrokeRisk = (double) person.attributes.get("cardio_risk") * 3650; boolean riskFactors = false; if((boolean) person.attributes.getOrDefault(Person.SMOKER, false) || ((boolean) person.attributes.getOrDefault("diabetes", false)) || ((boolean) person.attributes.getOrDefault("hypertension", false))){ riskFactors = true; } //TODO check for history of CVD if(this.offers(STATIN_MEDICATION) && age >= 40 && age <= 75 && (riskFactors = true) && tenYearStrokeRisk >= .1){ // TODO may need a better snomed code Procedure ct = person.record.procedure(time, "Over the counter statin therapy (procedure)"); ct.codes.add(new Code("SNOMED-CT","414981001","Over the counter statin therapy (procedure)")); double statin_chw_delta = Double.parseDouble( Config.get("lifecycle.statin_medication.chw_delta", "0.1")); if(person.attributes.containsKey("cardio_risk")){ double cardioRisk = (double) person.attributes.get("cardio_risk"); cardioRisk = cardioRisk / (4 + statin_chw_delta); person.attributes.put("cardio_risk", Utilities.convertRiskToTimestep(cardioRisk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("atrial_fibrillation_risk")){ double af_risk = (double) person.attributes.get("atrial_fibrillation_risk"); af_risk = af_risk / (4 + statin_chw_delta); person.attributes.put("atrial_fibrillation_risk", Utilities.convertRiskToTimestep(af_risk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("stroke_risk")){ double stroke_risk = (double) person.attributes.get("stroke_risk"); stroke_risk = stroke_risk / (4 + statin_chw_delta); person.attributes.put("stroke_risk", Utilities.convertRiskToTimestep(stroke_risk, TimeUnit.DAYS.toMillis(3650))); } if(person.attributes.containsKey("stroke_points")){ int stroke_points = (int) person.attributes.get("stroke_points"); stroke_points = stroke_points - 2; person.attributes.put("stroke_points", Math.max(0, stroke_points)); } } } // The USPSTF recommends exercise or physical therapy to prevent falls // in community-dwelling adults age 65 years and older who are at increased risk for falls. private void fallsPreventionExercise(Person person, long time) { int age = person.ageInYears(time); if (this.offers(EXERCISE_PT_INJURY_SCREENING) && age > 65) { // technically this refers to patients receiving care in acute situations, ie hospitals // 1. History of falling; immediate or within 3 months : No = 0, Yes = 25 // 2. Secondary diagnosis : No = 0, Yes = 15 // 3. Ambulatory aid : Bed rest/nurse assist = 0, Crutches/cane/walker = 15, Furniture = 30 // 4. IV/Heparin Lock : No = 0, Yes = 20 // 5. Gait/Transferring : Normal/bedrest/immobile = 0, Weak = 10, Impaired = 20 // 6. Mental status : Oriented to own ability = 0, Forgets limitations = 15 // Risk Level | MFS Score | Action // No Risk | 0 - 24 | Basic Care // Low Risk | 25 - 50 | Standard Fall Prevention Interventions // High Risk | 51 - 135 | High Risk Fall Prevention Interventions // These #s may be tailored to specific patients or situations. int fallRisk = (int)person.rand(0, 60); if (fallRisk > 50) { CarePlan pt = person.record.careplanStart(time, "Physical therapy"); pt.codes.add(new Code("SNOMED-CT", "91251008", "Physical therapy")); } else if (fallRisk > 40) { CarePlan exercise = person.record.careplanStart(time, "Physical activity target light exercise"); exercise.codes.add(new Code("SNOMED-CT", "408580007", "Physical activity target light exercise")); } // CHW interaction will decrease probability of injuries by f(x) % (this adds careplan for exercise) } } // The USPSTF recommends vitamin D supplementation to prevent falls // in community-dwelling adults age 65 years and older who are at increased risk for falls. private void fallsPreventionVitaminD(Person person, long time) { // https://www.uspreventiveservicestaskforce.org/Page/Document/RecommendationStatementFinal/falls-prevention-in-older-adults-counseling-and-preventive-medication#consider int age = person.ageInYears(time); if (this.offers(VITAMIN_D_INJURY_SCREENING) && age > 65) { // CHW interaction will decrease probability of injuries by g(x) % (this adds medication for vitamin D) // According to the Institute of Medicine, the recommended daily allowance for vitamin D // is 600 IU for adults aged 51 to 70 years and 800 IU for adults older than 70 years 7. // The AGS recommends 800 IU per day for persons at increased risk for falls. if (!person.record.medicationActive("Cholecalciferol 600 UNT")) { Medication vitD = person.record.medicationStart(time, "Cholecalciferol 600 UNT"); vitD.codes.add(new Code("RxNorm", "994830", "Cholecalciferol 600 UNT")); } } } // The USPSTF recommends screening for osteoporosis in women age 65 years // and older and in younger women whose fracture risk is equal // to or greater than that of a 65-year-old white woman // who has no additional risk factors. private void osteoporosisScreening(Person person, long time) { int age = person.ageInYears(time); String gender = (String) person.attributes.get(Person.GENDER); boolean elevatedFractureRisk = (person.rand() < 0.05); boolean alreadyDiagnosedOsteoporosis = person.record.conditionActive("Osteoporosis (disorder)"); if (this.offers(OSTEOPOROSIS_SCREENING) && "F".equals(gender) && (age > 65 || elevatedFractureRisk) && !alreadyDiagnosedOsteoporosis) { // note that a lot of this already exists in the injuries module // if(CHW interaction and osteoprosis = true) then increase adherence Fosamax. // Modify injuries module to decrease the probability of injury if osteoporosis and adherence of Fosamax by foo(x) %. // bone density test // observation of density // diagnosis } } }
package org.moonlightcontroller.blocks; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.moonlightcontroller.aggregator.Tupple.Pair; import org.moonlightcontroller.aggregator.UUIDGenerator; import org.moonlightcontroller.exceptions.MergeException; import org.moonlightcontroller.processing.BlockClass; import org.moonlightcontroller.processing.IProcessingGraph; import org.moonlightcontroller.processing.ProcessingBlock; import org.openboxprotocol.protocol.HeaderMatch; import org.openboxprotocol.protocol.Priority; import com.google.common.collect.ImmutableList; public class HeaderClassifier extends ProcessingBlock implements IClassifierProcessingBlock { private List<? extends HeaderClassifierRule> rules; private Priority priority; public HeaderClassifier(String id, List<? extends HeaderClassifierRule> rules, Priority priority) { super(id); this.priority = priority; this.rules = rules; } @Override public Priority getPriority() { return this.priority; } public List<HeaderClassifierRule> getRules() { return ImmutableList.copyOf(this.rules); } public int getNumberOfRules() { return this.rules.size(); } @Override public BlockClass getBlockClass() { return BlockClass.BLOCK_CLASS_CLASSIFIER; } @Override protected ProcessingBlock spawn(String id) { return new HeaderClassifier(id, this.getRules(), this.priority); } @Override public boolean canMergeWith(IClassifierProcessingBlock other) { return (other instanceof HeaderClassifier); } @Override protected void putConfiguration(Map<String, String> config) { config.put("priority", this.priority.toString()); config.put("match", getRulesJson()); } private String rulesJson = null; private String getRulesJson() { if (rulesJson == null) { synchronized (this) { if (rulesJson == null) { StringBuilder sb = new StringBuilder(); sb.append('['); this.rules.forEach(r -> sb.append(r.toJson()).append(',')); sb.deleteCharAt(sb.length() - 1); sb.append(']'); rulesJson = sb.toString(); } } } return rulesJson; } private static HeaderClassifierRuleWithSources aggregateRules(HeaderClassifierRule r1, HeaderClassifierRule r2, Priority p1, Priority p2, int src1, int src2, int order) throws MergeException { int pr1 = r1.getPriority().ordinal() * p1.ordinal() / 6; int pr2 = r2.getPriority().ordinal() * p2.ordinal() / 6; int newRulePrio = (pr1 > pr2 ? pr1 : pr2); HeaderMatch mergedMatch = r1.getMatch().mergeWith(r2.getMatch()); Pair<Integer> sources = new Pair<Integer>(src1, src2); HeaderClassifierRuleWithSources newRule = new HeaderClassifierRuleWithSources(mergedMatch, Priority.of(newRulePrio), order, sources); return newRule; } @Override public IClassifierProcessingBlock mergeWith(IClassifierProcessingBlock other, IProcessingGraph containingGraph, List<Pair<Integer>> outPortSources) throws MergeException { if (!(other instanceof HeaderClassifier)) throw new MergeException("Cannot merge with the given type of classifier"); HeaderClassifier o = (HeaderClassifier)other; // TODO: FIX THIS!!! // SECOND TRY: FULL CROSS PRODUCT // Create cross-product of rules table List<HeaderClassifierRuleWithSources> rules = new ArrayList<>(); int order = 0; for (int i = 0; i < this.rules.size(); i++) { HeaderClassifierRule r1 = this.rules.get(i); for (int j = 0; j < o.rules.size(); j++) { HeaderClassifierRule r2 = o.rules.get(j); rules.add(aggregateRules(r1, r2, this.priority, o.priority, i, j, order)); order++; } } Collections.sort(rules); //Collections.reverse(rules); // Remove duplicate rules Set<Integer> toRemove = new HashSet<>(); for (int i = 0; i < rules.size(); i++) { for (int j = i + 1; j < rules.size(); j++) { if (rules.get(i).matchEquals(rules.get(j))) { // Same rule - remove rule j toRemove.add(j); } } } List<Integer> toRemoveLst = toRemove.stream().collect(Collectors.toList()); Collections.sort(toRemoveLst); Collections.reverse(toRemoveLst); for (Integer i : toRemoveLst) { rules.remove(i.intValue()); } Priority newP = (this.priority.compareTo(o.priority) > 0 ? this.priority : o.priority); IClassifierProcessingBlock merged = new HeaderClassifier("MERGED##" + this.getId() + "##" + other.getId() + "##" + UUIDGenerator.getSystemInstance().getUUID().toString(), rules, newP); for (HeaderClassifierRuleWithSources r : rules) { outPortSources.add(r.sources); } return merged; } public static class HeaderClassifierRule implements Comparable<HeaderClassifierRule> { private HeaderMatch match; private Priority priority; private int order; private HeaderClassifierRule(){ } private HeaderClassifierRule(HeaderMatch match, Priority p, int order) { this.match = match; this.priority = p; this.order = order; } public HeaderMatch getMatch() { return this.match; } public Priority getPriority() { return this.priority; } @Override public int compareTo(HeaderClassifierRule o) { // Descending order - highest priority first / lowest order first if (this.priority != o.priority) return o.priority.compareTo(this.priority); else return this.order - o.order; } boolean matchEquals(HeaderClassifierRule other) { return this.match.equals(other.match); } @Override public String toString() { return String.format("[HeaderClassifierRule: priority: %s, order: %d, match: %s]", this.priority.name(), this.order, this.match.toString()); } public String toJson() { return this.match.toJson(); } public static class Builder { private HeaderClassifierRule rule; public Builder(){ this.rule = new HeaderClassifierRule(); } public Builder setHeaderMatch(HeaderMatch match){ this.rule.match = match; return this; } public Builder setPriority(Priority p){ this.rule.priority = p; return this; } public Builder setOrder(int o){ this.rule.order = 0; return this; } public HeaderClassifierRule build(){ return new HeaderClassifierRule(this.rule.match, this.rule.priority, this.rule.order); } } } private static class HeaderClassifierRuleWithSources extends HeaderClassifierRule { private Pair<Integer> sources; public HeaderClassifierRuleWithSources(HeaderMatch match, Priority priority, int order, Pair<Integer> sources) { super(match, priority, order); this.sources = sources; } } }
package org.myire.quill.report; import java.io.File; import groovy.lang.Closure; import org.gradle.api.Project; import org.gradle.api.logging.Logger; import org.gradle.api.provider.Property; import org.gradle.api.provider.Provider; import org.gradle.api.reporting.ConfigurableReport; import org.gradle.api.reporting.Report; import org.gradle.api.tasks.Input; import org.gradle.api.tasks.Internal; import org.gradle.util.ConfigureUtil; import org.myire.quill.common.ProjectAware; /** * Implementation of {@code org.gradle.api.reporting.ConfigurableReport}. */ abstract public class SimpleConfigurableReport extends ProjectAware implements ConfigurableReport { private final String fName; private final String fDisplayName; private final Report.OutputType fOutputType; private final Property<Boolean> fRequiredProperty; private Object fDestination; /** * Create a new {@code SimpleReport}. * * @param pProject The project for which the report will be produced. * @param pName The report's symbolic name. * @param pDisplayName The report's descriptive name. * @param pOutputType The type of output the report produces. * * @throws NullPointerException if {@code pProject} is null. */ protected SimpleConfigurableReport( Project pProject, String pName, String pDisplayName, Report.OutputType pOutputType) { super(pProject); fName = pName; fDisplayName = pDisplayName; fOutputType = pOutputType; fRequiredProperty = pProject.getObjects().property(Boolean.class); fRequiredProperty.set(Boolean.FALSE); } @Override public String getName() { return fName; } @Override public String getDisplayName() { return fDisplayName; } @Override public Report.OutputType getOutputType() { return fOutputType; } @Override public File getDestination() { return resolveDestination(); } @Override public void setDestination(File pFile) { fDestination = pFile; } @Override public void setDestination(Provider<File> pProvider) { fDestination = pProvider; } /** * Set the value of the {@code outputLocation} property. * * @param pLocation The property's new value. */ public void setOutputLocation(Object pLocation) { useDestination(pLocation); } @Override public boolean isEnabled() { return reportIsRequired(); } @Override public void setEnabled(boolean pEnabled) { fRequiredProperty.set(Boolean.valueOf(pEnabled)); } @Override public void setEnabled(Provider<Boolean> pProvider) { fRequiredProperty.set(pProvider); } @Override public Report configure(Closure pConfigureClosure) { return ConfigureUtil.configureSelf(pConfigureClosure, this); } // 6.1 compatibility. @Input public Property<Boolean> getRequired() { return fRequiredProperty; } /** * Set the value of the {@code required} property. * * @param pValue The property's new value. */ public void setRequired(boolean pValue) { fRequiredProperty.set(Boolean.valueOf(pValue)); } // Override to add @Internal annotation @Override @Internal public Project getProject() { return super.getProject(); } // Override to add @Internal annotation @Override @Internal public Logger getProjectLogger() { return super.getProjectLogger(); } @Override public String toString() { return "Report " + getName(); } /** * Check if this report is required (enabled) and should be created. * * @return True if this report is required, false if not. */ protected boolean reportIsRequired() { return fRequiredProperty.getOrElse(Boolean.FALSE).booleanValue(); } /** * Resolve the destination specified by the latest call to {@link #setDestination(File)}, * {@link #setDestination(Provider)}, or {@link #useDestination(Object)}. * * @return The destination file resolved with the project directory as base directory. If no * destination has been specified, null is returned. */ protected File resolveDestination() { return fDestination != null ? getProject().file(fDestination) : null; } /** * Set the value of the report's destination without calling {@link #setDestination(File)}. That * method was deprecated in Gradle 7.1. * * @param pDestination The report's destination, possibly null. */ protected void useDestination(Object pDestination) { fDestination = pDestination; } }
package nl.mpi.kinnate.svg; import java.awt.Cursor; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import nl.mpi.kinnate.kindata.DataTypes.RelationType; import org.w3c.dom.events.Event; import org.w3c.dom.events.EventListener; import org.apache.batik.dom.events.DOMMouseEvent; import javax.swing.event.MouseInputAdapter; import nl.mpi.arbil.data.ArbilDataNode; import nl.mpi.arbil.data.ArbilDataNodeLoader; import nl.mpi.arbil.ui.ArbilWindowManager; import nl.mpi.arbil.ui.GuiHelper; import nl.mpi.kinnate.gedcomimport.ImportException; import nl.mpi.kinnate.kindata.DataTypes; import nl.mpi.kinnate.kindata.EntityData; import nl.mpi.kinnate.kindata.EntityRelation; import nl.mpi.kinnate.kindocument.RelationLinker; import nl.mpi.kinnate.ui.KinDiagramPanel; import nl.mpi.kinnate.ui.SvgElementEditor; import nl.mpi.kinnate.uniqueidentifiers.IdentifierException; import nl.mpi.kinnate.uniqueidentifiers.UniqueIdentifier; import org.w3c.dom.Element; import org.w3c.dom.svg.SVGLocatable; import org.w3c.dom.svg.SVGMatrix; public class MouseListenerSvg extends MouseInputAdapter implements EventListener { private Cursor preDragCursor; private KinDiagramPanel kinDiagramPanel; private GraphPanel graphPanel; private Point startDragPoint = null; private boolean mouseActionOnNode = false; private boolean mouseActionIsPopupTrigger = false; private boolean mouseActionIsDrag = false; private UniqueIdentifier entityToToggle = null; HashMap<UniqueIdentifier, SvgElementEditor> shownGraphicsEditors; public enum ActionCode { selectAll, selectRelated, expandSelection, deselectAll } public MouseListenerSvg(KinDiagramPanel kinDiagramPanel, GraphPanel graphPanelLocal) { this.kinDiagramPanel = kinDiagramPanel; graphPanel = graphPanelLocal; shownGraphicsEditors = new HashMap<UniqueIdentifier, SvgElementEditor>(); } @Override public void mouseDragged(MouseEvent me) { if (graphPanel.svgUpdateHandler.relationDragHandle != null) { graphPanel.svgUpdateHandler.updateDragRelation(me.getPoint().x, me.getPoint().y); } else { if (startDragPoint != null) { // System.out.println("mouseDragged: " + me.toString()); if (graphPanel.selectedGroupId.size() > 0) { checkSelectionClearRequired(me); } if (graphPanel.selectedGroupId.size() > 0) { graphPanel.svgCanvas.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); // limit the drag to the distance draged not the location graphPanel.svgUpdateHandler.updateDragNode(me.getPoint().x - startDragPoint.x, me.getPoint().y - startDragPoint.y); } else { graphPanel.svgUpdateHandler.dragCanvas(me.getPoint().x - startDragPoint.x, me.getPoint().y - startDragPoint.y); } mouseActionIsDrag = true; } else { graphPanel.svgUpdateHandler.startDrag(); } startDragPoint = me.getPoint(); } } private void checkSelectionClearRequired(MouseEvent me) { boolean shiftDown = me.isShiftDown(); if (!shiftDown && /* !mouseActionIsDrag && */ !mouseActionIsPopupTrigger && !mouseActionOnNode && me.getButton() == MouseEvent.BUTTON1) { // todo: button1 could cause issues for left handed people with swapped mouse buttons System.out.println("Clear selection"); graphPanel.selectedGroupId.clear(); updateSelectionDisplay(); } } @Override public void mouseReleased(MouseEvent me) { // System.out.println("mouseReleased: " + me.toString()); graphPanel.svgCanvas.setCursor(preDragCursor); if (mouseActionIsDrag) { graphPanel.svgUpdateHandler.updateCanvasSize(); } startDragPoint = null; if (!mouseActionIsDrag && entityToToggle != null) { // toggle the highlight graphPanel.selectedGroupId.remove(entityToToggle); entityToToggle = null; updateSelectionDisplay(); } checkSelectionClearRequired(me); mouseActionOnNode = false; if (graphPanel.svgUpdateHandler.relationDragHandle != null) { if (graphPanel.svgUpdateHandler.relationDragHandle.targetIdentifier != null) { try { // if a relation has been set by this drag action then it is created here. final RelationType relationType = DataTypes.getOpposingRelationType(graphPanel.svgUpdateHandler.relationDragHandle.relationType); UniqueIdentifier[] changedIdentifiers = new RelationLinker().linkEntities(graphPanel.svgUpdateHandler.relationDragHandle.targetIdentifier, graphPanel.getSelectedIds(), relationType); kinDiagramPanel.entityRelationsChanged(changedIdentifiers); } catch (ImportException exception) { ArbilWindowManager.getSingleInstance().addMessageDialogToQueue("Failed to create relation: " + exception.getMessage(), "Drag Relation"); } } graphPanel.svgUpdateHandler.relationDragHandle = null; updateSelectionDisplay(); } } @Override public void mousePressed(MouseEvent e) { mouseActionIsDrag = false; mouseActionIsPopupTrigger = e.isPopupTrigger(); } @Override public void handleEvent(Event evt) { mouseActionOnNode = true; boolean shiftDown = false; if (evt instanceof DOMMouseEvent) { shiftDown = ((DOMMouseEvent) evt).getShiftKey(); } System.out.println("dom mouse event: " + evt.getCurrentTarget()); Element currentDraggedElement = ((Element) evt.getCurrentTarget()); preDragCursor = graphPanel.svgCanvas.getCursor(); final String handleTypeString = currentDraggedElement.getAttribute("handletype"); final String targetIdString = currentDraggedElement.getAttribute("target"); if ((targetIdString != null && targetIdString.length() > 0) || (handleTypeString != null && handleTypeString.length() > 0)) { if (evt instanceof DOMMouseEvent) { Element entityGroup = graphPanel.doc.getElementById("EntityGroup"); SVGMatrix entityGroupMatrix = ((SVGLocatable) entityGroup).getCTM(); SVGMatrix entityMatrix = ((SVGLocatable) currentDraggedElement).getCTM(); float xTranslate = entityMatrix.getE() - entityGroupMatrix.getE(); // because the target of the drag location is within the diagram translation we must subtract it here float yTranslate = entityMatrix.getF() - entityGroupMatrix.getF(); AffineTransform affineTransform = graphPanel.svgCanvas.getRenderingTransform(); if (targetIdString != null && targetIdString.length() > 0) { graphPanel.svgUpdateHandler.relationDragHandle = new GraphicsDragHandle( graphPanel.doc.getElementById(targetIdString), currentDraggedElement, (Element) currentDraggedElement.getParentNode().getFirstChild(), // this assumes that the rect is the first element in the highlight Float.valueOf(currentDraggedElement.getAttribute("cx")), // + xTranslate, Float.valueOf(currentDraggedElement.getAttribute("cy")), // + yTranslate, ((DOMMouseEvent) evt).getClientX(), ((DOMMouseEvent) evt).getClientY(), affineTransform.getScaleX() // the drawing should be proportional so only using X is adequate here ); } else { graphPanel.svgUpdateHandler.relationDragHandle = new RelationDragHandle( DataTypes.RelationType.valueOf(handleTypeString), Float.valueOf(currentDraggedElement.getAttribute("cx")) + xTranslate, Float.valueOf(currentDraggedElement.getAttribute("cy")) + yTranslate, ((DOMMouseEvent) evt).getClientX(), ((DOMMouseEvent) evt).getClientY(), affineTransform.getScaleX() // the drawing should be proportional so only using X is adequate here ); } } } else { final String attributeString = currentDraggedElement.getAttribute("id"); try { UniqueIdentifier entityIdentifier = new UniqueIdentifier(attributeString); System.out.println("entityPath: " + entityIdentifier.getAttributeIdentifier()); boolean nodeAlreadySelected = graphPanel.selectedGroupId.contains(entityIdentifier); if (!shiftDown && !nodeAlreadySelected) { System.out.println("Clear selection"); graphPanel.selectedGroupId.clear(); graphPanel.selectedGroupId.add(entityIdentifier); } else { // toggle the highlight if (shiftDown && nodeAlreadySelected) { // postpone until after a drag action can be tested for and only deselect if not draged entityToToggle = entityIdentifier; // graphPanel.selectedGroupId.remove(entityIdentifier); } else if (!nodeAlreadySelected) { graphPanel.selectedGroupId.add(entityIdentifier); } } updateSelectionDisplay(); } catch (IdentifierException exception) { GuiHelper.linorgBugCatcher.logError(exception); ArbilWindowManager.getSingleInstance().addMessageDialogToQueue("Failed to read selection identifier, selection might not be correct", "Selection Highlight"); } } } protected void updateSelectionDisplay() { graphPanel.svgUpdateHandler.updateSvgSelectionHighlights(); // update the table selection // todo: #1099 Labels should show the blue highlight if (graphPanel.arbilTableModel != null) { graphPanel.arbilTableModel.removeAllArbilDataNodeRows(); try { boolean showEditor = false; boolean tableRowShown = false; ArrayList<UniqueIdentifier> remainingEditors = new ArrayList<UniqueIdentifier>(shownGraphicsEditors.keySet()); for (UniqueIdentifier currentSelectedId : graphPanel.selectedGroupId) { remainingEditors.remove(currentSelectedId); if (currentSelectedId.isGraphicsIdentifier()) { if (!shownGraphicsEditors.containsKey(currentSelectedId)) { Element graphicsElement = graphPanel.doc.getElementById(currentSelectedId.getAttributeIdentifier()); SvgElementEditor elementEditor = new SvgElementEditor(graphPanel.svgCanvas.getUpdateManager(), graphicsElement); graphPanel.editorHidePane.addTab("Graphics Editor", elementEditor); // graphPanel.editorHidePane.setSelectedComponent(elementEditor); shownGraphicsEditors.put(currentSelectedId, elementEditor); } showEditor = true; } else { String currentSelectedPath = graphPanel.getPathForElementId(currentSelectedId); if (currentSelectedPath != null && currentSelectedPath.length() > 0) { ArbilDataNode arbilDataNode = ArbilDataNodeLoader.getSingleInstance().getArbilDataNode(null, new URI(currentSelectedPath)); // register this node with the graph panel kinDiagramPanel.registerArbilNode(currentSelectedId, arbilDataNode); graphPanel.arbilTableModel.addSingleArbilDataNode(arbilDataNode); showEditor = true; tableRowShown = true; } } } for (UniqueIdentifier remainingIdentifier : remainingEditors) { // remove the unused editors graphPanel.editorHidePane.remove(shownGraphicsEditors.get(remainingIdentifier)); shownGraphicsEditors.remove(remainingIdentifier); } if (tableRowShown) { graphPanel.editorHidePane.addTab("Metadata", graphPanel.tableScrollPane); } else { graphPanel.editorHidePane.remove(graphPanel.tableScrollPane); } if (showEditor && graphPanel.editorHidePane.isHidden()) { graphPanel.editorHidePane.toggleHiddenState(); } graphPanel.editorHidePane.setVisible(showEditor); } catch (URISyntaxException urise) { GuiHelper.linorgBugCatcher.logError(urise); } } } private void addRelations(int maxCount, EntityData currentEntity, HashSet<UniqueIdentifier> selectedIds) { if (maxCount <= selectedIds.size()) { return; } for (EntityRelation entityRelation : currentEntity.getVisiblyRelateNodes()) { EntityData alterNode = entityRelation.getAlterNode(); if (alterNode.isVisible && !selectedIds.contains(alterNode.getUniqueIdentifier())) { selectedIds.add(alterNode.getUniqueIdentifier()); addRelations(maxCount, alterNode, selectedIds); } } } public void performMenuAction(ActionCode commandCode) { System.out.println("commandCode: " + commandCode.name()); switch (commandCode) { case selectAll: graphPanel.selectedGroupId.clear(); for (EntityData currentEntity : graphPanel.dataStoreSvg.graphData.getDataNodes()) { if (currentEntity.isVisible) { if (!graphPanel.selectedGroupId.contains(currentEntity.getUniqueIdentifier())) { graphPanel.selectedGroupId.add(currentEntity.getUniqueIdentifier()); } } } break; case selectRelated: HashSet<UniqueIdentifier> selectedIds = new HashSet<UniqueIdentifier>(graphPanel.selectedGroupId); for (EntityData currentEntity : graphPanel.dataStoreSvg.graphData.getDataNodes()) { if (currentEntity.isVisible) { // todo: continue here if (graphPanel.selectedGroupId.contains(currentEntity.getUniqueIdentifier())) { addRelations(graphPanel.dataStoreSvg.graphData.getDataNodes().length, currentEntity, selectedIds); } } } graphPanel.selectedGroupId.clear(); graphPanel.selectedGroupId.addAll(selectedIds); break; case expandSelection: // todo: continue here... break; case deselectAll: graphPanel.selectedGroupId.clear(); break; } updateSelectionDisplay(); } }
package nl.mpi.kinnate.ui; import java.awt.BorderLayout; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import nl.mpi.arbil.data.ArbilDataNode; import nl.mpi.arbil.data.ArbilDataNodeLoader; import nl.mpi.arbil.ui.ArbilTable; import nl.mpi.arbil.ui.ArbilTree; import nl.mpi.arbil.util.ArbilBugCatcher; import nl.mpi.kinnate.entityindexer.EntityCollection; public class EntitySearchPanel extends JPanel { private EntityCollection entityCollection; private ArbilTree leftTree; private JTextArea resultsArea = new JTextArea(); private JTextField searchField; public EntitySearchPanel(EntityCollection entityCollectionLocal, ArbilTable arbilTable) { entityCollection = entityCollectionLocal; this.setLayout(new BorderLayout()); leftTree = new ArbilTree(); leftTree.setCustomPreviewTable(arbilTable); leftTree.setModel(new DefaultTreeModel(new DefaultMutableTreeNode("Test Tree"), true)); // ArrayList<URI> allEntityUris = new ArrayList<URI>(); // String[] treeNodesArray = LinorgSessionStorage.getSingleInstance().loadStringArray("KinGraphTree"); // if (treeNodesArray != null) { // ArrayList<ArbilTreeObject> tempArray = new ArrayList<ArbilTreeObject>(); // for (String currentNodeString : treeNodesArray) { // try { // ArbilTreeObject currentArbilNode = ArbilLoader.getSingleInstance().getArbilObject(null, new URI(currentNodeString)); // tempArray.add(currentArbilNode); // allEntityUris.add(currentArbilNode.getURI()); // } catch (URISyntaxException exception) { // GuiHelper.linorgBugCatcher.logError(exception); // ArbilTreeObject[] allEntities = tempArray.toArray(new ArbilTreeObject[]{}); // leftTree.rootNodeChildren = allEntities; // imdiTableModel.removeAllArbilRows(); // imdiTableModel.addArbilObjects(leftTree.rootNodeChildren); // } //else { // // leftTree.rootNodeChildren = new ArbilTreeObject[]{graphPanel.imdiNode}; leftTree.setRootVisible(false); leftTree.requestResort(); JLabel searchLabel = new JLabel("Search Entity Names"); searchField = new JTextField(); searchField.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ENTER) { EntitySearchPanel.this.performSearch(); } super.keyReleased(e); } }); JButton searchButton = new JButton("Search"); searchButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { EntitySearchPanel.this.performSearch(); } }); JPanel searchPanel = new JPanel(); searchPanel.setLayout(new BorderLayout()); searchPanel.add(searchLabel, BorderLayout.PAGE_START); searchPanel.add(searchField, BorderLayout.CENTER); searchPanel.add(searchButton, BorderLayout.PAGE_END); this.add(searchPanel, BorderLayout.PAGE_START); this.add(new JScrollPane(leftTree), BorderLayout.CENTER); this.add(resultsArea, BorderLayout.PAGE_END); } public void setTransferHandler(DragTransferHandler dragTransferHandler) { leftTree.setTransferHandler(dragTransferHandler); } protected void performSearch() { ArrayList<ArbilDataNode> resultsArray = new ArrayList<ArbilDataNode>(); EntityCollection.SearchResults searchResults = entityCollection.searchByName(searchField.getText()); String[] rawResultsArray = searchResults.resultsPathArray; resultsArea.setText(searchResults.statusMessage + "\n"); for (String resultLine : rawResultsArray) { try { if (resultsArray.size() < 100) { ArbilDataNode currentArbilObject = ArbilDataNodeLoader.getSingleInstance().getArbilDataNode(null, new URI(resultLine)); currentArbilObject.reloadNode(); resultsArray.add(currentArbilObject); } else { resultsArea.append("results limited to 100\n"); break; } } catch (URISyntaxException exception) { new ArbilBugCatcher().logError(exception); resultsArea.append("error: " + resultLine + "\n"); } } leftTree.rootNodeChildren = resultsArray.toArray(new ArbilDataNode[]{}); leftTree.requestResort(); } }
package nl.mpi.kinnate.ui; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import nl.mpi.kinnate.export.EntityUploader; public class EntityUploadPanel extends JPanel implements ActionListener { // private JList uploadList; private JTextArea uploadText; private JButton searchNewButton; private JButton searchModifiedButton; private JButton uploadButton; private JTextField workspaceName; private JPasswordField passwordText; private JProgressBar uploadProgress; private EntityUploader entityUploader; private JPanel workspacePanel; private JPanel passwordPanel; public EntityUploadPanel() { entityUploader = new EntityUploader(); // uploadList = new JList(); uploadText = new JTextArea(); searchNewButton = new JButton("Search New Entities"); searchModifiedButton = new JButton("Search Modified Entities"); uploadButton = new JButton("Upload Selected"); workspaceName = new JTextField(); passwordText = new JPasswordField(); uploadProgress = new JProgressBar(); JPanel controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout()); controlPanel.add(searchNewButton); controlPanel.add(searchModifiedButton); controlPanel.add(uploadButton); workspacePanel = new JPanel(); workspacePanel.setLayout(new BorderLayout()); workspacePanel.add(new JLabel("Target Workspace Name"), BorderLayout.LINE_START); workspacePanel.add(workspaceName, BorderLayout.CENTER); passwordPanel = new JPanel(); passwordPanel.setLayout(new BorderLayout()); passwordPanel.add(new JLabel("Workspace Password"), BorderLayout.LINE_START); passwordPanel.add(passwordText, BorderLayout.CENTER); JPanel topPanel = new JPanel(); topPanel.setLayout(new BoxLayout(topPanel, BoxLayout.PAGE_AXIS)); topPanel.add(controlPanel); topPanel.add(workspacePanel); topPanel.add(passwordPanel); this.setLayout(new BorderLayout()); this.add(topPanel, BorderLayout.PAGE_START); // this.add(uploadList, BorderLayout.CENTER); this.add(new JScrollPane(uploadText), BorderLayout.CENTER); this.add(uploadProgress, BorderLayout.PAGE_END); uploadButton.setEnabled(false); // workspaceName.setEnabled(false); // passwordText.setEnabled(false); workspacePanel.setVisible(false); passwordPanel.setVisible(false); searchNewButton.addActionListener(this); searchModifiedButton.addActionListener(this); uploadButton.addActionListener(this); searchNewButton.setActionCommand("searchnew"); searchModifiedButton.setActionCommand("searchmodified"); uploadButton.setActionCommand("upload"); } public void actionPerformed(ActionEvent e) { searchNewButton.setEnabled(false); searchModifiedButton.setEnabled(false); uploadButton.setEnabled(false); if (e.getActionCommand().equals("searchnew")) { uploadText.setText("Searching for local entities that do not exist on the server\n"); int foundCount = entityUploader.findLocalEntities(uploadProgress); // uploadText.append(entityUploader.getSearchMessage()); uploadText.append("Found " + foundCount + " entities to upload\n"); } else if (e.getActionCommand().equals("searchmodified")) { uploadText.setText("Searching for modified entities that require upload to the server\n"); int foundCount = entityUploader.findModifiedEntities(uploadProgress); uploadText.append("Found " + foundCount + " entities to upload\n"); } else if (e.getActionCommand().equals("upload")) { uploadText.append("Uploading entities to the server\n"); entityUploader.uploadLocalEntites(uploadProgress, uploadText, workspaceName.getText(), passwordText.getPassword()); // uploadText.append("Done\n"); } // workspaceName.setEnabled(entityUploader.canUpload()); // passwordText.setEnabled(entityUploader.canUpload()); workspacePanel.setVisible(entityUploader.canUpload()); passwordPanel.setVisible(entityUploader.canUpload()); uploadButton.setEnabled(entityUploader.canUpload()); searchNewButton.setEnabled(!entityUploader.canUpload()); searchModifiedButton.setEnabled(!entityUploader.canUpload()); } }
package com.liferay.lms; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.portlet.PortletException; import javax.portlet.PortletRequest; import javax.portlet.PortletRequestDispatcher; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.portlet.ResourceRequest; import javax.portlet.ResourceResponse; import org.apache.velocity.tools.generic.DateTool; import org.xhtmlrenderer.pdf.ITextRenderer; import com.liferay.lms.model.Competence; import com.liferay.lms.model.Course; import com.liferay.lms.model.CourseResult; import com.liferay.lms.model.LmsPrefs; import com.liferay.lms.model.Module; import com.liferay.lms.model.ModuleResult; import com.liferay.lms.model.UserCompetence; import com.liferay.lms.service.CompetenceLocalServiceUtil; import com.liferay.lms.service.CourseLocalServiceUtil; import com.liferay.lms.service.CourseResultLocalServiceUtil; import com.liferay.lms.service.LmsPrefsLocalServiceUtil; import com.liferay.lms.service.ModuleLocalServiceUtil; import com.liferay.lms.service.ModuleResultLocalServiceUtil; import com.liferay.lms.service.UserCompetenceLocalServiceUtil; import com.liferay.lms.views.CompetenceView; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.util.GetterUtil; import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portal.kernel.util.PropsUtil; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.kernel.util.WebKeys; import com.liferay.portal.kernel.xml.Attribute; import com.liferay.portal.kernel.xml.Document; import com.liferay.portal.kernel.xml.Element; import com.liferay.portal.kernel.xml.SAXReaderUtil; import com.liferay.portal.model.User; import com.liferay.portal.model.UserGroupRole; import com.liferay.portal.service.UserGroupRoleLocalServiceUtil; import com.liferay.portal.service.UserLocalServiceUtil; import com.liferay.portal.theme.ThemeDisplay; import com.liferay.portal.util.PortalUtil; import com.liferay.util.VelocityUtil; import com.liferay.util.bridges.mvc.MVCPortlet; import com.lowagie.text.DocumentException; import com.lowagie.text.pdf.BaseFont; public class UserCompetencePortlet extends MVCPortlet { private static Log log = LogFactoryUtil.getLog(UserCompetencePortlet.class); private String viewJSP; public void init() throws PortletException { viewJSP = getInitParameter("view-template"); } public void doView(RenderRequest renderRequest,RenderResponse renderResponse) throws IOException, PortletException { ThemeDisplay themeDisplay = (ThemeDisplay)renderRequest.getAttribute(WebKeys.THEME_DISPLAY); int page = 0; int delta = 10; try{ page = Integer.valueOf(renderRequest.getParameter("act")); if(page>0){ page = page -1; } }catch(NumberFormatException nfe){ if(log.isDebugEnabled())nfe.printStackTrace(); } try{ delta = Integer.valueOf(renderRequest.getParameter("delta")); }catch(NumberFormatException nfe){ if(log.isDebugEnabled())nfe.printStackTrace(); } try{ if(renderRequest.getParameter("deltaact")!=null){ delta = Integer.valueOf(renderRequest.getParameter("deltaact")); } }catch(NumberFormatException nfe){ if(log.isDebugEnabled())nfe.printStackTrace(); } List<UserCompetence> ucs = UserCompetenceLocalServiceUtil.findBuUserId(themeDisplay.getUserId(),page*delta,(page*delta)+delta); int totale = UserCompetenceLocalServiceUtil.countByUserId(themeDisplay.getUserId()); List<CompetenceView> competences = new ArrayList<CompetenceView>(); for(UserCompetence uc : ucs){ try { Competence competence = CompetenceLocalServiceUtil.getCompetence(uc.getCompetenceId()); if(competence!=null){ competences.add(new CompetenceView(competence, uc)); } } catch (PortalException e) { if(log.isDebugEnabled())e.printStackTrace(); } catch (SystemException e) { if(log.isDebugEnabled())e.printStackTrace(); } } renderRequest.setAttribute("competences", competences); renderRequest.setAttribute("totale", String.valueOf(totale)); renderRequest.setAttribute("delta", String.valueOf(delta)); include(viewJSP, renderRequest, renderResponse); } private void printCertificate(OutputStream out,String uuid,PortletRequest request) throws SystemException, PortalException, IOException, DocumentException { UserCompetence userCompetence=UserCompetenceLocalServiceUtil.findByUuid(uuid); User user=UserLocalServiceUtil.getUser(userCompetence.getUserId()); Competence competence = CompetenceLocalServiceUtil.getCompetence(userCompetence.getCompetenceId()); Course course=CourseLocalServiceUtil.getCourse(userCompetence.getCourseId()); ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(WebKeys.THEME_DISPLAY); DateFormat dateFormatDate = DateFormat.getDateInstance(DateFormat.SHORT,user.getLocale()); dateFormatDate.setTimeZone(user.getTimeZone()); if (dateFormatDate instanceof SimpleDateFormat) { SimpleDateFormat sdf = (SimpleDateFormat) dateFormatDate; // To show Locale specific short date expression with full year String pattern = sdf.toPattern().replaceAll("y+","yyyy"); sdf.applyPattern(pattern); dateFormatDate=sdf; } if(user!=null&&competence!=null&&course!=null){ if(log.isDebugEnabled())log.debug("Enter:"+user.getLocale()); CourseResult courseResult = CourseResultLocalServiceUtil.getCourseResultByCourseAndUser(course.getCourseId(), user.getUserId()); ITextRenderer renderer = new ITextRenderer(); Map<String, Object> variables = new HashMap<String, Object>(); variables.put("dateFormatDate", dateFormatDate); variables.put("dateTool", new DateTool()); variables.put("user", user); variables.put("competence", competence); variables.put("course", course); variables.put("uuid", userCompetence.getUuid()); variables.put("userCompetence", userCompetence); if(courseResult!=null) { variables.put("courseResult", courseResult); String extraData=courseResult.getExtraData(); if(extraData!=null&&!extraData.trim().equals("")) { try { Document eldoc= SAXReaderUtil.read(extraData); Element root = eldoc.getRootElement(); List<Element> elements = root.elements(); for (Element element : elements) { processElement(element, variables); } } catch (com.liferay.portal.kernel.xml.DocumentException e) { e.printStackTrace(); } } } variables.put("courseName", course.getTitle(user.getLocale())); variables.put("competenceName", competence.getTitle(user.getLocale())); variables.put("userName", user.getFullName()); variables.put("themeDisplay", themeDisplay); LmsPrefs lmsprefs=LmsPrefsLocalServiceUtil.getLmsPrefs(themeDisplay.getCompanyId()); long teacherRoleId=lmsprefs.getTeacherRole(); List<UserGroupRole> teachersGroups=UserGroupRoleLocalServiceUtil.getUserGroupRolesByGroupAndRole(course.getGroupCreatedId(),teacherRoleId); StringBuffer teachersNames = new StringBuffer(StringPool.BLANK); List<User> teachers = new ArrayList<User>(); if(teachersGroups!=null){ if(log.isDebugEnabled())log.debug(teachersGroups.size()); teachersNames.append("<ul>"); for(UserGroupRole userGroupRole : teachersGroups){ User teacher = UserLocalServiceUtil.getUser(userGroupRole.getUserId()); if(teacher!=null){ teachersNames.append("<li>"); teachersNames.append(teacher.getFullName()); teachers.add(teacher); teachersNames.append("</li>"); } } teachersNames.append("</ul>"); } StringBuffer modulesNames = new StringBuffer(StringPool.BLANK); List<Module> modules= ModuleLocalServiceUtil.findAllInGroup(course.getGroupCreatedId()); Map<Long,ModuleResult> moduleResults=new java.util.HashMap<Long,ModuleResult>(); if(modules!=null){ modulesNames.append("<ul>"); if(log.isDebugEnabled())log.debug(modules.size()); for(Module module : modules){ modulesNames.append("<li>"); modulesNames.append(module.getTitle(user.getLocale())); modulesNames.append("</li>"); ModuleResult mResult=ModuleResultLocalServiceUtil.getByModuleAndUser(module.getModuleId(), user.getUserId()); moduleResults.put(module.getModuleId(), mResult); } modulesNames.append("</ul>"); } variables.put("modules", modules); variables.put("moduleResults",moduleResults); variables.put("modulesNames", modulesNames); variables.put("teachers", teachers); variables.put("teachersNames", teachersNames); String template = StringPool.BLANK; try { template = VelocityUtil.evaluate(competence.getDiplomaTemplate(user.getLocale()).replaceAll("&nbsp;", StringPool.BLANK), variables); } catch (Exception e) { if(log.isDebugEnabled())e.printStackTrace(); } String cssurl = GetterUtil.get(PropsUtil.get("com.ted.siele.diploma.css"), StringPool.BLANK); String imageurl =CompetenceLocalServiceUtil.getBGImageURL( competence, PortalUtil.getHttpServletRequest(request)); StringBuffer html = new StringBuffer("<html xmlns=\"http: html.append("@page { size: "); html.append(competence.getPage()); File file = new File(imageurl.replace("file:", "")); if(file.exists()){ html.append(" ; background: url('"); html.append(imageurl); html.append("') repeat-y top center}"); }else{ html.append("}"); } if(!StringPool.BLANK.equals(cssurl)){ String css = getFileContent(cssurl); if(css!=null){ html.append(css); } } html.append("</style></head><body>"); html.append(template); html.append("</body></html>"); if(log.isDebugEnabled())log.debug(html); String listafuentes = GetterUtil.get(PropsUtil.get("com.ted.siele.diploma.fonts"), StringPool.BLANK); String[] fonts = listafuentes.split(","); for (int i = 0; i<fonts.length; i++){ renderer.getFontResolver().addFont(getAbsolutePath(fonts[i]),BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); } renderer.setDocumentFromString(html.toString()); renderer.layout(); try { renderer.createPDF(out, false); } catch (DocumentException e) { if(log.isDebugEnabled())e.printStackTrace(); } renderer.layout(); renderer.finishPDF(); }else{ if(log.isDebugEnabled())log.debug("Nodata!"); ITextRenderer renderer = new ITextRenderer(); renderer.setDocumentFromString(StringPool.BLANK); renderer.layout(); renderer.finishPDF(); } } public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException,IOException{ Long competenceId = ParamUtil.getLong(request, "competenceId", 0); String uuid=ParamUtil.getString(request, "uuid", ""); ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(WebKeys.THEME_DISPLAY); UserCompetence userCompetence=null; if("".equals(uuid)) { userCompetence= UserCompetenceLocalServiceUtil.findByUserIdCompetenceId(themeDisplay.getUserId(), competenceId); } else { userCompetence= UserCompetenceLocalServiceUtil.findByUuid(uuid); } response.setContentType("application/pdf"); if(themeDisplay.isSignedIn()) { if(userCompetence!=null) { try { OutputStream out = response.getPortletOutputStream(); printCertificate(out, userCompetence.getUuid(), request); out.close(); } catch (PortalException e) { if(log.isDebugEnabled())e.printStackTrace(); } catch (SystemException e) { if(log.isDebugEnabled())e.printStackTrace(); } catch (DocumentException e) { if(log.isDebugEnabled())e.printStackTrace(); } } } } protected void include(String path, RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { PortletRequestDispatcher portletRequestDispatcher = getPortletContext() .getRequestDispatcher(path); if (portletRequestDispatcher == null) { } else { portletRequestDispatcher.include(renderRequest, renderResponse); } } protected String getFileContent(String filepath) { String absolutePath = System.getProperty("catalina.base")+filepath; StringBuilder sb = new StringBuilder(); BufferedReader reader; try { reader = new BufferedReader(new FileReader(absolutePath)); char[] buf = new char[1024]; int numRead = 0; while ((numRead = reader.read(buf)) != -1) { String readData = String.valueOf(buf, 0, numRead); sb.append(readData); buf = new char[1024]; } reader.close(); return sb.toString(); } catch (FileNotFoundException e) { if(log.isDebugEnabled()){ log.debug(e); } return null; } catch (IOException e) { if(log.isDebugEnabled()){ log.debug(e); } return null; } } protected String getAbsolutePath(String filepath) { return System.getProperty("catalina.base")+filepath; } protected void processElement(Element element, Map<String, Object> variables){ if(element.hasContent()){ variables.put(element.getName(), element.getData()); } List<Attribute> attributes = element.attributes(); for (Attribute attribute : attributes) { variables.put(attribute.getName(), attribute.getValue()); } List<Element> elements = element.elements(); for (Element ele : elements) { processElement(ele, variables); } } }
package org.testng.remote.strprotocol; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.SkipException; import org.testng.collections.Lists; import java.io.PrintWriter; import java.io.StringWriter; import java.util.List; /** * An <code>IStringMessage</code> implementation for test results events. * * @author <a href='mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a> */ public class TestResultMessage implements IStringMessage { private static final Object[] EMPTY_PARAMS= new Object[0]; private static final Class[] EMPTY_TYPES= new Class[0]; protected int m_messageType; protected String m_suiteName; protected String m_testName; protected String m_testClassName; protected String m_testMethodName; protected String m_stackTrace; protected long m_startMillis; protected long m_endMillis; protected String[] m_parameters= new String[0]; protected String[] m_paramTypes= new String[0]; private String m_testDescription; TestResultMessage(final int resultType, final String suiteName, final String testName, final String className, final String methodName, final String testDescriptor, final String[] params, final long startMillis, final long endMillis, final String stackTrace) { init(resultType, suiteName, testName, className, methodName, stackTrace, startMillis, endMillis, extractParams(params), extractParamTypes(params), testDescriptor ); } public TestResultMessage(final String suiteName, final String testName, final ITestResult result) { String stackTrace = null; if((ITestResult.FAILURE == result.getStatus()) || (ITestResult.SUCCESS_PERCENTAGE_FAILURE == result.getStatus())) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); Throwable cause= result.getThrowable(); if (null != cause) { cause.printStackTrace(pw); stackTrace = sw.getBuffer().toString(); } else { stackTrace= "unknown stack trace"; } } else if(ITestResult.SKIP == result.getStatus() && (result.getThrowable() != null && SkipException.class.isAssignableFrom(result.getThrowable().getClass()))) { stackTrace= result.getThrowable().getMessage(); } init(MessageHelper.TEST_RESULT + result.getStatus(), suiteName, testName, result.getTestClass().getName(), result.getMethod().getMethod().getName(), MessageHelper.replaceUnicodeCharactersWithAscii(stackTrace), result.getStartMillis(), result.getEndMillis(), toString(result.getParameters(), result.getMethod().getMethod().getParameterTypes()), toString(result.getMethod().getMethod().getParameterTypes()), MessageHelper.replaceUnicodeCharactersWithAscii(result.getName()) ); } public TestResultMessage(final ITestContext testCtx, final ITestResult result) { this(testCtx.getSuite().getName(), testCtx.getCurrentXmlTest().getName(), result); // this(testCtx.getSuite().getName(), // result.getTestName() != null ? result.getTestName() : result.getName(), result); } private void init(final int resultType, final String suiteName, final String testName, final String className, final String methodName, final String stackTrace, final long startMillis, final long endMillis, final String[] parameters, final String[] types, final String testDescription) { m_messageType = resultType; m_suiteName = suiteName; m_testName = testName; m_testClassName = className; m_testMethodName = methodName; m_stackTrace = stackTrace; m_startMillis= startMillis; m_endMillis= endMillis; m_parameters= parameters; m_paramTypes= types; m_testDescription= testDescription; } public int getResult() { return m_messageType; } @Override public String getMessageAsString() { StringBuffer buf = new StringBuffer(); StringBuffer parambuf = new StringBuffer(); if(null != m_parameters && m_parameters.length > 0) { for (int j = 0; j < m_parameters.length; j++) { if (j > 0) { parambuf.append(MessageHelper.PARAM_DELIMITER); } parambuf.append(m_paramTypes[j] + ":" + m_parameters[j]); } } buf.append(m_messageType) .append(MessageHelper.DELIMITER) .append(m_suiteName) .append(MessageHelper.DELIMITER) .append(m_testName) .append(MessageHelper.DELIMITER) .append(m_testClassName) .append(MessageHelper.DELIMITER) .append(m_testMethodName) .append(MessageHelper.DELIMITER) .append(parambuf) .append(MessageHelper.DELIMITER) .append(m_startMillis) .append(MessageHelper.DELIMITER) .append(m_endMillis) .append(MessageHelper.DELIMITER) .append(MessageHelper.replaceNewLine(m_stackTrace)) .append(MessageHelper.DELIMITER) .append(MessageHelper.replaceNewLine(m_testDescription)) ; return buf.toString(); } public String getSuiteName() { return m_suiteName; } public String getTestClass() { return m_testClassName; } public String getMethod() { return m_testMethodName; } public String getName() { return m_testName; } public String getStackTrace() { return m_stackTrace; } public long getEndMillis() { return m_endMillis; } public long getStartMillis() { return m_startMillis; } public String[] getParameters() { return m_parameters; } public String[] getParameterTypes() { return m_paramTypes; } public String getTestDescription() { return m_testDescription; } public String toDisplayString() { StringBuffer buf= new StringBuffer(m_testName != null ? m_testName : m_testMethodName); if(null != m_parameters && m_parameters.length > 0) { buf.append("("); for(int i= 0; i < m_parameters.length; i++) { if(i > 0) { buf.append(", "); } if("java.lang.String".equals(m_paramTypes[i]) && !("null".equals(m_parameters[i]) || "\"\"".equals(m_parameters[i]))) { buf.append("\"").append(m_parameters[i]).append("\""); } else { buf.append(m_parameters[i]); } } buf.append(")"); } return buf.toString(); } @Override public boolean equals(Object o) { if(this == o) { return true; } if(o == null || getClass() != o.getClass()) { return false; } final TestResultMessage that = (TestResultMessage) o; if(m_suiteName != null ? !m_suiteName.equals(that.m_suiteName) : that.m_suiteName != null) { return false; } if(m_testName != null ? !m_testName.equals(that.m_testName) : that.m_testName != null) { return false; } if(m_testClassName != null ? !m_testClassName.equals(that.m_testClassName) : that.m_testClassName != null) { return false; } String toDisplayString= toDisplayString(); if(toDisplayString != null ? !toDisplayString.equals(that.toDisplayString()) : that.toDisplayString() != null) { return false; } return true; } @Override public int hashCode() { int result = (m_suiteName != null ? m_suiteName.hashCode() : 0); result = 29 * result + (m_testName != null ? m_testName.hashCode() : 0); result = 29 * result + m_testClassName.hashCode(); result = 29 * result + toDisplayString().hashCode(); return result; } private String[] toString(Object[] objects, Class[] objectClasses) { if(null == objects) { return new String[0]; } List<String> result= Lists.newArrayList(objects.length); for(Object o: objects) { if(null == o) { result.add("null"); } else { String tostring= o.toString(); if("".equals(tostring)) { result.add("\"\""); } else { result.add(MessageHelper.replaceNewLine(tostring)); } } } return result.toArray(new String[result.size()]); } private String[] toString(Class[] classes) { if(null == classes) { return new String[0]; } List<String> result= Lists.newArrayList(classes.length); for(Class cls: classes) { result.add(cls.getName()); } return result.toArray(new String[result.size()]); } /** * @param params * @return */ private String[] extractParamTypes(String[] params) { List<String> result= Lists.newArrayList(params.length); for(String s: params) { result.add(s.substring(0, s.indexOf(':'))); } return result.toArray(new String[result.size()]); } private String[] extractParams(String[] params) { List<String> result= Lists.newArrayList(params.length); for(String s: params) { result.add(MessageHelper.replaceNewLineReplacer(s.substring(s.indexOf(':') + 1))); } return result.toArray(new String[result.size()]); } }
package com.evolveum.midpoint.eclipse.ui.prefs; import java.io.File; import org.eclipse.jface.dialogs.TitleAreaDialog; import org.eclipse.swt.SWT; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; public class ServerEditDialog extends TitleAreaDialog { private Text txtName; private Text txtUrl; private Text txtLogin; private Text txtPassword; private Text txtShortName; private Text txtProperties; private Text txtLogFile; private Button btnTestConnection; private Button btnBrowsePropertiesFile; private Button btnBrowseLogFile; private ServerInfo newDataItem; private ServerInfo existingDataItem; private boolean createNew; public ServerEditDialog(Shell parentShell, ServerInfo dataItemToEdit, boolean createNew) { super(parentShell); existingDataItem = dataItemToEdit; this.createNew = createNew; } public static ServerEditDialog createEdit(Shell shell, ServerInfo data) { return new ServerEditDialog(shell, data, false); } public static ServerEditDialog createNew(Shell shell, ServerInfo data) { return new ServerEditDialog(shell, data, true); } @Override public void create() { super.create(); if (createNew) { setTitle("Add a midPoint server"); } else { setTitle("Edit a midPoint server"); } } @Override protected Control createDialogArea(Composite parent) { Composite area = (Composite) super.createDialogArea(parent); Composite container = new Composite(area, SWT.NONE); container.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); GridLayout layout = new GridLayout(4, false); container.setLayout(layout); createName(container); createUrl(container); createLogin(container); createPassword(container); createShortName(container); createPropertiesFile(container); createLogFile(container); return area; } private void createName(Composite container) { Label label = new Label(container, SWT.NONE); label.setText("Name"); GridData gd = new GridData(); gd.grabExcessHorizontalSpace = true; gd.horizontalSpan = 3; gd.horizontalAlignment = GridData.FILL; txtName = new Text(container, SWT.BORDER); txtName.setLayoutData(gd); if (existingDataItem != null) { txtName.setText(existingDataItem.getName()); } } private void createUrl(Composite container) { Label label = new Label(container, SWT.NONE); label.setText("URL"); GridData gd = new GridData(); gd.grabExcessHorizontalSpace = true; gd.horizontalSpan = 3; gd.horizontalAlignment = GridData.FILL; txtUrl = new Text(container, SWT.BORDER); txtUrl.setLayoutData(gd); if (existingDataItem != null) { txtUrl.setText(existingDataItem.getUrl()); } } private void createLogin(Composite container) { Label label = new Label(container, SWT.NONE); label.setText("Login"); GridData gd = new GridData(); gd.grabExcessHorizontalSpace = true; gd.horizontalSpan = 3; gd.horizontalAlignment = GridData.FILL; txtLogin = new Text(container, SWT.BORDER); txtLogin.setLayoutData(gd); if (existingDataItem != null) { txtLogin.setText(existingDataItem.getLogin()); } } private void createPassword(Composite container) { Label label = new Label(container, SWT.NONE); label.setText("Password"); GridData gd = new GridData(); gd.grabExcessHorizontalSpace = true; gd.horizontalSpan = 2; gd.horizontalAlignment = GridData.FILL; txtPassword = new Text(container, SWT.BORDER); txtPassword.setLayoutData(gd); txtPassword.setEchoChar('*'); if (existingDataItem != null) { txtPassword.setText(existingDataItem.getPassword()); } GridData gd2 = new GridData(); gd2.horizontalAlignment = GridData.FILL; btnTestConnection = new Button(container, SWT.PUSH); btnTestConnection.setText("Test connection"); btnTestConnection.setLayoutData(gd2); btnTestConnection.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent evt) { PluginPreferences.testConnection(txtName.getText(), txtUrl.getText(), txtLogin.getText(), txtPassword.getText()); } }); btnTestConnection.addDisposeListener(event -> btnTestConnection = null); } private void createShortName(Composite container) { Label label = new Label(container, SWT.NONE); label.setText("Short name"); GridData gd = new GridData(); gd.grabExcessHorizontalSpace = true; gd.horizontalSpan = 3; gd.horizontalAlignment = GridData.FILL; txtShortName = new Text(container, SWT.BORDER); txtShortName.setLayoutData(gd); if (existingDataItem != null) { txtShortName.setText(existingDataItem.getShortName()); } } private void createPropertiesFile(Composite container) { Label label = new Label(container, SWT.NONE); label.setText("Properties file"); GridData gd = new GridData(); gd.grabExcessHorizontalSpace = true; gd.horizontalSpan = 2; gd.horizontalAlignment = GridData.FILL; txtProperties = new Text(container, SWT.BORDER); txtProperties.setLayoutData(gd); if (existingDataItem != null) { txtProperties.setText(existingDataItem.getPropertiesFile()); } GridData gd2 = new GridData(); gd2.horizontalAlignment = GridData.FILL; btnBrowsePropertiesFile = new Button(container, SWT.PUSH); btnBrowsePropertiesFile.setText("Browse..."); btnBrowsePropertiesFile.setLayoutData(gd2); btnBrowsePropertiesFile.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent evt) { String newValue = changePressed(); if (newValue != null) { txtProperties.setText(newValue); } } protected String changePressed() { File f = new File(txtProperties.getText()); if (!f.exists()) { f = null; } File d = getFile(f); if (d == null) { return null; } return d.getAbsolutePath(); } }); btnBrowsePropertiesFile.addDisposeListener(event -> btnBrowsePropertiesFile = null); } private void createLogFile(Composite container) { Label label = new Label(container, SWT.NONE); label.setText("Log file (if local)"); GridData gd = new GridData(); gd.grabExcessHorizontalSpace = true; gd.horizontalSpan = 2; gd.horizontalAlignment = GridData.FILL; txtLogFile = new Text(container, SWT.BORDER); txtLogFile.setLayoutData(gd); if (existingDataItem != null) { txtLogFile.setText(existingDataItem.getLogFile()); } GridData gd2 = new GridData(); gd2.horizontalAlignment = GridData.FILL; btnBrowseLogFile = new Button(container, SWT.PUSH); btnBrowseLogFile.setText("Browse..."); btnBrowseLogFile.setLayoutData(gd2); btnBrowseLogFile.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent evt) { String newValue = changePressed(); if (newValue != null) { txtLogFile.setText(newValue); } } protected String changePressed() { File f = new File(txtLogFile.getText()); if (!f.exists()) { f = null; } File d = getFile(f); if (d == null) { return null; } return d.getAbsolutePath(); } }); btnBrowseLogFile.addDisposeListener(event -> btnBrowseLogFile = null); } private File getFile(File startingDirectory) { FileDialog dialog = new FileDialog(getShell(), SWT.OPEN | SWT.SHEET); if (startingDirectory != null) { dialog.setFileName(startingDirectory.getPath()); } String file = dialog.open(); if (file != null) { file = file.trim(); if (file.length() > 0) { return new File(file); } } return null; } @Override protected boolean isResizable() { return true; } // save content of the Text fields because they get disposed // as soon as the Dialog closes private void saveInput() { newDataItem = new ServerInfo(); newDataItem.setName(txtName.getText()); newDataItem.setUrl(txtUrl.getText()); newDataItem.setLogin(txtLogin.getText()); newDataItem.setPassword(txtPassword.getText()); newDataItem.setShortName(txtShortName.getText()); newDataItem.setPropertiesFile(txtProperties.getText()); newDataItem.setLogFile(txtLogFile.getText()); if (existingDataItem != null) { newDataItem.setSelected(existingDataItem.isSelected()); } } public ServerInfo getServerDataItem() { return newDataItem; } @Override protected void okPressed() { saveInput(); super.okPressed(); } }
package org.testng.remote.strprotocol; import static org.testng.internal.Utils.isStringEmpty; import org.testng.ITestContext; import org.testng.ITestResult; import org.testng.SkipException; import org.testng.collections.Lists; import java.io.PrintWriter; import java.io.StringWriter; import java.util.List; /** * An <code>IStringMessage</code> implementation for test results events. * * @author <a href='mailto:the_mindstorm[at]evolva[dot]ro'>Alexandru Popescu</a> */ public class TestResultMessage implements IStringMessage { private static final Object[] EMPTY_PARAMS= new Object[0]; private static final Class[] EMPTY_TYPES= new Class[0]; protected int m_messageType; protected String m_suiteName; protected String m_testName; protected String m_testClassName; protected String m_testMethodName; protected String m_stackTrace; protected long m_startMillis; protected long m_endMillis; protected String[] m_parameters= new String[0]; protected String[] m_paramTypes= new String[0]; private String m_testDescription; private int m_invocationCount; private int m_currentInvocationCount; private String m_instanceName; /** * This constructor is used by the Eclipse client to initialize a result message based * on what was received over the network. */ public TestResultMessage(final int resultType, final String suiteName, final String testName, final String className, final String methodName, final String testDescriptor, String instanceName, final String[] params, final long startMillis, final long endMillis, final String stackTrace, int invocationCount, int currentInvocationCount) { init(resultType, suiteName, testName, className, methodName, stackTrace, startMillis, endMillis, extractParams(params), extractParamTypes(params), testDescriptor, instanceName, invocationCount, currentInvocationCount ); } /** * This constructor is used by RemoteTestNG to initialize a result message * from an ITestResult. */ public TestResultMessage(final String suiteName, final String testName, final ITestResult result) { Throwable throwable = result.getThrowable(); String stackTrace = null; if((ITestResult.FAILURE == result.getStatus()) || (ITestResult.SUCCESS_PERCENTAGE_FAILURE == result.getStatus())) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); Throwable cause= throwable; if (null != cause) { cause.printStackTrace(pw); stackTrace = sw.getBuffer().toString(); } else { stackTrace= "unknown stack trace"; } } else if(ITestResult.SKIP == result.getStatus() && (throwable != null && SkipException.class.isAssignableFrom(throwable.getClass()))) { stackTrace= throwable.getMessage(); } else if (throwable != null) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); throwable.printStackTrace(pw); stackTrace = sw.toString(); } init(MessageHelper.TEST_RESULT + result.getStatus(), suiteName, testName, result.getTestClass().getName(), result.getMethod().getMethod().getName(), MessageHelper.replaceUnicodeCharactersWithAscii(stackTrace), result.getStartMillis(), result.getEndMillis(), toString(result.getParameters(), result.getMethod().getMethod().getParameterTypes()), toString(result.getMethod().getMethod().getParameterTypes()), MessageHelper.replaceUnicodeCharactersWithAscii(result.getName()), MessageHelper.replaceUnicodeCharactersWithAscii(result.getInstanceName()), result.getMethod().getInvocationCount(), result.getMethod().getCurrentInvocationCount() ); } public TestResultMessage(final ITestContext testCtx, final ITestResult result) { this(testCtx.getSuite().getName(), testCtx.getCurrentXmlTest().getName(), result); // this(testCtx.getSuite().getName(), // result.getTestName() != null ? result.getTestName() : result.getName(), result); } private void init(final int resultType, final String suiteName, final String testName, final String className, final String methodName, final String stackTrace, final long startMillis, final long endMillis, final String[] parameters, final String[] types, final String testDescription, String instanceName, int invocationCount, int currentInvocationCount) { m_messageType = resultType; m_suiteName = suiteName; m_testName = testName; m_testClassName = className; m_testMethodName = methodName; m_stackTrace = stackTrace; m_startMillis= startMillis; m_endMillis= endMillis; m_parameters= parameters; m_paramTypes= types; m_testDescription= testDescription; m_invocationCount = invocationCount; m_currentInvocationCount = currentInvocationCount; m_instanceName = instanceName; } public int getResult() { return m_messageType; } @Override public String getMessageAsString() { StringBuffer buf = new StringBuffer(); StringBuffer parambuf = new StringBuffer(); if(null != m_parameters && m_parameters.length > 0) { for (int j = 0; j < m_parameters.length; j++) { if (j > 0) { parambuf.append(MessageHelper.PARAM_DELIMITER); } parambuf.append(m_paramTypes[j] + ":" + m_parameters[j]); } } buf.append(m_messageType) .append(MessageHelper.DELIMITER) .append(m_suiteName) .append(MessageHelper.DELIMITER) .append(m_testName) .append(MessageHelper.DELIMITER) .append(m_testClassName) .append(MessageHelper.DELIMITER) .append(m_testMethodName) .append(MessageHelper.DELIMITER) .append(parambuf) .append(MessageHelper.DELIMITER) .append(m_startMillis) .append(MessageHelper.DELIMITER) .append(m_endMillis) .append(MessageHelper.DELIMITER) .append(MessageHelper.replaceNewLine(m_stackTrace)) .append(MessageHelper.DELIMITER) .append(MessageHelper.replaceNewLine(m_testDescription)) ; return buf.toString(); } public String getSuiteName() { return m_suiteName; } public String getTestClass() { return m_testClassName; } public String getMethod() { return m_testMethodName; } public String getName() { return m_testName; } public String getStackTrace() { return m_stackTrace; } public long getEndMillis() { return m_endMillis; } public long getStartMillis() { return m_startMillis; } public String[] getParameters() { return m_parameters; } public String[] getParameterTypes() { return m_paramTypes; } public String getTestDescription() { return m_testDescription; } public String toDisplayString() { StringBuffer buf= new StringBuffer(m_testName != null ? m_testName : m_testMethodName); if(null != m_parameters && m_parameters.length > 0) { buf.append("("); for(int i= 0; i < m_parameters.length; i++) { if(i > 0) { buf.append(", "); } if("java.lang.String".equals(m_paramTypes[i]) && !("null".equals(m_parameters[i]) || "\"\"".equals(m_parameters[i]))) { buf.append("\"").append(m_parameters[i]).append("\""); } else { buf.append(m_parameters[i]); } } buf.append(")"); } return buf.toString(); } @Override public boolean equals(Object o) { if(this == o) { return true; } if(o == null || getClass() != o.getClass()) { return false; } final TestResultMessage that = (TestResultMessage) o; if(m_suiteName != null ? !m_suiteName.equals(that.m_suiteName) : that.m_suiteName != null) { return false; } if(m_testName != null ? !m_testName.equals(that.m_testName) : that.m_testName != null) { return false; } if(m_testClassName != null ? !m_testClassName.equals(that.m_testClassName) : that.m_testClassName != null) { return false; } String toDisplayString= toDisplayString(); if(toDisplayString != null ? !toDisplayString.equals(that.toDisplayString()) : that.toDisplayString() != null) { return false; } return true; } @Override public int hashCode() { int result = (m_suiteName != null ? m_suiteName.hashCode() : 0); result = 29 * result + (m_testName != null ? m_testName.hashCode() : 0); result = 29 * result + m_testClassName.hashCode(); result = 29 * result + toDisplayString().hashCode(); return result; } private String[] toString(Object[] objects, Class[] objectClasses) { if(null == objects) { return new String[0]; } List<String> result= Lists.newArrayList(objects.length); for(Object o: objects) { if(null == o) { result.add("null"); } else if (o.getClass().isArray()) { String[] strArray = toString((Object[]) o, null); StringBuilder sb = new StringBuilder("["); for (int i = 0; i < strArray.length; i++) { sb.append(strArray[i]); if (i + 1 < strArray.length) { sb.append(","); } } sb.append("]"); result.add(sb.toString()); } else { String tostring= o.toString(); if(isStringEmpty(tostring)) { result.add("\"\""); } else { result.add(MessageHelper.replaceNewLine(tostring)); } } } return result.toArray(new String[result.size()]); } private String[] toString(Class[] classes) { if(null == classes) { return new String[0]; } List<String> result= Lists.newArrayList(classes.length); for(Class cls: classes) { result.add(cls.getName()); } return result.toArray(new String[result.size()]); } /** * @param params * @return */ private String[] extractParamTypes(String[] params) { List<String> result= Lists.newArrayList(params.length); for(String s: params) { result.add(s.substring(0, s.indexOf(':'))); } return result.toArray(new String[result.size()]); } private String[] extractParams(String[] params) { List<String> result= Lists.newArrayList(params.length); for(String s: params) { result.add(MessageHelper.replaceNewLineReplacer(s.substring(s.indexOf(':') + 1))); } return result.toArray(new String[result.size()]); } public int getInvocationCount() { return m_invocationCount; } public int getCurrentInvocationCount() { return m_currentInvocationCount; } @Override public String toString() { return "[TestResultMessage suite:" + m_suiteName + " test:" + m_testName + " method:" + m_testMethodName + "]"; } public void setParameters(String[] params) { m_parameters = extractParams(params); m_paramTypes = extractParamTypes(params); } public String getInstanceName() { return m_instanceName; } }
package com.python.pydev.refactoring.refactorer.refactorings.rename; public class RenameLocalVariableRefactoringTest extends RefactoringTestBase { public static void main(String[] args) { try { RenameLocalVariableRefactoringTest test = new RenameLocalVariableRefactoringTest(); test.setUp(); test.testRename2(); test.tearDown(); junit.textui.TestRunner.run(RenameLocalVariableRefactoringTest.class); } catch (Throwable e) { e.printStackTrace(); } } private String getDefaultDocStr() { return "" + "def method():\n"+ " %s = 2\n"+ " print %s\n"+ ""; } public void testRenameErr() throws Exception { int line = 2; int col = 10; checkRename(getDefaultDocStr(), line, col, "bb", true, false, "aaa bb"); } public void testRenameInstance2() throws Exception { String str = "" + "class Foo:\n" + " def m1(self,%s):\n" +//we want to target only the bb in this method and not in the next " print %s\n" + " def m2(self,bb):\n" + " return bb\n" + "\n"; int line = 2; int col = 16; checkRename(str, line, col); } public void testRenameParameter() throws Exception { String str = "" + "class Foo:\n" + " def m1(self,%s):\n" +//we want to target only the parameter foo in this method and not the attribute " print %s\n" + " print self.foo" + "\n"; int line = 1; int col = 16; checkRename(str, line, col, "foo", false); } public void testRenameParameter2() throws Exception { String str = "" + "class Foo:\n" + " def m1(self,%s):\n" +//we want to target only the parameter foo in this method and not the attribute " print %s\n" + " print %s.bla" + "\n"; int line = 1; int col = 16; checkRename(str, line, col, "foo", false); } public void testRenameLocalMethod() throws Exception { String str = "" + "def Foo():\n" + " def %s():\n" + " pass\n" + " if %s(): pass\n" + "\n" + ""; int line = 1; int col = 9; checkRename(str, line, col, "met1", false, true); } public void testRenameLocalMethod2() throws Exception { String str = "" + "def %s():\n" + " def mm():\n" + " print %s()\n" + "\n" + ""; int line = 0; int col = 5; checkRename(str, line, col, "met1", false, true); } public void testRenameImportLocally() throws Exception { String str = "" + "from foo import %s\n" + "def mm():\n" + " print %s\n" + "\n" + ""; int line = 0; int col = 17; checkRename(str, line, col, "bla", false, true); } public void testRenameImportLocally2() throws Exception { String str = "" + "import %s\n" + "def run():\n" + " print %s.getopt()\n" + "\n" + ""; int line = 0; int col = 10; checkRename(str, line, col, "getopt", false, true); } public void testRenameImportLocally3() throws Exception { String str = "" + "import %s\n" + "def run():\n" + " print %s\n" + "\n" + ""; int line = 0; int col = 10; checkRename(str, line, col, "sys", false, true); } public void testRenameImportLocally4() throws Exception { String str = "" + "from extendable.constants import %s\n" + "def run():\n" + " print %s\n" + "\n" + ""; int line = 2; int col = 11; checkRename(str, line, col, "CONSTANT1", false, true); } public void testRenameMethodImportLocally() throws Exception { String str = "" + "from testAssist.assist.ExistingClass import %s\n" + "def run():\n" + " print %s\n" + "\n" + ""; int line = 2; int col = 11; checkRename(str, line, col, "existingMethod", false, true); } public void testRenameMethodImportLocally2() throws Exception { String str = "" + "from testAssist.assist import ExistingClass\n" + "def run():\n" + " print ExistingClass.%s\n" + "\n" + ""; int line = 2; int col = 26; checkRename(str, line, col, "existingMethod", false, true); } public void testRenameClassImportLocally() throws Exception { String str = "" + "from testAssist.assist import %s\n" + "def run():\n" + " print %s\n" + "\n" + ""; int line = 2; int col = 11; checkRename(str, line, col, "ExistingClass", false, true); } public void testRenameMethodLocally() throws Exception { String str = "" + "class Foo:\n" + " def %s(self):\n" + " tup = 10\n" + " tup[1].append(1)\n" + ""; int line = 1; int col = 9; checkRename(str, line, col, "foo", false, true); } public void testRenameLocalAttr() throws Exception { String str = "" + "class Foo:\n" + " def foo(self):\n" + " %s = [[],[]]\n" + " %s[1].append(1)\n" + ""; int line = 2; int col = 9; checkRename(str, line, col, "tup", false, true); } public void testRenameAttribute() throws Exception { String str = "" + "class Foo(object):\n" + " def %s(self):\n" + " pass\n" + " \n" + "foo = Foo()\n" + "foo.%s()\n" + ""; int line = 1; int col = 9; checkRename(str, line, col, "met1", false, true); } public void testRenameUndefined() throws Exception { String str = "" + "from a import %s\n" + "print %s\n" + ""; int line = 0; int col = 15; checkRename(str, line, col, "foo", false, true); } public void testNotFoundAttr() throws Exception { String str = "" + "class Foo:\n" + " def %s(self, foo):\n" + " print foo.%s\n" + ""; int line = 2; int col = 19; checkRename(str, line, col, "met1", false, true); } public void testMultiStr() throws Exception { String str = "" + "%s = str(1)+ 'foo2'\n" + "print %s\n" + ""; int line = 0; int col = 1; checkRename(str, line, col, "ss", false, true); } public void testDict() throws Exception { String str = "" + "%s = {}\n" + "print %s[1]\n" + ""; int line = 0; int col = 1; checkRename(str, line, col, "ddd", false, true); } public void testRenameInstance() throws Exception { String str=getDefaultDocStr(); int line = 2; int col = 10; checkRename(str, line, col); } public void testImport() throws Exception { String str = "" + "import os.%s\n" + "print os.%s\n" + ""; int line = 1; int col = 10; checkRename(str, line, col, "path", false, true); } public void testLocalNotGotten() throws Exception { String str = "" + "def m1():\n" + " foo.%s = 10\n" + //accessing this should not affect the locals (not taking methods into account) " print foo.%s\n" + " bla = 20\n" + " print bla\n" + ""; int line = 1; int col = 9; checkRename(str, line, col, "bla", false, true); } public void testLocalNotGotten2() throws Exception { String str = "" + "def m1():\n" + " print foo.%s\n" + //accessing this should not affect the locals (not taking methods into account) " print bla\n" + ""; int line = 1; int col = 15; checkRename(str, line, col, "bla", false, true); } public void testLocalGotten() throws Exception { String str = "" + "def m1():\n" + " print foo.bla\n" + " print %s\n" + //should only affect the locals ""; int line = 2; int col = 11; checkRename(str, line, col, "bla", false, true); } public void testRenameSelf() throws Exception { String str = "" + "def checkProps(%s):\n" + " getattr(%s).value\n" + "\n"; int line = 0; int col = 17; checkRename(str, line, col, "fff", false, true); } public void testRenameClassVar() throws Exception { String str = "" + "class Foo:\n" + " %s = ''\n" + " def toSimulator(self):\n" + " print self.%s\n" + ""; int line = 3; int col = 21; checkRename(str, line, col, "vlMolecularWeigth", false, true); } public void testRenameNonLocal() throws Exception { String str = "" + "import b \n" + "print b.%s\n" + "class C2:\n" + " def m1(self):\n" + " barr = 10\n" + //should not rename the local "\n" + ""; int line = 1; int col = 9; checkRename(str, line, col, "barr", false, true); } public void testRenameNonLocal2() throws Exception { String str = "" + "def m1():\n" + " bar = 10\n" + " bar.%s\n" + //selected (Foo) " foop = 20\n" + ""; int line = 2; int col = 9; checkRename(str, line, col, "foop", false, true); } public void testRename1() throws Exception { String str = "" + "import pprint\n" + "def myHook():\n" + " pprint.%s()\n" + ""; int line = 2; int col = 12; checkRename(str, line, col, "PrettyPrinter", false, true); } public void testRename2() throws Exception { String str = "" + "import bla as %s\n" + "raise %s.ffff(msg)\n" + "\n" + ""; int line = 0; int col = 15; checkRename(str, line, col, "fooo", false, true); } public void testRename3() throws Exception { String str = "" + "def m1(a):\n" + " a.data.%s\n" + ""; int line = 1; int col = 12; checkRename(str, line, col, "fooo", false, true); } }
package se.kth.id2212.project.fish.server; import se.kth.id2212.project.fish.common.Message; import se.kth.id2212.project.fish.common.MessageDescriptor; import se.kth.id2212.project.fish.common.ClientAddress; import se.kth.id2212.project.fish.common.ProtocolException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.util.ArrayList; public class ClientHandler implements Runnable { private ObjectInputStream in; private ObjectOutputStream out; private Server server; private Socket clientSocket; public ClientHandler(Server server, Socket socket) { this.server = server; this.clientSocket = socket; } @Override public void run() { if (connect() && register()) serve(); server.removeFileList(clientSocket); disconnect(); } private void clientPrint(String msg) { System.out.println("(" + clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort() + ") " + msg); } private boolean connect() { try { out = new ObjectOutputStream(clientSocket.getOutputStream()); out.flush(); in = new ObjectInputStream(clientSocket.getInputStream()); clientPrint("Connected"); return true; } catch (IOException e) { clientPrint("Connecting failed"); return false; } } private boolean register() { try { Message m = (Message) in.readObject(); if (m.getDescriptor() != MessageDescriptor.REGISTER) { throw new ProtocolException("Did not receive REGISTER"); } ArrayList<String> sharedFiles = (ArrayList<String>) m.getContent(); server.addFileList(clientSocket, sharedFiles); out.writeObject(new Message(MessageDescriptor.REGISTER_OK, null)); clientPrint("Registered"); return true; } catch (IOException | ClassNotFoundException | ProtocolException e) { clientPrint("Registration failed"); return false; } } private void serve() { for (boolean stop = false; !stop; ) { try { Message m = (Message) in.readObject(); switch (m.getDescriptor()) { case SEARCH: search((String) m.getContent()); break; case UNREGISTER: unregister(); stop = true; break; case UPDATE: update((ArrayList<String>) m.getContent()); break; default: throw new ProtocolException("Received " + m.getDescriptor().name()); } } catch (IOException | ClassNotFoundException | ProtocolException e) { clientPrint("Error: " + e.getMessage()); stop = true; } } } private void search(String request) throws IOException { ArrayList<ClientAddress> result = server.searchFileLists(clientSocket, request); out.writeObject(new Message(MessageDescriptor.SEARCH_RESULT, result)); clientPrint("Searched"); } private void update(ArrayList<String> sharedFiles) throws IOException { server.addFileList(clientSocket, sharedFiles); out.writeObject(new Message(MessageDescriptor.UPDATE_OK, null)); clientPrint("Updated"); } private void unregister() throws IOException { out.writeObject(new Message(MessageDescriptor.UNREGISTER_OK, null)); clientPrint("Unregistered"); } private boolean disconnect() { try { in.close(); out.close(); clientSocket.close(); clientPrint("Disconnected"); return true; } catch (IOException e) { clientPrint("Disconnecting failed"); return false; } } }
package team.creative.creativecore.common.gui; import java.util.Iterator; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Consumer; import org.apache.commons.lang3.ArrayUtils; import com.mojang.blaze3d.systems.RenderSystem; import com.mojang.blaze3d.vertex.PoseStack; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import team.creative.creativecore.common.gui.event.GuiControlChangedEvent; import team.creative.creativecore.common.gui.event.GuiControlClickEvent; import team.creative.creativecore.common.gui.event.GuiEvent; import team.creative.creativecore.common.gui.event.GuiEventManager; import team.creative.creativecore.common.gui.event.GuiTooltipEvent; import team.creative.creativecore.common.gui.flow.GuiFlow; import team.creative.creativecore.common.gui.style.ControlFormatting; import team.creative.creativecore.common.gui.sync.LayerOpenPacket; import team.creative.creativecore.common.util.math.geo.Rect; public class GuiParent extends GuiControl implements IGuiParent, Iterable<GuiChildControl> { private GuiEventManager eventManager; protected List<GuiChildControl> controls = new CopyOnWriteArrayList<>(); protected List<GuiChildControl> hoverControls = new CopyOnWriteArrayList<>(); public GuiFlow flow; public Align align = Align.LEFT; public VAlign valign = VAlign.TOP; public int spacing = 2; public GuiParent(String name, GuiFlow flow) { super(name); this.flow = flow; } public GuiParent(String name, GuiFlow flow, int width, int height) { super(name, width, height); this.flow = flow; } public GuiParent(String name, GuiFlow flow, Align align, VAlign valign) { this(name, flow); this.align = align; this.valign = valign; } public GuiParent(String name, GuiFlow flow, int width, int height, Align align, VAlign valign) { this(name, flow, width, height); this.align = align; this.valign = valign; } public GuiParent(String name, GuiFlow flow, int width, int height, VAlign valign) { this(name, flow, width, height, Align.LEFT, valign); } public GuiParent(String name) { this(name, GuiFlow.STACK_X); } public GuiParent() { this(""); } public GuiParent(GuiFlow flow) { this("", flow); } @Override public boolean isClient() { return getParent().isClient(); } public double getScaleFactor() { return 1; } public double getOffsetY() { return 0; } public double getOffsetX() { return 0; } @Override public boolean isExpandableX() { if (super.isExpandableX()) return true; for (GuiChildControl child : controls) if (child.control.isExpandableX()) return true; return false; } @Override public boolean isExpandableY() { if (super.isExpandableY()) return true; for (GuiChildControl child : controls) if (child.control.isExpandableY()) return true; return false; } private static GuiControl get(String name, List<GuiChildControl> collection) { for (int i = 0; i < collection.size(); i++) { GuiControl control = collection.get(i).control; if (control.name.equalsIgnoreCase(name)) return control; else if (control instanceof GuiParent) { if (control.name.isBlank()) { GuiControl result = ((GuiParent) control).get(name); if (result != null) return result; } else if (name.startsWith(control.name + ".")) return ((GuiParent) control).get(name.substring(control.name.length() + 1)); } } return null; } public GuiControl get(String name) { GuiControl result = get(name, controls); if (result != null) return result; return get(name, hoverControls); } public boolean has(String name) { return get(name) != null; } public GuiChildControl add(GuiControl control) { control.setParent(this); GuiChildControl child = new GuiChildControl(control); controls.add(child); return child; } public GuiChildControl addHover(GuiControl control) { control.setParent(this); GuiChildControl child = new GuiChildControl(control); hoverControls.add(child); return child; } public boolean remove(GuiChildControl control) { return controls.remove(control) || hoverControls.remove(control); } public GuiChildControl remove(GuiControl control) { for (int i = 0; i < controls.size(); i++) { GuiChildControl child = controls.get(i); if (child.control == control) { controls.remove(i); return child; } } for (int i = 0; i < hoverControls.size(); i++) { GuiChildControl child = hoverControls.get(i); if (child.control == control) { hoverControls.remove(i); return child; } } return null; } public void remove(String... include) { controls.removeIf((x) -> ArrayUtils.contains(include, x.control.name)); hoverControls.removeIf((x) -> ArrayUtils.contains(include, x.control.name)); } public void removeExclude(String... exclude) { controls.removeIf((x) -> !ArrayUtils.contains(exclude, x.control.name)); hoverControls.removeIf((x) -> !ArrayUtils.contains(exclude, x.control.name)); } public boolean isEmpty() { return controls.isEmpty() && hoverControls.isEmpty(); } public void clear() { controls.clear(); hoverControls.clear(); } public int size() { return controls.size() + hoverControls.size(); } @Override public Iterator<GuiChildControl> iterator() { return new Iterator<GuiChildControl>() { Iterator<GuiChildControl> itr = hoverControls.iterator(); boolean first = true; @Override public boolean hasNext() { if (itr.hasNext()) return true; if (first) { itr = controls.iterator(); first = false; } return itr.hasNext(); } @Override public GuiChildControl next() { return itr.next(); } }; } protected void renderContent(PoseStack matrix, Rect contentRect, Rect realContentRect, int mouseX, int mouseY, List<GuiChildControl> collection, double scale, double xOffset, double yOffset, boolean hover) { for (int i = collection.size() - 1; i >= 0; i GuiChildControl child = collection.get(i); GuiControl control = child.control; if (!control.visible) continue; Rect controlRect = contentRect.child(child.rect, scale, xOffset, yOffset); Rect realRect = realContentRect.intersection(controlRect); if (realRect != null || hover) { if (hover) RenderSystem.disableScissor(); else realRect.scissor(); matrix.pushPose(); matrix.translate((child.getX() + xOffset) * scale, (child.getY() + yOffset) * scale, 10); control.render(matrix, child, controlRect, hover ? controlRect : realRect, mouseX, mouseY); matrix.popPose(); } } } @Override @OnlyIn(value = Dist.CLIENT) protected void renderContent(PoseStack matrix, GuiChildControl control, Rect contentRect, Rect realContentRect, int mouseX, int mouseY) { if (realContentRect == null) return; double scale = getScaleFactor(); double xOffset = getOffsetX(); double yOffset = getOffsetY(); renderContent(matrix, contentRect, realContentRect, mouseX, mouseY, controls, scale, xOffset, yOffset, false); renderContent(matrix, contentRect, realContentRect, mouseX, mouseY, hoverControls, scale, xOffset, yOffset, true); super.renderContent(matrix, control, contentRect, realContentRect, mouseX, mouseY); } @Override @OnlyIn(value = Dist.CLIENT) protected void renderContent(PoseStack matrix, GuiChildControl control, Rect rect, int mouseX, int mouseY) {} @Override public boolean isContainer() { return getParent().isContainer(); } @Override public void init() { for (GuiChildControl child : this) child.control.init(); } @Override public void closed() { for (GuiChildControl child : this) child.control.closed(); } @Override public void tick() { for (GuiChildControl child : this) child.control.tick(); } @Override public void closeTopLayer() { getParent().closeTopLayer(); } @Override public GuiLayer openLayer(LayerOpenPacket packet) { return getParent().openLayer(packet); } @Override public GuiTooltipEvent getTooltipEvent(Rect rect, double x, double y) { GuiTooltipEvent event = super.getTooltipEvent(rect, x, y); if (event != null) return event; x *= getScaleFactor(); y *= getScaleFactor(); int offset = getContentOffset(); x += -getOffsetX() - offset; y += -getOffsetY() - offset; for (GuiChildControl child : this) if (child.control.isInteractable() && child.isMouseOver(x, y)) { event = child.control.getTooltipEvent(child.rect, x - child.getX(), y - child.getY()); if (event != null) return event; } return null; } @Override public boolean testForDoubleClick(Rect rect, double x, double y) { x *= getScaleFactor(); y *= getScaleFactor(); int offset = getContentOffset(); x += -getOffsetX() - offset; y += -getOffsetY() - offset; for (GuiChildControl child : this) if (child.control.isInteractable() && child.control.testForDoubleClick(child.rect, x - child.getX(), y - child.getY())) return true; return false; } @Override public void mouseMoved(Rect rect, double x, double y) { x *= getScaleFactor(); y *= getScaleFactor(); int offset = getContentOffset(); x += -getOffsetX() - offset; y += -getOffsetY() - offset; for (GuiChildControl child : this) if (child.control.isInteractable()) child.control.mouseMoved(child.rect, x - child.getX(), y - child.getY()); } @Override public boolean mouseClicked(Rect rect, double x, double y, int button) { x *= getScaleFactor(); y *= getScaleFactor(); int offset = getContentOffset(); x += -getOffsetX() - offset; y += -getOffsetY() - offset; boolean result = false; for (GuiChildControl child : this) if (!result && child.control.isInteractable() && child.isMouseOver(x, y) && child.control.mouseClicked(child.rect, x - child.getX(), y - child.getY(), button)) { raiseEvent(new GuiControlClickEvent(child.control, button, false)); result = true; } else child.control.looseFocus(); return result; } @Override public boolean mouseDoubleClicked(Rect rect, double x, double y, int button) { x *= getScaleFactor(); y *= getScaleFactor(); int offset = getContentOffset(); x += -getOffsetX() - offset; y += -getOffsetY() - offset; boolean result = false; for (GuiChildControl child : this) if (!result && child.control.isInteractable() && child.isMouseOver(x, y) && child.control.mouseDoubleClicked(child.rect, x - child.getX(), y - child.getY(), button)) { raiseEvent(new GuiControlClickEvent(child.control, button, false)); result = true; } else child.control.looseFocus(); return result; } @Override public void mouseReleased(Rect rect, double x, double y, int button) { x *= getScaleFactor(); y *= getScaleFactor(); int offset = getContentOffset(); x += -getOffsetX() - offset; y += -getOffsetY() - offset; for (GuiChildControl child : this) if (child.control.isInteractable()) child.control.mouseReleased(child.rect, x - child.getX(), y - child.getY(), button); } @Override public void mouseDragged(Rect rect, double x, double y, int button, double dragX, double dragY, double time) { x *= getScaleFactor(); y *= getScaleFactor(); int offset = getContentOffset(); x += -getOffsetX() - offset; y += -getOffsetY() - offset; for (GuiChildControl child : this) if (child.control.isInteractable()) child.control.mouseDragged(child.rect, x - child.getX(), y - child.getY(), button, dragX, dragY, time); } @Override public boolean mouseScrolled(Rect rect, double x, double y, double delta) { x *= getScaleFactor(); y *= getScaleFactor(); int offset = getContentOffset(); x += -getOffsetX() - offset; y += -getOffsetY() - offset; for (GuiChildControl child : this) if (child.control.isInteractable() && child.isMouseOver(x, y) && child.control.mouseScrolled(child.rect, x - child.getX(), y - child.getY(), delta)) return true; return false; } @Override public boolean keyPressed(int keyCode, int scanCode, int modifiers) { for (GuiChildControl child : this) if (child.control.isInteractable() && child.control.keyPressed(keyCode, scanCode, modifiers)) return true; return false; } @Override public boolean keyReleased(int keyCode, int scanCode, int modifiers) { for (GuiChildControl child : this) if (child.control.isInteractable() && child.control.keyReleased(keyCode, scanCode, modifiers)) return true; return false; } @Override public boolean charTyped(char codePoint, int modifiers) { for (GuiChildControl child : this) if (child.control.isInteractable() && child.control.charTyped(codePoint, modifiers)) return true; return false; } @Override public void looseFocus() { for (GuiChildControl child : this) child.control.looseFocus(); } @Override public void raiseEvent(GuiEvent event) { if (getParent() == null) return; if (eventManager != null) eventManager.raiseEvent(event); if (!event.isCanceled()) getParent().raiseEvent(event); } public void registerEventClick(Consumer<GuiControlClickEvent> consumer) { registerEvent(GuiControlClickEvent.class, consumer); } public void registerEventChanged(Consumer<GuiControlChangedEvent> consumer) { registerEvent(GuiControlChangedEvent.class, consumer); } public <T extends GuiEvent> void registerEvent(Class<T> clazz, Consumer<T> action) { if (eventManager == null) eventManager = new GuiEventManager(); eventManager.registerEvent(clazz, action); } @Override public String getNestedName() { if (name.isBlank()) { if (getParent() instanceof GuiControl) return ((GuiControl) getParent()).getNestedName(); return ""; } return super.getNestedName(); } @Override public void flowX(int width, int preferred) { flow.flowX(controls, spacing, align, width, preferred); } @Override public void flowY(int height, int preferred) { flow.flowY(controls, spacing, valign, height, preferred); } @Override public int getMinWidth() { return flow.minWidth(controls, spacing); } @Override protected int preferredWidth() { return flow.preferredWidth(controls, spacing); } @Override public int getMinHeight() { return flow.minHeight(controls, spacing); } @Override protected int preferredHeight() { return flow.preferredHeight(controls, spacing); } @Override public ControlFormatting getControlFormatting() { return ControlFormatting.TRANSPARENT; } }
package vn.com.hiringviet.service.impl; import java.text.MessageFormat; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import vn.com.hiringviet.auth.AuthenticationUtil; import vn.com.hiringviet.constant.ConstantValues; import vn.com.hiringviet.dao.ApplyDAO; import vn.com.hiringviet.dto.ApplyDTO; import vn.com.hiringviet.model.Account; import vn.com.hiringviet.model.Apply; import vn.com.hiringviet.model.Job; import vn.com.hiringviet.model.Member; import vn.com.hiringviet.model.Message; import vn.com.hiringviet.service.AccountService; import vn.com.hiringviet.service.ApplyService; import vn.com.hiringviet.service.JobService; import vn.com.hiringviet.service.LoggerService; import vn.com.hiringviet.service.MailService; import vn.com.hiringviet.service.MailboxService; import vn.com.hiringviet.util.FileUtil; import vn.com.hiringviet.util.Utils; @Service("applyService") @Transactional public class ApplyServiceImpl implements ApplyService { private static final String CONFIRM_APPLY_DENIED_SIGN = "Please update personal information to be more trusted"; @Autowired private ApplyDAO applyDao; @Autowired private JobService jobService; @Autowired private MailboxService mailBoxService; @Autowired private MailService mailService; @Autowired private AccountService accountService; @Autowired private LoggerService loggerService; @Override public void addApply(Apply apply) { applyDao.create(apply); } @Override public void addApplyByDTO(ApplyDTO applyDTO, Member member) { String[] jobIds = applyDTO.getJobList().split("\\+"); String description = applyDTO.getDescription(); for (String id : jobIds) { Job job = jobService.getJobById(Integer.parseInt(id)); Apply apply = new Apply(); apply.setJob(job); apply.setMember(member); apply.setDisscription(description); apply.setCurriculumVitae(applyDTO.getCurriculumVitae()); apply.setChangeLog(Utils.createDefaultChangeLog()); apply.setAccepted(null); applyDao.addApplyByNativeSQL(apply); String info = "<p><b>" + member.getFirstName() + " " + member.getLastName() + "</b> vừa apply vào công việc \"" + job.getTitle() + "\"</p>"; info += "</p><a href=\"/company/apply?companyId=" + job.getCompany().getId() + "&jobId=" + job.getId() + "\">Xác thực ngay!</a><p>"; loggerService.create(job.getCompany().getAccount().getId(), member.getAccount().getId(), info, false); } } @Override public List<Apply> findApplies(int jobId) { Job job = jobService.getJobById(jobId); return applyDao.getApplies(job); } @Override public Apply get(int id) { return applyDao.findOne(id); } @Override public void update(Apply apply) { applyDao.update(apply); } @Override public List<ApplyDTO> getAllApplyByJobId(Integer jobId) { return applyDao.getAllApplyByJobId(jobId); } public void sendApprovedApplyMessage(int applyId, Message approveMessage) { Apply apply = get(applyId); Account receiverAcc = apply.getMember().getAccount(); Account company = AuthenticationUtil.getLoggedAccount(); if (receiverAcc != null && company != null && apply != null) { approveMessage.setSenderAccount(company); approveMessage.setOwnerAccount(receiverAcc); approveMessage.setChangeLog(Utils.createDefaultChangeLog()); apply.setAccepted(true); this.update(apply); mailBoxService.createMessageNativeSQL(approveMessage); sendEmailConfirmApply(receiverAcc, apply, true, approveMessage.getContent()); } else { throw new RuntimeException("Internal Error"); } } private void sendEmailConfirmApply(Account to, Apply apply, boolean isApproved, String approveMessage) { String title = null; if(isApproved) { title = "HiringViet - Your apply has been accepted"; } else { title = "HiringViet - Your apply has been denied"; } String content = FileUtil.getConfigProperties().getProperty("email.confirmApply"); content = MessageFormat.format(content, to.getMember().getFirstName() + to.getMember().getLastName(), apply.getJob().getTitle(), isApproved ? "APPROVED": "DENIED", approveMessage); mailService.sendMail(to.getEmail(), title, content); } @Override public void sendDeniedApplyMessage(int applyId) { String title = ConstantValues.MESSAGE_PROPS.getProperty("apply.deniedTitle"); String content = ConstantValues.MESSAGE_PROPS .getProperty("apply.deniedContent"); Apply apply = get(applyId); Account receiverAcc = apply.getMember().getAccount(); Account company = AuthenticationUtil.getLoggedAccount(); if (receiverAcc != null && company != null && apply != null) { Member receiverMember = receiverAcc.getMember(); title = MessageFormat.format(title, apply.getApplyID(),company.getCompany().getDisplayName()); content = MessageFormat.format( content, receiverMember.getFirstName() + receiverMember.getLastName(), company.getCompany().getDisplayName()); Message message = new Message(); message.setOwnerAccount(receiverAcc); message.setSenderAccount(company); message.setTitle(title); message.setContent(content); apply.setAccepted(false); this.update(apply); mailBoxService.createMessageNativeSQL(message); sendEmailConfirmApply(receiverAcc, apply, false, content); } else { throw new RuntimeException("Internal Error"); } } }
package website.automate.waml.io.model.step; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import website.automate.waml.io.model.criteria.IncludeCriteria; public class IncludeStep extends BasicStep { static final String TYPE_NAME = "include"; private IncludeCriteria include; @JsonCreator public IncludeStep(@JsonProperty("when") String when, @JsonProperty("register") String register, @JsonProperty("timeout") String timeout, @JsonProperty("invert") String invert, @JsonProperty("include") IncludeCriteria include){ super(when, register, timeout, invert); this.include = include; } public IncludeCriteria getInclude() { return include; } }
package org.hisp.dhis.android.core.trackedentity; import org.hisp.dhis.android.core.data.database.SyncedDatabaseMockIntegrationShould; import org.junit.Test; import org.junit.runner.RunWith; import java.util.List; import androidx.test.runner.AndroidJUnit4; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @RunWith(AndroidJUnit4.class) public class TrackedEntityInstanceCollectionRepositoryMockIntegrationShould extends SyncedDatabaseMockIntegrationShould { @Test public void allow_access_to_all_teis_without_children() { List<TrackedEntityInstance> trackedEntityInstances = d2.trackedEntityModule().trackedEntityInstances.get(); assertThat(trackedEntityInstances.size(), is(2)); TrackedEntityInstance trackedEntityInstance = trackedEntityInstances.get(0); assertThat(trackedEntityInstance.uid(), is("nWrB0TfWlvh")); assertThat(trackedEntityInstance.organisationUnit(), is("DiszpKrYNg8")); assertThat(trackedEntityInstance.trackedEntityAttributeValues() == null, is(true)); } @Test public void allow_access_to_one_tei_without_children() { TrackedEntityInstance tei = d2.trackedEntityModule().trackedEntityInstances.uid("nWrB0TfWlvh").get(); assertThat(tei.uid(), is("nWrB0TfWlvh")); assertThat(tei.organisationUnit(), is("DiszpKrYNg8")); assertThat(tei.trackedEntityAttributeValues() == null, is(true)); } @Test public void include_enrollments_as_children() { TrackedEntityInstance tei = d2.trackedEntityModule().trackedEntityInstances .withEnrollments().uid("nWrB0TfWlvh").get(); assertThat(tei.enrollments().size(), is(1)); assertThat(tei.enrollments().get(0).uid(), is("enroll1")); } @Test public void include_tracked_entity_attribute_values_as_children() { TrackedEntityInstance tei = d2.trackedEntityModule().trackedEntityInstances .withTrackedEntityAttributeValues().uid("nWrB0TfWlvh").get(); assertThat(tei.trackedEntityAttributeValues().size(), is(1)); assertThat(tei.trackedEntityAttributeValues().get(0).trackedEntityAttribute(), is("lZGmxYbs97q")); assertThat(tei.trackedEntityAttributeValues().get(0).value(), is("4081507")); } @Test public void include_relationships_as_children() { TrackedEntityInstance tei = d2.trackedEntityModule().trackedEntityInstances .withRelationships().uid("nWrB0TfWlvh").get(); assertThat(tei.relationships().size(), is(2)); assertThat(tei.relationships().get(0).uid(), is("AJOytZW7OaI")); } @Test public void include_relationship_items_in_relationships_as_children() { TrackedEntityInstance tei = d2.trackedEntityModule().trackedEntityInstances .withRelationships().uid("nWrB0TfWlvh").get(); assertThat(tei.relationships().size(), is(2)); assertThat(tei.relationships().get(0).from().elementUid(), is("nWrB0TfWlvh")); assertThat(tei.relationships().get(0).to().elementUid(), is("nWrB0TfWlvh")); } @Test public void add_tracked_entity_instances_to_the_repository() { List<TrackedEntityInstance> trackedEntityInstances1 = d2.trackedEntityModule().trackedEntityInstances.get(); assertThat(trackedEntityInstances1.size(), is(2)); String teiUid = d2.trackedEntityModule().trackedEntityInstances.add( TrackedEntityInstanceCreateProjection.create("DiszpKrYNg8", "nEenWmSyUEp")); List<TrackedEntityInstance> trackedEntityInstances2 = d2.trackedEntityModule().trackedEntityInstances.get(); assertThat(trackedEntityInstances2.size(), is(3)); TrackedEntityInstance trackedEntityInstance = d2.trackedEntityModule().trackedEntityInstances.uid(teiUid).get(); assertThat(trackedEntityInstance.uid(), is(teiUid)); } }
package za.co.paulscott.musicgraph.entities.geo; /** * A country should be a node, with all places in that country as sub nodes. * Hopefully that will enable easy traversal from specific places to country and vice versa * * @author paul * */ public class Country { private String isoCode; private String iso3Code; private int isoNumericCode; private String fips; private String country; private String capital; private int area; // (in sq km) private int population; private String continent; private String tld; private String currencyCode; private String currencyName; private String phone; private String postalCodeFormat; private String postalCodeRegex; private String languages; private String neighbours; private String equivalentFipsCode; public String getIsoCode() { return isoCode; } public void setIsoCode(String isoCode) { this.isoCode = isoCode; } public String getIso3Code() { return iso3Code; } public void setIso3Code(String iso3Code) { this.iso3Code = iso3Code; } public int getIsoNumericCode() { return isoNumericCode; } public void setIsoNumericCode(int isoNumericCode) { this.isoNumericCode = isoNumericCode; } public String getFips() { return fips; } public void setFips(String fips) { this.fips = fips; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCapital() { return capital; } public void setCapital(String capital) { this.capital = capital; } public int getArea() { return area; } public void setArea(int area) { this.area = area; } public int getPopulation() { return population; } public void setPopulation(int population) { this.population = population; } public String getContinent() { return continent; } public void setContinent(String continent) { this.continent = continent; } public String getTld() { return tld; } public void setTld(String tld) { this.tld = tld; } public String getCurrencyCode() { return currencyCode; } public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; } public String getCurrencyName() { return currencyName; } public void setCurrencyName(String currencyName) { this.currencyName = currencyName; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPostalCodeFormat() { return postalCodeFormat; } public void setPostalCodeFormat(String postalCodeFormat) { this.postalCodeFormat = postalCodeFormat; } public String getPostalCodeRegex() { return postalCodeRegex; } public void setPostalCodeRegex(String postalCodeRegex) { this.postalCodeRegex = postalCodeRegex; } public String getLanguages() { return languages; } public void setLanguages(String languages) { this.languages = languages; } public String getNeighbours() { return neighbours; } public void setNeighbours(String neighbours) { this.neighbours = neighbours; } public String getEquivalentFipsCode() { return equivalentFipsCode; } public void setEquivalentFipsCode(String equivalentFipsCode) { this.equivalentFipsCode = equivalentFipsCode; } }
package org.deviceconnect.android.profile.restful.test; import android.support.test.runner.AndroidJUnit4; import org.deviceconnect.message.DConnectMessage; import org.deviceconnect.message.DConnectResponseMessage; import org.deviceconnect.profile.AuthorizationProfileConstants; import org.deviceconnect.profile.DConnectProfileConstants; import org.junit.Test; import org.junit.runner.RunWith; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; /** * URLmethod * GET. * @author NTT DOCOMO, INC. */ @RunWith(AndroidJUnit4.class) public class FailAllGetControlTestCase extends RESTfulDConnectTestCase { /** * : {@value} . */ public static final String PROFILE_NAME = "allGetControl"; /** * : {@value} . */ private static final String INTERFACE_TEST = "test"; /** * : {@value} . */ private static final String ATTRIBUTE_PING = "ping"; /** Http Method post test. */ /** * HTTPPOST/profilemethodGET. * <pre> * HTTP * Method: POST * Path: /GET/allGetControl?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPostGetRequestProfile() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_GET); builder.append("/").append(PROFILE_NAME); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); postInvalidUrl(builder); } /** * HTTPPOST/profile/attributemethodGET. * <pre> * HTTP * Method: POST * Path: /GET/allGetControl/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPostGetRequestProfileAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_GET); builder.append("/").append(PROFILE_NAME); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); postInvalidUrl(builder); } /** * HTTPPOST/profile/interface/attributemethodGET. * <pre> * HTTP * Method: POST * Path: /GET/allGetControl/test/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> */ @Test public void testHttpMethodPostGetRequestProfileInterfaceAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_GET); builder.append("/").append(PROFILE_NAME); builder.append("/").append(INTERFACE_TEST); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); postInvalidUrl(builder); } /** * HTTPPOST/profilemethodPOST. * <pre> * HTTP * Method: POST * Path: /POST/allGetControl?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPostPostRequestProfile() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_POST); builder.append("/").append(PROFILE_NAME); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); postInvalidUrl(builder); } /** * HTTPPOST /profile/attributemethodPOST. * <pre> * HTTP * Method: POST * Path: /POST/allGetControl/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPostPostRequestProfileAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_POST); builder.append("/").append(PROFILE_NAME); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); postInvalidUrl(builder); } /** * HTTPPOST/profile/interface/attributemethodPOST. * <pre> * HTTP * Method: POST * Path: /POST/allGetControl/test/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPostPostRequestProfileInterfaceAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_POST); builder.append("/").append(PROFILE_NAME); builder.append("/").append(INTERFACE_TEST); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); postInvalidUrl(builder); } /** * HTTPPOST/profilemethodPUT. * <pre> * HTTP * Method: POST * Path: /PUT/allGetControl?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPostPutRequestProfile() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_PUT); builder.append("/").append(PROFILE_NAME); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); postInvalidUrl(builder); } /** * HTTPPOST/profile/attributemethodPUT. * <pre> * HTTP * Method: POST * Path: /PUT/allGetControl/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPostPutRequestProfileAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_PUT); builder.append("/").append(PROFILE_NAME); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); postInvalidUrl(builder); } /** * HTTPPOST /profile/interface/attributemethodGET. * <pre> * HTTP * Method: POST * Path: /PUT/allGetControl/test/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPostPutRequestProfileInterfaceAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_PUT); builder.append("/").append(PROFILE_NAME); builder.append("/").append(INTERFACE_TEST); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); postInvalidUrl(builder); } /** * HTTPPOST /profilemethodDELEte. * <pre> * HTTP * Method: POST * Path: /DELETE/allGetControl?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPostDeleteRequestProfile() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_DELETE); builder.append("/").append(PROFILE_NAME); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); postInvalidUrl(builder); } /** * HTTPPOST/profile/attributemethodDELETE. * <pre> * HTTP * Method: POST * Path: /DELETE/allGetControl/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> */ @Test public void testHttpMethodPostDeleteRequestProfileAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_DELETE); builder.append("/").append(PROFILE_NAME); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); postInvalidUrl(builder); } /** * HTTPPOST/profile/interface/attributemethodDELETE. * <pre> * HTTP * Method: POST * Path: /DELETE/allGetControl/test/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPostDeleteRequestProfileInterfaceAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_DELETE); builder.append("/").append(PROFILE_NAME); builder.append("/").append(INTERFACE_TEST); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); postInvalidUrl(builder); } /** Http Method put test. */ /** * HTTPPUT/profilemethodGET. * <pre> * HTTP * Method: PUT * Path: /GET/allGetControl?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPutGetRequestProfile() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_GET); builder.append("/").append(PROFILE_NAME); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); putInvalidUrl(builder); } /** * HTTPPUT/profile/attributemethodGET. * <pre> * HTTP * Method: PUT * Path: /GET/allGetControl/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPutGetRequestProfileAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_GET); builder.append("/").append(PROFILE_NAME); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); putInvalidUrl(builder); } /** * HTTPPUT/profile/interface/attributemethodGET. * <pre> * HTTP * Method: PUT * Path: /GET/allGetControl/test/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> */ @Test public void testHttpMethodPutGetRequestProfileInterfaceAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_GET); builder.append("/").append(PROFILE_NAME); builder.append("/").append(INTERFACE_TEST); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); putInvalidUrl(builder); } /** * HTTPPUT/profilemethodPOST. * <pre> * HTTP * Method: PUT * Path: /POST/allGetControl?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPutPostRequestProfile() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_POST); builder.append("/").append(PROFILE_NAME); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); putInvalidUrl(builder); } /** * HTTPPUT /profile/attributemethodPOST. * <pre> * HTTP * Method: PUT * Path: /POST/allGetControl/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPutPostRequestProfileAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_POST); builder.append("/").append(PROFILE_NAME); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); putInvalidUrl(builder); } /** * HTTPPUT/profile/interface/attributemethodPOST. * <pre> * HTTP * Method: PUT * Path: /POST/allGetControl/test/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPutPostRequestProfileInterfaceAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_POST); builder.append("/").append(PROFILE_NAME); builder.append("/").append(INTERFACE_TEST); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); putInvalidUrl(builder); } /** * HTTPPUT/profilemethodPUT. * <pre> * HTTP * Method: PUT * Path: /PUT/allGetControl?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPutPutRequestProfile() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_PUT); builder.append("/").append(PROFILE_NAME); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); putInvalidUrl(builder); } /** * HTTPPUT/profile/attributemethodPUT. * <pre> * HTTP * Method: PUT * Path: /PUT/allGetControl/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPutPutRequestProfileAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_PUT); builder.append("/").append(PROFILE_NAME); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); putInvalidUrl(builder); } /** * HTTPPUT /profile/interface/attributemethodGET. * <pre> * HTTP * Method: PUT * Path: /PUT/allGetControl/test/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPutPutRequestProfileInterfaceAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_PUT); builder.append("/").append(PROFILE_NAME); builder.append("/").append(INTERFACE_TEST); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); putInvalidUrl(builder); } /** * HTTPPUT /profilemethodDELEte. * <pre> * HTTP * Method: PUT * Path: /DELETE/allGetControl?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPutDeleteRequestProfile() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_DELETE); builder.append("/").append(PROFILE_NAME); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); putInvalidUrl(builder); } /** * HTTPPUT/profile/attributemethodDELETE. * <pre> * HTTP * Method: PUT * Path: /DELETE/allGetControl/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> */ @Test public void testHttpMethodPutDeleteRequestProfileAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_DELETE); builder.append("/").append(PROFILE_NAME); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); putInvalidUrl(builder); } /** * HTTPPUT/profile/interface/attributemethodDELETE. * <pre> * HTTP * Method: PUT * Path: /DELETE/allGetControl/test/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodPutDeleteRequestProfileInterfaceAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_DELETE); builder.append("/").append(PROFILE_NAME); builder.append("/").append(INTERFACE_TEST); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); postInvalidUrl(builder); } /** Http Method delete test. */ /** * HTTPDELETE/profilemethodGET. * <pre> * HTTP * Method: DELETE * Path: /GET/allGetControl?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodDeleteGetRequestProfile() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_GET); builder.append("/").append(PROFILE_NAME); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); deleteInvalidUrl(builder); } /** * HTTPDELETE/profile/attributemethodGET. * <pre> * HTTP * Method: DELETE * Path: /GET/allGetControl/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodDeleteGetRequestProfileAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_GET); builder.append("/").append(PROFILE_NAME); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); deleteInvalidUrl(builder); } /** * HTTPDELETE/profile/interface/attributemethodGET. * <pre> * HTTP * Method: DELETE * Path: /GET/allGetControl/test/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> */ @Test public void testHttpMethodDeleteGetRequestProfileInterfaceAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_GET); builder.append("/").append(PROFILE_NAME); builder.append("/").append(INTERFACE_TEST); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); deleteInvalidUrl(builder); } /** * HTTPDELETE/profilemethodPOST. * <pre> * HTTP * Method: DELETE * Path: /POST/allGetControl?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodDeletePostRequestProfile() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_POST); builder.append("/").append(PROFILE_NAME); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); deleteInvalidUrl(builder); } /** * HTTPDELETE /profile/attributemethodPOST. * <pre> * HTTP * Method: DELETE * Path: /POST/allGetControl/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodDeletePostRequestProfileAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_POST); builder.append("/").append(PROFILE_NAME); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); deleteInvalidUrl(builder); } /** * HTTPDELETE/profile/interface/attributemethodPOST. * <pre> * HTTP * Method: DELETE * Path: /POST/allGetControl/test/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodDeletePostRequestProfileInterfaceAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_POST); builder.append("/").append(PROFILE_NAME); builder.append("/").append(INTERFACE_TEST); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); deleteInvalidUrl(builder); } /** * HTTPDELETE/profilemethodPUT. * <pre> * HTTP * Method: DELETE * Path: /PUT/allGetControl?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodDeletePutRequestProfile() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_PUT); builder.append("/").append(PROFILE_NAME); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); deleteInvalidUrl(builder); } /** * HTTPDELETE/profile/attributemethodPUT. * <pre> * HTTP * Method: DELETE * Path: /PUT/allGetControl/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodDeletePutRequestProfileAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_PUT); builder.append("/").append(PROFILE_NAME); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); deleteInvalidUrl(builder); } /** * HTTPDELETE /profile/interface/attributemethodGET. * <pre> * HTTP * Method: DELETE * Path: /PUT/allGetControl/test/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodDeletePutRequestProfileInterfaceAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_PUT); builder.append("/").append(PROFILE_NAME); builder.append("/").append(INTERFACE_TEST); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); deleteInvalidUrl(builder); } /** * HTTPDELETE /profilemethodDELEte. * <pre> * HTTP * Method: DELETE * Path: /DELETE/allGetControl?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodDeleteDeleteRequestProfile() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_DELETE); builder.append("/").append(PROFILE_NAME); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); deleteInvalidUrl(builder); } /** * HTTPDELETE/profile/attributemethodDELETE. * <pre> * HTTP * Method: DELETE * Path: /DELETE/allGetControl/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> */ @Test public void testHttpMethodDeleteDeleteRequestProfileAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_DELETE); builder.append("/").append(PROFILE_NAME); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); deleteInvalidUrl(builder); } /** * HTTPDELETE/profile/interface/attributemethodDELETE. * <pre> * HTTP * Method: DELETE * Path: /DELETE/allGetControl/test/ping?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid url * </pre> * */ @Test public void testHttpMethodDeleteDeleteRequestProfileInterfaceAttribute() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_DELETE); builder.append("/").append(PROFILE_NAME); builder.append("/").append(INTERFACE_TEST); builder.append("/").append(ATTRIBUTE_PING); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); deleteInvalidUrl(builder); } /** ProfileHttp. */ /** * methodprofileGET. * <pre> * HTTP * Method: GET * Path: /GET?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid profile * </pre> * */ @Test public void testProfileHttpMethodGetByNormal() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_GET); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); getInvalidProfile(builder); } /** * methodprofilePOST. * <pre> * HTTP * Method: GET * Path: /POST?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid profile * </pre> * */ @Test public void testProfileHttpMethodPostByNormal() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_POST); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); postInvalidProfile(builder); } /** * methodprofilePUT. * <pre> * HTTP * Method: GET * Path: /PUT?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid profile * </pre> * */ @Test public void testProfileHttpMethodPutByNormal() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_PUT); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); putInvalidProfile(builder); } /** * methodprofileDELETE. * <pre> * HTTP * Method: GET * Path: /DELETE?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid profile * </pre> * */ @Test public void testProfileHttpMethodDeleteByNormal() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_DELETE); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); deleteInvalidProfile(builder); } /** MethodProfileHttp. */ /** * methodGETprofileGET. * <pre> * HTTP * Method: GET * Path: /GET/GET?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid profile * </pre> * */ @Test public void testProfileHttpMethodGetGetByAllGetControl() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_GET); builder.append("/").append(DConnectMessage.METHOD_GET); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); getInvalidProfile(builder); } /** * methodGETprofileGET. * <pre> * HTTP * Method: GET * Path: /GET/POST?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid profile * </pre> * */ @Test public void testProfileHttpMethodGetPostByAllGetControl() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_GET); builder.append("/").append(DConnectMessage.METHOD_POST); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); getInvalidProfile(builder); } /** * methodGETprofileGET. * <pre> * HTTP * Method: GET * Path: /GET/PUT?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid profile * </pre> * */ @Test public void testProfileHttpMethodGetPutByAllGetControl() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_GET); builder.append("/").append(DConnectMessage.METHOD_PUT); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); getInvalidProfile(builder); } /** * methodGETprofileGET. * <pre> * HTTP * Method: GET * Path: /GET/DELETE?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid profile * </pre> * */ @Test public void testProfileHttpMethodGetDeleteByAllGetControl() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_GET); builder.append("/").append(DConnectMessage.METHOD_DELETE); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); getInvalidProfile(builder); } /** * methodGETprofilePOST. * <pre> * HTTP * Method: GET * Path: /POST/GET?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid profile * </pre> * */ @Test public void testProfileHttpMethodPostGetByAllGetControl() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_POST); builder.append("/").append(DConnectMessage.METHOD_GET); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); getInvalidProfile(builder); } /** * methodGETprofilePOST. * <pre> * HTTP * Method: GET * Path: /POST/PUT?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid profile * </pre> * */ @Test public void testProfileHttpMethodPostPutByAllGetControl() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_POST); builder.append("/").append(DConnectMessage.METHOD_PUT); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); getInvalidProfile(builder); } /** * methodGETprofilePOST. * <pre> * HTTP * Method: GET * Path: /POST/DELETE?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid profile * </pre> * */ @Test public void testProfileHttpMethodPostDeleteByAllGetControl() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_POST); builder.append("/").append(DConnectMessage.METHOD_DELETE); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); getInvalidProfile(builder); } /** * methodGETprofilePUT. * <pre> * HTTP * Method: GET * Path: /PUT/PUT?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid profile * </pre> * */ @Test public void testProfileHttpMethodPutByAllGetControl() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_PUT); builder.append("/").append(DConnectMessage.METHOD_PUT); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); getInvalidProfile(builder); } /** * methodGETprofilePUT. * <pre> * HTTP * Method: GET * Path: /PUT/GET?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid profile * </pre> * */ @Test public void testProfileHttpMethodPutGetByAllGetControl() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_PUT); builder.append("/").append(DConnectMessage.METHOD_GET); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); getInvalidProfile(builder); } /** * methodGETprofilePUT. * <pre> * HTTP * Method: GET * Path: /PUT/POST?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid profile * </pre> * */ @Test public void testProfileHttpMethodPutPostByAllGetControl() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_PUT); builder.append("/").append(DConnectMessage.METHOD_POST); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); getInvalidProfile(builder); } /** * methodGETprofilePUT. * <pre> * HTTP * Method: GET * Path: /PUT/DELETE?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid profile * </pre> * */ @Test public void testProfileHttpMethodPutDeleteByAllGetControl() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_PUT); builder.append("/").append(DConnectMessage.METHOD_DELETE); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); getInvalidProfile(builder); } /** * methodGETprofileDELETE. * <pre> * HTTP * Method: GET * Path: /DELETE/DELETE?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid profile * </pre> * */ @Test public void testProfileHttpMethodDeleteByAllGetControl() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_DELETE); builder.append("/").append(DConnectMessage.METHOD_DELETE); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); getInvalidProfile(builder); } /** * methodGETprofileDELETE. * <pre> * HTTP * Method: GET * Path: /DELETE/GET?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid profile * </pre> * */ @Test public void testProfileHttpMethodDeleteGetByAllGetControl() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_DELETE); builder.append("/").append(DConnectMessage.METHOD_GET); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); getInvalidProfile(builder); } /** * methodGETprofileDELETE. * <pre> * HTTP * Method: GET * Path: /DELETE/POST?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid profile * </pre> * */ @Test public void testProfileHttpMethodDeletePostByAllGetControl() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_DELETE); builder.append("/").append(DConnectMessage.METHOD_POST); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); getInvalidProfile(builder); } /** * methodGETprofileDELETE. * <pre> * HTTP * Method: GET * Path: /DELETE/PUT?serviceId&accessToken=xxxx * </pre> * <pre> * * result1 * Invalid profile * </pre> * */ @Test public void testProfileHttpMethodDeletePutByAllGetControl() { StringBuilder builder = new StringBuilder(); builder.append(DCONNECT_MANAGER_URI); builder.append("/").append(DConnectMessage.METHOD_DELETE); builder.append("/").append(DConnectMessage.METHOD_PUT); builder.append("?").append(DConnectProfileConstants.PARAM_SERVICE_ID).append("=").append(getServiceId()); builder.append("&"); builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN).append("=").append(getAccessToken()); getInvalidProfile(builder); } /** private method **/ /** * HttpMethodPostGET, * Invalid Url. * @param builder URL */ private void postInvalidUrl(StringBuilder builder) { DConnectResponseMessage response = mDConnectSDK.post(builder.toString(), null); assertThat(response, is(notNullValue())); assertThat(response.getResult(), is(DConnectMessage.RESULT_ERROR)); assertThat(response.getInt(DConnectMessage.EXTRA_ERROR_CODE), is(DConnectMessage.ErrorCode.INVALID_URL.getCode())); } /** * HttpMethodPutGET, * Invalid Url. * @param builder URL */ private void putInvalidUrl(StringBuilder builder) { DConnectResponseMessage response = mDConnectSDK.put(builder.toString(), null); assertThat(response, is(notNullValue())); assertThat(response.getResult(), is(DConnectMessage.RESULT_ERROR)); assertThat(response.getInt(DConnectMessage.EXTRA_ERROR_CODE), is(DConnectMessage.ErrorCode.INVALID_URL.getCode())); } /** * HttpMethodDeleteGET, * Invalid Url. * @param builder URL */ private void deleteInvalidUrl(StringBuilder builder) { DConnectResponseMessage response = mDConnectSDK.delete(builder.toString()); assertThat(response, is(notNullValue())); assertThat(response.getResult(), is(DConnectMessage.RESULT_ERROR)); assertThat(response.getInt(DConnectMessage.EXTRA_ERROR_CODE), is(DConnectMessage.ErrorCode.INVALID_URL.getCode())); } /** * HttpMethodGetGET, * Invalid Profile. * @param builder URL */ private void getInvalidProfile(StringBuilder builder) { DConnectResponseMessage response = mDConnectSDK.post(builder.toString(), null); assertThat(response, is(notNullValue())); assertThat(response.getResult(), is(DConnectMessage.RESULT_ERROR)); assertThat(response.getInt(DConnectMessage.EXTRA_ERROR_CODE), is(DConnectMessage.ErrorCode.INVALID_PROFILE.getCode())); } /** * HttpMethodPostGET, * Invalid Profile. */ private void postInvalidProfile(StringBuilder builder) { DConnectResponseMessage response = mDConnectSDK.post(builder.toString(), null); assertThat(response, is(notNullValue())); assertThat(response.getResult(), is(DConnectMessage.RESULT_ERROR)); assertThat(response.getInt(DConnectMessage.EXTRA_ERROR_CODE), is(DConnectMessage.ErrorCode.INVALID_PROFILE.getCode())); } /** * HttpMethodPutGET, * Invalid Profile. * @param builder URL */ private void putInvalidProfile(StringBuilder builder) { DConnectResponseMessage response = mDConnectSDK.put(builder.toString(), null); assertThat(response, is(notNullValue())); assertThat(response.getResult(), is(DConnectMessage.RESULT_ERROR)); assertThat(response.getInt(DConnectMessage.EXTRA_ERROR_CODE), is(DConnectMessage.ErrorCode.INVALID_PROFILE.getCode())); } /** * HttpMethodDeleteGET, * Invalid Profile. * @param builder URL */ private void deleteInvalidProfile(StringBuilder builder) { DConnectResponseMessage response = mDConnectSDK.delete(builder.toString()); assertThat(response, is(notNullValue())); assertThat(response.getResult(), is(DConnectMessage.RESULT_ERROR)); assertThat(response.getInt(DConnectMessage.EXTRA_ERROR_CODE), is(DConnectMessage.ErrorCode.INVALID_PROFILE.getCode())); } }
package zmaster587.advancedRocketry.cable; import java.util.HashSet; import java.util.Iterator; import java.util.Random; import java.util.Map.Entry; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.EnumFacing; import net.minecraftforge.fluids.Fluid; import net.minecraftforge.fluids.FluidStack; import net.minecraftforge.fluids.FluidTankInfo; import net.minecraftforge.fluids.capability.CapabilityFluidHandler; import net.minecraftforge.fluids.capability.FluidTankProperties; import net.minecraftforge.fluids.capability.IFluidHandler; import net.minecraftforge.fluids.capability.IFluidTankProperties; public class LiquidNetwork extends CableNetwork { private final int MAX_TRANSFER = 100; /** * Create a new network and get an ID * @return ID of this new network */ public static LiquidNetwork initNetwork() { Random random = new Random(System.currentTimeMillis()); int id = random.nextInt(); while(usedIds.contains(id)){ id = random.nextInt(); }; LiquidNetwork net = new LiquidNetwork(); usedIds.add(id); net.networkID = id; return net; } //TODO: balance tanks @Override public void tick() { int amount = MAX_TRANSFER; //Return if there is nothing to do if(sinks.isEmpty() || sources.isEmpty()) return; Iterator<Entry<TileEntity,EnumFacing>> sinkItr = sinks.iterator(); //Go through all sinks, if one is not full attempt to fill it while(sinkItr.hasNext()) { //Get tile and key Entry<TileEntity,EnumFacing> obj = (Entry<TileEntity, EnumFacing>)sinkItr.next(); IFluidHandler fluidHandleSink = (IFluidHandler)obj.getKey().getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, obj.getValue()); EnumFacing dir = obj.getValue(); Iterator<Entry<TileEntity,EnumFacing>> sourceItr = sources.iterator(); Fluid fluid = null; //If the sink already has fluid in it then lets only try to fill it with that particular fluid for(IFluidTankProperties info : fluidHandleSink.getTankProperties()) { if(info != null && info.getContents() != null) { fluid = info.getContents().getFluid(); break; } } //If no fluid can be found then find the first source with a fluid in it if(fluid == null) { out: while(sourceItr.hasNext()) { Entry<TileEntity,EnumFacing> objSource = (Entry<TileEntity, EnumFacing>)sourceItr.next(); IFluidHandler fluidHandleSource = (IFluidHandler)objSource.getKey().getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, obj.getValue()); for(IFluidTankProperties srcInfo : fluidHandleSource.getTankProperties()) { if(srcInfo != null && srcInfo.getContents() != null) { fluid = srcInfo.getContents().getFluid(); break out; } } } } //No fluids can be moved if(fluid == null) break; if(fluidHandleSink.fill(new FluidStack(fluid, 1), false) > 0) { //Distribute? and drain tanks //Get the max the tank can take this tick then iterate through all sources until it's been filled sourceItr = sources.iterator(); int maxFill = Math.min(fluidHandleSink.fill(new FluidStack(fluid, amount), false), amount); int actualFill = 0; while(sourceItr.hasNext()) { Entry<TileEntity,EnumFacing> objSource = (Entry<TileEntity, EnumFacing>)sourceItr.next(); IFluidHandler fluidHandleSource = (IFluidHandler)objSource.getKey().getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, obj.getValue()); if(fluidHandleSource.drain(maxFill, false) != null) { int buffer; FluidStack fluid2 = fluidHandleSource.drain(maxFill, true); //drain sometimes returns a null value even when canDrain returns true if(fluid2 == null) buffer = 0; else buffer=fluid2.amount; maxFill -= buffer; actualFill += buffer; } if(maxFill == 0) break; } fluidHandleSink.fill(new FluidStack(fluid, actualFill), true); } } } }
package org.deidentifier.arx.framework.check.history; import java.util.HashMap; import java.util.Iterator; import org.deidentifier.arx.ARXConfiguration; import org.deidentifier.arx.framework.check.distribution.Distribution; import org.deidentifier.arx.framework.check.distribution.IntArrayDictionary; import org.deidentifier.arx.framework.check.groupify.HashGroupifyEntry; import org.deidentifier.arx.framework.check.groupify.IHashGroupify; import org.deidentifier.arx.framework.lattice.Node; /** * The Class History. * * @author Fabian Prasser * @author Florian Kohlmayer */ public class History { public static enum StorageStrategy { NON_ANONYMOUS, ALL } public static enum PruningStrategy { ANONYMOUS, CHECKED, K_ANONYMOUS } /** The actual buffer. */ private MRUCache<Node> cache = null; /** Current config */ private final ARXConfiguration config; /** The dictionary for frequencies of the distributions */ private final IntArrayDictionary dictionarySensFreq; /** The dictionary for values of the distributions */ private final IntArrayDictionary dictionarySensValue; /** Maximal number of entries. */ private int size; /** A map from nodes to snapshots. */ private HashMap<Node, int[]> nodeToSnapshot = null; /** The current pruning strategy */ private PruningStrategy pruningStrategy; /** The current storage strategy */ private StorageStrategy storageStrategy; /** The current requirements */ private final int requirements; /** The node backing the last returned snapshot */ private Node resultNode; /** The snapshotSizeDataset for the size of entries. */ private final long snapshotSizeDataset; /** The snapshotSizeDataset for the minimum required reduction of a snapshot */ private final double snapshotSizeSnapshot; /** * Creates a new history. * * @param rowCount * the row count * @param size * the max size * @param snapshotSizeDataset * the snapshotSizeDataset */ public History(final int rowCount, final int size, final double snapshotSizeDataset, final double snapshotSizeSnapshot, final ARXConfiguration config, final IntArrayDictionary dictionarySensValue, final IntArrayDictionary dictionarySensFreq) { this.snapshotSizeDataset = (long) (rowCount * snapshotSizeDataset); this.snapshotSizeSnapshot = snapshotSizeSnapshot; this.cache = new MRUCache<Node>(size); this.nodeToSnapshot = new HashMap<Node, int[]>(size); this.size = size; this.dictionarySensFreq = dictionarySensFreq; this.dictionarySensValue = dictionarySensValue; this.config = config; this.requirements = config.getRequirements(); this.pruningStrategy = PruningStrategy.ANONYMOUS; this.storageStrategy = StorageStrategy.NON_ANONYMOUS; } /** * Retrieves a snapshot. * * @param node * the node * @return the int[] */ public int[] get(final Node node) { int[] rData = null; Node rNode = null; // Iterate over nodes with snapshots MRUCacheEntry<Node> entry = cache.getFirst(); while (entry != null) { final Node cNode = entry.data; if (cNode.getLevel() < node.getLevel()) { final int[] cSnapshot = nodeToSnapshot.get(cNode); if ((rNode == null) || (cSnapshot.length < rData.length)) { boolean synergetic = true; for (int i = 0; i < cNode.getTransformation().length; i++) { if (node.getTransformation()[i] < cNode.getTransformation()[i]) { synergetic = false; break; } } if (synergetic) { rNode = cNode; rData = cSnapshot; } } } entry = entry.next; } if (rNode != null) { cache.touch(rNode); } resultNode = rNode; return rData; } /** * Method needed for benchmarking * * @return */ public IntArrayDictionary getDictionarySensFreq() { return dictionarySensFreq; } /** * Method needed for benchmarking * * @return */ public IntArrayDictionary getDictionarySensValue() { return dictionarySensValue; } /** * Returns the node backing the last returned snapshot * * @return */ public Node getNode() { return resultNode; } /** * Returns the current pruning strategy * * @return */ public PruningStrategy getPruningStrategy() { return pruningStrategy; } /** * Returns the current storage strategy * * @return */ public StorageStrategy getStorageStrategy() { return storageStrategy; } /** * Clears the history. */ public void reset() { this.cache.clear(); this.nodeToSnapshot.clear(); this.dictionarySensFreq.clear(); this.dictionarySensValue.clear(); this.resultNode = null; } /** * Set the pruning strategy * * @param strategy */ public void setPruningStrategy(final PruningStrategy strategy) { pruningStrategy = strategy; } /** * Set the storage strategy * * @param strategy */ public void setStorageStrategy(final StorageStrategy strategy) { storageStrategy = strategy; } /** * Sets the size of this history * @param size */ public void setSize(int size) { this.size = size; } public int size() { return cache.size(); } /** * Stores a snapshot. * * @param node * the node * @param g * the g */ public boolean store(final Node node, final IHashGroupify g, final int[] usedSnapshot) { boolean store = storageStrategy == StorageStrategy.NON_ANONYMOUS ? !node.isAnonymous() : true; if ((!store || (g.size() > snapshotSizeDataset) || canPrune(node))) { return false; } // Store only if significantly smaller if (usedSnapshot != null) { final double percentSize = (g.size() / ((double) usedSnapshot.length / config.getSnapshotLength())); if (percentSize > snapshotSizeSnapshot) { return false; } } // Create the snapshot final int[] data = createSnapshot(g); // if cache size is too large purge if (cache.size() >= size) { purgeCache(); } // assign snapshot and keep reference for cache nodeToSnapshot.put(node, data); cache.append(node); return true; } /** * Can a node be pruned. * * @param node * the node * @return true, if successful */ private final boolean canPrune(final Node node) { boolean prune = true; switch (pruningStrategy) { case ANONYMOUS: for (final Node upNode : node.getSuccessors()) { if (!upNode.isAnonymous()) { prune = false; break; } } break; case CHECKED: for (final Node upNode : node.getSuccessors()) { if (!upNode.isChecked()) { prune = false; break; } } break; case K_ANONYMOUS: for (final Node upNode : node.getSuccessors()) { if (!upNode.isKAnonymous()) { prune = false; break; } } break; } return prune; } /** * Creates a generic snapshot for all criteria * * @param g * the g * @return the int[] */ private final int[] createSnapshot(final IHashGroupify g) { // Copy Groupify final int[] data = new int[g.size() * config.getSnapshotLength()]; int index = 0; HashGroupifyEntry m = g.getFirstEntry(); while (m != null) { // Store element data[index] = m.representant; data[index + 1] = m.count; // Add data for different requirements switch (requirements) { case ARXConfiguration.REQUIREMENT_COUNTER: // do nothing break; case ARXConfiguration.REQUIREMENT_COUNTER | ARXConfiguration.REQUIREMENT_SECONDARY_COUNTER: data[index + 2] = m.pcount; break; case ARXConfiguration.REQUIREMENT_COUNTER | ARXConfiguration.REQUIREMENT_SECONDARY_COUNTER | ARXConfiguration.REQUIREMENT_DISTRIBUTION: data[index + 2] = m.pcount; for (int i=0; i<m.distributions.length; i++) { Distribution distribution = m.distributions[i]; distribution.pack(); data[index + 3 + i * 2] = dictionarySensValue.probe(distribution.getPackedElements()); data[index + 4 + i * 2] = dictionarySensFreq.probe(distribution.getPackedFrequency()); } break; // TODO: If we only need a distribution, we should get rid of the primary counter case ARXConfiguration.REQUIREMENT_COUNTER | ARXConfiguration.REQUIREMENT_DISTRIBUTION: case ARXConfiguration.REQUIREMENT_DISTRIBUTION: for (int i=0; i<m.distributions.length; i++) { Distribution distribution = m.distributions[i]; distribution.pack(); data[index + 2 + i * 2] = dictionarySensValue.probe(distribution.getPackedElements()); data[index + 3 + i * 2] = dictionarySensFreq.probe(distribution.getPackedFrequency()); } break; default: throw new RuntimeException("Invalid requirements: " + requirements); } index += config.getSnapshotLength(); // Next element m = m.nextOrdered; } return data; } /** * Remove least recently used from cache and index. */ private final void purgeCache() { int purged = 0; // Purge prunable nodes final Iterator<Node> it = cache.iterator(); while (it.hasNext()) { final Node node = it.next(); if (canPrune(node)) { purged++; it.remove(); removeHistoryEntry(node); } } // Purge LRU if (purged == 0) { final Node node = cache.removeHead(); removeHistoryEntry(node); } } /** * Removes a snapshot * * @param node */ private final void removeHistoryEntry(final Node node) { final int[] snapshot = nodeToSnapshot.remove(node); switch (requirements) { case ARXConfiguration.REQUIREMENT_COUNTER | ARXConfiguration.REQUIREMENT_SECONDARY_COUNTER | ARXConfiguration.REQUIREMENT_DISTRIBUTION: for (int i = 0; i < snapshot.length; i += config.getSnapshotLength()) { for (int j = i + 3; j < i + config.getSnapshotLength() - 1; j += 2) { dictionarySensValue.decrementRefCount(snapshot[j]); dictionarySensFreq.decrementRefCount(snapshot[j+1]); } } break; // TODO: If we only need a distribution, we should get rid of the primary counter case ARXConfiguration.REQUIREMENT_COUNTER | ARXConfiguration.REQUIREMENT_DISTRIBUTION: case ARXConfiguration.REQUIREMENT_DISTRIBUTION: for (int i = 0; i < snapshot.length; i += config.getSnapshotLength()) { for (int j = i + 2; j < i + config.getSnapshotLength() - 1; j += 2) { dictionarySensValue.decrementRefCount(snapshot[j]); dictionarySensFreq.decrementRefCount(snapshot[j+1]); } } } } }
package org.innovateuk.ifs.project.status.populator; import org.innovateuk.ifs.async.generation.AsyncAdaptor; import org.innovateuk.ifs.commons.rest.RestResult; import org.innovateuk.ifs.competition.resource.CompetitionPostAwardServiceResource; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.competition.service.CompetitionRestService; import org.innovateuk.ifs.competition.service.CompetitionSetupPostAwardServiceRestService; import org.innovateuk.ifs.organisation.resource.OrganisationResource; import org.innovateuk.ifs.project.ProjectService; import org.innovateuk.ifs.project.constant.ProjectActivityStates; import org.innovateuk.ifs.project.internal.ProjectSetupStage; import org.innovateuk.ifs.project.monitoring.resource.MonitoringOfficerResource; import org.innovateuk.ifs.project.monitoring.service.MonitoringOfficerRestService; import org.innovateuk.ifs.project.resource.ProjectPartnerStatusResource; import org.innovateuk.ifs.project.resource.ProjectResource; import org.innovateuk.ifs.project.service.ProjectRestService; import org.innovateuk.ifs.project.status.resource.ProjectTeamStatusResource; import org.innovateuk.ifs.project.status.security.SetupSectionAccessibilityHelper; import org.innovateuk.ifs.project.status.viewmodel.SetupStatusStageViewModel; import org.innovateuk.ifs.project.status.viewmodel.SetupStatusViewModel; import org.innovateuk.ifs.sections.SectionAccess; import org.innovateuk.ifs.sections.SectionStatus; import org.innovateuk.ifs.status.StatusService; import org.innovateuk.ifs.user.resource.UserResource; import org.innovateuk.ifs.util.NavigationUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; import java.util.concurrent.CompletableFuture; import static java.lang.String.format; import static java.util.stream.Collectors.toList; import static org.innovateuk.ifs.project.constant.ProjectActivityStates.COMPLETE; import static org.innovateuk.ifs.sections.SectionStatus.TICK; /** * Populator for creating the {@link SetupStatusViewModel} */ @Service public class SetupStatusViewModelPopulator extends AsyncAdaptor { @Autowired private ProjectService projectService; @Autowired private ProjectRestService projectRestService; @Autowired private StatusService statusService; @Autowired private MonitoringOfficerRestService monitoringOfficerService; @Autowired private CompetitionRestService competitionRestService; @Autowired private SetupSectionStatus sectionStatus; @Autowired private CompetitionSetupPostAwardServiceRestService competitionSetupPostAwardServiceRestService; @Autowired private NavigationUtils navigationUtils; public SetupStatusViewModel populateViewModel(long projectId, UserResource loggedInUser) { ProjectResource project = projectService.getById(projectId); boolean monitoringOfficer = monitoringOfficerService.isMonitoringOfficerOnProject(projectId, loggedInUser.getId()).getSuccess(); CompetitionResource competition = competitionRestService.getCompetitionById(project.getCompetition()).getSuccess(); RestResult<OrganisationResource> organisationResult = projectRestService.getOrganisationByProjectAndUser(project.getId(), loggedInUser.getId()); ProjectTeamStatusResource teamStatus = statusService.getProjectTeamStatus(project.getId(), Optional.of(loggedInUser.getId())); CompletableFuture<ProjectTeamStatusResource> teamStatusRequest = async(() -> statusService.getProjectTeamStatus(project.getId(), Optional.empty())); CompletableFuture<OrganisationResource> organisationRequest = async(() -> monitoringOfficer ? projectService.getLeadOrganisation(project.getId()) : projectRestService.getOrganisationByProjectAndUser(project.getId(), loggedInUser.getId()).getSuccess()); List<SetupStatusStageViewModel> stages = competition.getProjectSetupStages().stream() .filter(stage -> (ProjectSetupStage.BANK_DETAILS != stage) || showBankDetails(organisationResult, teamStatus)) .map(stage -> toStageViewModel(stage, project, competition, loggedInUser, monitoringOfficer, teamStatusRequest, organisationRequest)) .collect(toList()); RestResult<CompetitionPostAwardServiceResource> competitionPostAwardServiceResource = competitionSetupPostAwardServiceRestService.getPostAwardService(project.getCompetition()); boolean isProjectManager = projectService.isProjectManager(loggedInUser.getId(), projectId); boolean isProjectFinanceContact = projectService.isProjectFinanceContact(loggedInUser.getId(), projectId); return new SetupStatusViewModel( project, monitoringOfficer, stages, competition.getFundingType(), showApplicationSummaryLink(project, loggedInUser, monitoringOfficer), isProjectManager, isProjectFinanceContact, competitionPostAwardServiceResource.getSuccess().getPostAwardService(), navigationUtils.getLiveProjectsLandingPageUrl()); } private boolean showBankDetails(RestResult<OrganisationResource> organisationResult, ProjectTeamStatusResource teamStatus) { if (organisationResult.isFailure()) { return true; } OrganisationResource organisation = organisationResult.getSuccess(); if (organisation.isInternational()) { return false; } Optional<ProjectPartnerStatusResource> statusForOrg = teamStatus.getPartnerStatusForOrganisation(organisation.getId()); if (statusForOrg.isPresent() && ProjectActivityStates.NOT_REQUIRED == statusForOrg.get().getBankDetailsStatus()) { return false; } return true; } private boolean showApplicationSummaryLink(ProjectResource project, UserResource loggedInUser, boolean isMonitoringOfficer){ if (isMonitoringOfficer){ return true; } else { long organisationId = projectService.getOrganisationIdFromUser(project.getId(), loggedInUser); return projectRestService.existsOnApplication(project.getId(), organisationId).getSuccess(); } } private SetupStatusStageViewModel toStageViewModel(ProjectSetupStage stage, ProjectResource project, CompetitionResource competition, UserResource user, boolean monitoringOfficer, CompletableFuture<ProjectTeamStatusResource> teamStatusRequest, CompletableFuture<OrganisationResource> organisationRequest) { SetupSectionAccessibilityHelper statusAccessor = new SetupSectionAccessibilityHelper(resolve(teamStatusRequest)); boolean projectComplete = project.getProjectState().isLive(); boolean isLeadPartner = isLeadPartner(resolve(teamStatusRequest), resolve(organisationRequest)); boolean partnerProjectLocationRequired = competition.isLocationPerPartner(); ProjectPartnerStatusResource ownOrganisation = resolve(teamStatusRequest).getPartnerStatusForOrganisation(resolve(organisationRequest).getId()).get(); switch (stage) { case PROJECT_DETAILS: boolean isProjectDetailsProcessCompleted = isLeadPartner ? checkLeadPartnerProjectDetailsProcessCompleted(resolve(teamStatusRequest)) : partnerProjectDetailsComplete(statusAccessor, resolve(organisationRequest), partnerProjectLocationRequired); boolean awaitingProjectDetailsActionFromOtherPartners = isLeadPartner && awaitingProjectDetailsActionFromOtherPartners(resolve(teamStatusRequest), partnerProjectLocationRequired); return new SetupStatusStageViewModel(stage, stage.getShortName(), projectComplete ? "Confirm the proposed start date and location of the project." : competition.isProcurement() ? "The start date and location of this project." : "The proposed start date and location of the project.", projectComplete ? format("/project/%d/details/readonly", project.getId()) : format("/project/%d/details", project.getId()), sectionStatus.projectDetailsSectionStatus( isProjectDetailsProcessCompleted, awaitingProjectDetailsActionFromOtherPartners, isLeadPartner), statusAccessor.canAccessProjectDetailsSection(resolve(organisationRequest)) ); case PROJECT_TEAM: return new SetupStatusStageViewModel(stage, stage.getShortName(), projectComplete ? "Add people to your project." : "The people on your project.", projectComplete ? format("/project/%d/team", project.getId()) : format("/project/%d/team", project.getId()), sectionStatus.projectTeamSectionStatus(ownOrganisation.getProjectTeamStatus()), statusAccessor.canAccessProjectTeamSection(resolve(organisationRequest)) ); case DOCUMENTS: boolean isProjectManager = projectService.getProjectManager(project.getId()).map(pu -> pu.isUser(user.getId())).orElse(false); return new SetupStatusStageViewModel(stage, stage.getShortName(), isProjectManager ? "You must upload supporting documents to be reviewed." : "The Project Manager must upload supporting documents to be reviewed.", format("/project/%d/document/all", project.getId()), sectionStatus.documentsSectionStatus( isProjectManager, project, competition ), statusAccessor.canAccessDocumentsSection(resolve(organisationRequest)) ); case MONITORING_OFFICER: Optional<MonitoringOfficerResource> maybeMonitoringOfficer = monitoringOfficerService.findMonitoringOfficerForProject(project.getId()).getOptionalSuccessObject(); boolean isProjectDetailsSubmitted = COMPLETE.equals(resolve(teamStatusRequest).getLeadPartnerStatus().getProjectDetailsStatus()); boolean requiredProjectDetailsForMonitoringOfficerComplete = requiredProjectDetailsForMonitoringOfficerComplete(partnerProjectLocationRequired, isProjectDetailsSubmitted, resolve(teamStatusRequest)); return new SetupStatusStageViewModel(stage, "Monitoring Officer", maybeMonitoringOfficer.isPresent() ? format(getMonitoringOfficerText(competition.isKtp()) + " %s.", maybeMonitoringOfficer.get().getFullName()) : "We will assign the project a Monitoring Officer.", projectComplete ? format("/project/%d/monitoring-officer/readonly", project.getId()) : format("/project/%d/monitoring-officer", project.getId()), sectionStatus.monitoringOfficerSectionStatus(maybeMonitoringOfficer.isPresent(), requiredProjectDetailsForMonitoringOfficerComplete), statusAccessor.canAccessMonitoringOfficerSection(resolve(organisationRequest), partnerProjectLocationRequired), maybeMonitoringOfficer.isPresent() ? null : "awaiting-assignment" ); case BANK_DETAILS: return new SetupStatusStageViewModel(stage, stage.getShortName(), "We need your organisation's bank details.", projectComplete ? format("/project/%d/bank-details/readonly", project.getId()) : format("/project/%d/bank-details", project.getId()), sectionStatus.bankDetailsSectionStatus(ownOrganisation.getBankDetailsStatus()), monitoringOfficer ? SectionAccess.NOT_ACCESSIBLE : statusAccessor.canAccessBankDetailsSection(resolve(organisationRequest)) ); case FINANCE_CHECKS: SectionAccess financeChecksAccess = statusAccessor.canAccessFinanceChecksSection(resolve(organisationRequest)); SectionStatus financeChecksStatus = sectionStatus.financeChecksSectionStatus( ownOrganisation.getFinanceChecksStatus(), financeChecksAccess ); boolean pendingQueries = SectionStatus.FLAG.equals(financeChecksStatus); return new SetupStatusStageViewModel(stage, stage.getShortName(), "We will review your financial information.", format("/project/%d/finance-checks", project.getId()), financeChecksStatus, monitoringOfficer ? SectionAccess.NOT_ACCESSIBLE : financeChecksAccess, pendingQueries ? "pending-query" : null ); case SPEND_PROFILE: return new SetupStatusStageViewModel(stage, stage.getShortName(), "Once we have approved your project finances you can change your project spend profile.", format("/project/%d/partner-organisation/%d/spend-profile", project.getId(), resolve(organisationRequest).getId()), sectionStatus.spendProfileSectionStatus(ownOrganisation.getSpendProfileStatus()), statusAccessor.canAccessSpendProfileSection(resolve(organisationRequest)) ); case GRANT_OFFER_LETTER: String title = competition.isProcurement() ? "Contract" : "Grant offer letter"; return new SetupStatusStageViewModel(stage, title, getGrantOfferLetterSubtitle(title, competition.isKtp()), format("/project/%d/offer", project.getId()), sectionStatus.grantOfferLetterSectionStatus( ownOrganisation.getGrantOfferLetterStatus(), isLeadPartner ), statusAccessor.canAccessGrantOfferLetterSection(resolve(organisationRequest)) ); case PROJECT_SETUP_COMPLETE: SectionStatus projectSetupCompleteStatus = sectionStatus.projectSetupCompleteStatus(ownOrganisation.getProjectSetupCompleteStatus()); return new SetupStatusStageViewModel(stage, stage.getShortName(), "Once all tasks are complete Innovate UK will review your application.", String.format("/project/%d/setup", project.getId()), projectSetupCompleteStatus, statusAccessor.canAccessProjectSetupCompleteSection(), projectSetupCompleteStatus.equals(TICK) ? null : "awaiting-review" ); } throw new IllegalArgumentException("Unknown enum type " + stage.name()); } private String getGrantOfferLetterSubtitle(String title, boolean isKtp) { return isKtp ? "The project manager can review, sign and submit the grant offer letter to us once all tasks are complete." : "Once all tasks are complete the Project Manager can review, sign and submit the " + title.toLowerCase() + " to us."; } private String getMonitoringOfficerText(boolean isKtp) { return isKtp ? "Your monitoring officer for this project is knowledge transfer advisor (KTA)" : "Your Monitoring Officer for this project is"; } private boolean isLeadPartner(ProjectTeamStatusResource teamStatus, OrganisationResource organisation) { return teamStatus.getLeadPartnerStatus().getOrganisationId().equals(organisation.getId()); } private boolean requiredProjectDetailsForMonitoringOfficerComplete(boolean partnerProjectLocationRequired, boolean isProjectDetailsSubmitted, ProjectTeamStatusResource teamStatus) { if (partnerProjectLocationRequired) { return isProjectDetailsSubmitted && allPartnersProjectLocationStatusComplete(teamStatus); } else { return isProjectDetailsSubmitted; } } private boolean partnerProjectDetailsComplete(SetupSectionAccessibilityHelper statusAccessor, OrganisationResource organisation, boolean partnerProjectLocationRequired) { return !partnerProjectLocationRequired || statusAccessor.isPartnerProjectLocationSubmitted(organisation); } public boolean checkLeadPartnerProjectDetailsProcessCompleted(ProjectTeamStatusResource teamStatus) { ProjectPartnerStatusResource leadPartnerStatus = teamStatus.getLeadPartnerStatus(); return leadPartnerStatus.getProjectDetailsStatus().equals(COMPLETE); } private boolean awaitingProjectDetailsActionFromOtherPartners(ProjectTeamStatusResource teamStatus, boolean partnerProjectLocationRequired) { ProjectPartnerStatusResource leadPartnerStatus = teamStatus.getLeadPartnerStatus(); return partnerProjectLocationRequired && isAwaitingWhenProjectLocationRequired(teamStatus, leadPartnerStatus); } private boolean isAwaitingWhenProjectLocationRequired(ProjectTeamStatusResource teamStatus, ProjectPartnerStatusResource leadPartnerStatus) { return COMPLETE.equals(leadPartnerStatus.getProjectDetailsStatus()) && COMPLETE.equals(leadPartnerStatus.getPartnerProjectLocationStatus()) && !allOtherPartnersProjectLocationStatusComplete(teamStatus); } private boolean allOtherPartnersProjectLocationStatusComplete(ProjectTeamStatusResource teamStatus) { return teamStatus.checkForOtherPartners(status -> COMPLETE.equals(status.getPartnerProjectLocationStatus())); } private boolean allPartnersProjectLocationStatusComplete(ProjectTeamStatusResource teamStatus) { return teamStatus.checkForAllPartners(status -> COMPLETE.equals(status.getPartnerProjectLocationStatus())); } }
package org.hyperic.sigar.win32; import java.io.PrintStream; import java.util.Arrays; import java.util.ArrayList; import java.util.List; public class ServiceConfig { // Start type /** * A device driver started by the system loader. This value is valid only for driver services. */ public static final int START_BOOT = 0x00000000; /** * A device driver started by the IoInitSystem function. This value is valid only for driver services. */ public static final int START_SYSTEM = 0x00000001; /** * A service started automatically by the service control manager during system startup. */ public static final int START_AUTO = 0x00000002; /** * A service started by the service control manager when a process calls the StartService function. */ public static final int START_MANUAL = 0x00000003; /** * A service that cannot be started. * Attempts to start the service result in the error code ERROR_SERVICE_DISABLED. */ public static final int START_DISABLED = 0x00000004; /** * Driver service. */ public static final int TYPE_KERNEL_DRIVER = 0x00000001; /** * File system driver service. */ public static final int TYPE_FILE_SYSTEM_DRIVER = 0x00000002; public static final int TYPE_ADAPTER = 0x00000004; public static final int TYPE_RECOGNIZER_DRIVER = 0x00000008; /** * Service that runs in its own process. */ public static final int TYPE_WIN32_OWN_PROCESS = 0x00000010; /** * Service that shares a process with other services. */ public static final int TYPE_WIN32_SHARE_PROCESS = 0x00000020; /** * The service can interact with the desktop. */ public static final int TYPE_INTERACTIVE_PROCESS = 0x00000100; // Error control type /** * The startup (boot) program logs the error but continues the startup operation. */ public static final int ERROR_IGNORE = 0x00000000; /** * The startup program logs the error and displays a message box pop-up but continues the startup operation. */ public static final int ERROR_NORMAL = 0x00000001; /** * The startup program logs the error. * If the last-known good configuration is being started, the startup operation continues. * Otherwise, the system is restarted with the last-known-good configuration. */ public static final int ERROR_SEVERE = 0x00000002; /** * The startup program logs the error, if possible. * If the last-known good configuration is being started, the startup operation fails. * Otherwise, the system is restarted with the last-known good configuration. */ public static final int ERROR_CRITICAL = 0x00000003; private static final String[] START_TYPES = { "Boot", "System", "Auto", "Manual", "Disabled" }; private static final String[] ERROR_TYPES = { "Ignore", "Normal", "Severe", "Critical" }; int type; int startType; int errorControl; String path; String exe; String loadOrderGroup; int tagId; String[] dependencies; String startName; String displayName; String description; String password; String name; ServiceConfig() {} public ServiceConfig(String name) { this.name = name; this.type = TYPE_WIN32_OWN_PROCESS; this.startType = START_AUTO; this.errorControl = ERROR_NORMAL; //msdn docs: //"Specify an empty string if the account has no password //or if the service runs in the LocalService, NetworkService, //or LocalSystem account" this.password = ""; } /** * @return Returns the path. */ public String getPath() { return path; } /** * @param path The path to set. */ public void setPath(String path) { this.path = path; } public String getExe() { return this.exe; } /** * @return Returns the dependencies. */ public String[] getDependencies() { if (this.dependencies == null) { return new String[0]; } return dependencies; } /** * @param dependencies The dependencies to set. */ public void setDependencies(String[] dependencies) { this.dependencies = dependencies; } /** * @return Returns the displayName. */ public String getDisplayName() { return displayName; } /** * @param displayName The displayName to set. */ public void setDisplayName(String displayName) { this.displayName = displayName; } /** * @return Returns the errorControl, one of ERROR_* constants. */ public int getErrorControl() { return errorControl; } /** * @param errorControl The errorControl to set, one of ERROR_* constants. */ public void setErrorControl(int errorControl) { this.errorControl = errorControl; } public String getErrorControlString() { return ERROR_TYPES[getErrorControl()]; } /** * @return Returns the loadOrderGroup. */ public String getLoadOrderGroup() { return loadOrderGroup; } /** * @param loadOrderGroup The loadOrderGroup to set. */ public void setLoadOrderGroup(String loadOrderGroup) { this.loadOrderGroup = loadOrderGroup; } /** * @return Returns the startName. */ public String getStartName() { return startName; } /** * @param startName The startName to set. */ public void setStartName(String startName) { this.startName = startName; } /** * @return Returns the startType, one of START_* constants. */ public int getStartType() { return startType; } /** * @param startType The startType to set, one of START_* constants. */ public void setStartType(int startType) { this.startType = startType; } public String getStartTypeString() { return START_TYPES[getStartType()]; } /** * @return Returns the tagId. */ public int getTagId() { return tagId; } /** * @param tagId The tagId to set. */ public void setTagId(int tagId) { this.tagId = tagId; } /** * @return Returns the type, one of TYPE_* constants. */ public int getType() { return type; } public List getTypeList() { ArrayList types = new ArrayList(); if ((this.type & TYPE_KERNEL_DRIVER) != 0) { types.add("Kernel Driver"); } if ((this.type & TYPE_FILE_SYSTEM_DRIVER) != 0) { types.add("File System Driver"); } if ((this.type & TYPE_ADAPTER) != 0) { types.add("Adapter"); } if ((this.type & TYPE_RECOGNIZER_DRIVER) != 0) { types.add("Recognizer Driver"); } if ((this.type & TYPE_WIN32_OWN_PROCESS) != 0) { types.add("Own Process"); } if ((this.type & TYPE_WIN32_SHARE_PROCESS) != 0) { types.add("Share Process"); } if ((this.type & TYPE_INTERACTIVE_PROCESS) != 0) { types.add("Interactive Process"); } return types; } /** * @param type The type to set, one of TYPE_* constants. */ public void setType(int type) { this.type = type; } /** * @return Returns the description. */ public String getDescription() { return description; } /** * @param description The description to set. */ public void setDescription(String description) { this.description = description; } /** * @return Returns the password. */ public String getPassword() { return password; } /** * @param password The password to set. */ public void setPassword(String password) { this.password = password; } /** * @return Returns the name. */ public String getName() { return name; } /** * @param name The name to set. */ public void setName(String name) { this.name = name; } public void list(PrintStream out) throws Win32Exception { out.println("name..........[" + getName() + "]"); out.println("display.......[" + getDisplayName() + "]"); out.println("description...[" + getDescription() + "]"); out.println("start type....[" + getStartTypeString() + "]"); out.println("start name....[" + getStartName() + "]"); out.println("type.........." + getTypeList()); out.println("path..........[" + getPath() + "]"); out.println("exe...........[" + getExe() + "]"); out.println("deps.........." + Arrays.asList(getDependencies())); out.println("error ctl.....[" + getErrorControlString() + "]"); } }
/** * <p> * This package contains API for Procedure implementations. * </p> * <p> * Every procedure should implement {@link Procedure} interface. For convenience the package comes with * {@link AbstractProcedure} class which implements basic initialization logic and that is preferable to use in most * cases. * </p> */ package com.continuuity.api.procedure;
package org.opencb.opencga.storage.hadoop.variant.archive; import com.fasterxml.jackson.databind.MapperFeature; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.util.Bytes; import org.opencb.biodata.models.variant.VariantSource; import org.opencb.biodata.models.variant.protobuf.VcfMeta; import org.opencb.datastore.core.ObjectMap; import org.opencb.datastore.core.QueryResult; import org.opencb.opencga.storage.hadoop.auth.HBaseCredentials; import org.opencb.opencga.storage.hadoop.utils.HBaseManager; import org.opencb.opencga.storage.hadoop.variant.GenomeHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; public class ArchiveFileMetadataManager implements AutoCloseable { private final String tableName; private final Configuration configuration; private final ObjectMap options; private final GenomeHelper genomeHelper; private final Connection connection; private final ObjectMapper objectMapper; private final HBaseManager hBaseManager; private final Logger logger = LoggerFactory.getLogger(ArchiveDriver.class); public ArchiveFileMetadataManager(HBaseCredentials credentials, Configuration configuration, ObjectMap options) throws IOException { this(credentials.getTable(), configuration, options); } public ArchiveFileMetadataManager(String tableName, Configuration configuration, ObjectMap options) throws IOException { this(ConnectionFactory.createConnection(configuration), tableName, configuration, options); } public ArchiveFileMetadataManager(Connection con, String tableName, Configuration configuration, ObjectMap options) throws IOException { this.tableName = tableName; this.configuration = configuration; this.options = options == null ? new ObjectMap() : options; genomeHelper = new GenomeHelper(configuration); connection = con; objectMapper = new ObjectMapper(); objectMapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true); hBaseManager = new HBaseManager(configuration); } public QueryResult<VcfMeta> getAllVcfMetas(ObjectMap options) throws IOException { return getVcfMeta(Collections.emptyList(), options); } public QueryResult<VcfMeta> getVcfMeta(int fileId, ObjectMap options) throws IOException { return getVcfMeta(Collections.singletonList(fileId), options); } public QueryResult<VcfMeta> getVcfMeta(List<Integer> fileIds, ObjectMap options) throws IOException { long start = System.currentTimeMillis(); Get get = new Get(genomeHelper.getMetaRowKey()); if (fileIds == null || fileIds.isEmpty()) { get.addFamily(genomeHelper.getColumnFamily()); } else { for (Integer fileId : fileIds) { byte[] columnName = Bytes.toBytes(ArchiveHelper.getColumnName(fileId)); get.addColumn(genomeHelper.getColumnFamily(), columnName); } } if (!hBaseManager.act(connection, tableName, (table, admin) -> admin.tableExists(table.getName()))) { return new QueryResult<>("getVcfMeta", (int) (System.currentTimeMillis() - start), 0, 0, "", "", Collections.emptyList()); } HBaseManager.HBaseTableFunction<Result> resultHBaseTableFunction = table -> table.get(get); Result result = hBaseManager.act(connection, tableName, resultHBaseTableFunction); logger.debug("Get VcfMeta from : {}", fileIds); if (result.isEmpty()) { return new QueryResult<>("getVcfMeta", (int) (System.currentTimeMillis() - start), 0, 0, "", "", Collections.emptyList()); } else { List<VcfMeta> metas = new ArrayList<>(result.size()); for (Map.Entry<byte[], byte[]> entry : result.getFamilyMap(genomeHelper.getColumnFamily()).entrySet()) { if (Arrays.equals(entry.getKey(), genomeHelper.getMetaRowKey())) { continue; } VariantSource variantSource = objectMapper.readValue(entry.getValue(), VariantSource.class); logger.debug("Got VcfMeta from : {}, [{}]", variantSource.getFileName(), variantSource.getFileId()); VcfMeta vcfMeta = new VcfMeta(variantSource); metas.add(vcfMeta); } return new QueryResult<>("getVcfMeta", (int) (System.currentTimeMillis() - start), 1, 1, "", "", metas); } } public void updateVcfMetaData(VcfMeta meta) throws IOException { Objects.requireNonNull(meta); updateVcfMetaData(meta.getVariantSource()); } public void updateVcfMetaData(VariantSource variantSource) throws IOException { if (ArchiveDriver.createArchiveTableIfNeeded(genomeHelper, tableName, connection)) { logger.info("Create table '{}' in hbase!", tableName); } Put put = new Put(genomeHelper.getMetaRowKey()); put.addColumn(genomeHelper.getColumnFamily(), Bytes.toBytes(variantSource.getFileId()), variantSource.getImpl().toString().getBytes()); hBaseManager.act(connection, tableName, table -> { table.put(put); }); } public void updateLoadedFilesSummary(List<Integer> newLoadedFiles) throws IOException { if (ArchiveDriver.createArchiveTableIfNeeded(genomeHelper, tableName, connection)) { logger.info("Create table '{}' in hbase!", tableName); } StringBuilder sb = new StringBuilder(); for (Integer newLoadedFile : newLoadedFiles) { sb.append(",").append(newLoadedFile); } Append append = new Append(genomeHelper.getMetaRowKey()); append.add(genomeHelper.getColumnFamily(), genomeHelper.getMetaRowKey(), Bytes.toBytes(sb.toString())); hBaseManager.act(connection, tableName, table -> { table.append(append); }); } @Override public void close() throws IOException { connection.close(); } public Set<Integer> getLoadedFiles() throws IOException { if (!hBaseManager.tableExists(connection, tableName)) { return new HashSet<>(); } else { return hBaseManager.act(connection, tableName, table -> { Get get = new Get(genomeHelper.getMetaRowKey()); get.addColumn(genomeHelper.getColumnFamily(), genomeHelper.getMetaRowKey()); byte[] value = table.get(get).getValue(genomeHelper.getColumnFamily(), genomeHelper.getMetaRowKey()); Set<Integer> set; if (value != null) { set = new LinkedHashSet<Integer>(); for (String s : Bytes.toString(value).split(",")) { if (!s.isEmpty()) { set.add(Integer.parseInt(s)); } } } else { set = new LinkedHashSet<Integer>(); } return set; }); } } }
package com.rho; import net.rim.device.api.browser.field.RenderingOptions; import net.rim.device.api.browser.field2.*; import net.rim.device.api.system.Application; import javax.microedition.io.HttpConnection; import javax.microedition.io.InputConnection; import com.rho.RhoLogger; import com.rho.RhodesApp; import com.rho.net.URI; import rhomobile.Utilities; import rhomobile.RhodesApplication.PrimaryResourceFetchThread; import rhomobile.RhodesApplication; //http://supportforums.blackberry.com/t5/Web-Development/JavaScript-not-working-on-Black-Berry-Simulator-8330/m-p/412687#M3397 public class BrowserAdapter5 implements IBrowserAdapter { private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() : new RhoLogger("BrowserAdapter"); private RhoMainScreen m_oMainScreen; private BrowserField m_oBrowserField; private BrowserFieldConfig m_oConfig; private RhodesApplication m_app; private class RhoProtocolController extends ProtocolController { public RhoProtocolController(BrowserField browserField) { super(browserField); } public void handleNavigationRequest(BrowserFieldRequest request) throws Exception { String url = request.getURL(); if ( request.getPostData() == null || request.getPostData().length == 0 ) { //String referrer = request.getHeaders().getPropertyValue("referer"); m_app.addToHistory(url, null ); } PrimaryResourceFetchThread thread = new PrimaryResourceFetchThread( url, request.getHeaders(),request.getPostData(),url); thread.start(); } public InputConnection handleResourceRequest(BrowserFieldRequest request) throws Exception { String url = request.getURL(); if ( RhodesApp.getInstance().isRhodesAppUrl(url) || URI.isLocalData(url)) { HttpConnection connection = Utilities.makeConnection(url, request.getHeaders(), null, null); return connection; }else return super.handleResourceRequest(request); } public void setNavigationRequestHandler(String protocol, BrowserFieldNavigationRequestHandler handler) { super.setNavigationRequestHandler(protocol, handler); } public void setResourceRequestHandler(String protocol, BrowserFieldResourceRequestHandler handler) { super.setResourceRequestHandler(protocol, handler); } }; private RhoProtocolController m_oController; public BrowserAdapter5(RhoMainScreen oMainScreen, RhodesApplication app) { m_oMainScreen = oMainScreen; m_app = app; m_oConfig = new BrowserFieldConfig(); m_oConfig.setProperty( BrowserFieldConfig.NAVIGATION_MODE, BrowserFieldConfig.NAVIGATION_MODE_POINTER ); m_oConfig.setProperty( BrowserFieldConfig.JAVASCRIPT_ENABLED, Boolean.TRUE ); // m_oConfig.setProperty( BrowserFieldConfig.NAVIGATION_MODE, BrowserFieldConfig.NAVIGATION_MODE_CARET ); m_oConfig.setProperty( BrowserFieldConfig.ENABLE_COOKIES, Boolean.TRUE ); } public void setFullBrowser() { } private void createBrowserField() { LOG.INFO("Use BrowserField5"); m_oBrowserField = new BrowserField(m_oConfig); m_oBrowserField.getRenderingOptions().setProperty(RenderingOptions.CORE_OPTIONS_GUID, RenderingOptions.ALLOW_POPUPS, true); m_oController = new RhoProtocolController(m_oBrowserField); m_oConfig.setProperty(BrowserFieldConfig.CONTROLLER, m_oController); BrowserFieldListener _listener = new BrowserFieldListener() { public void documentLoaded(BrowserField browserField, org.w3c.dom.Document document) throws Exception { synchronized (Application.getEventLock()) { m_oMainScreen.deleteAll(); m_oMainScreen.add(m_oBrowserField); } } /* public void downloadProgress(BrowserField browserField, net.rim.device.api.browser.field.ContentReadEvent event)throws Exception { //Add your code here. }*/ }; m_oBrowserField.addListener( _listener ); } public void processConnection(HttpConnection connection, Object e) { synchronized (Application.getEventLock()) { createBrowserField(); m_oBrowserField.displayContent(connection, (e != null ? (String)e : "") ); } } public void executeJavascript(String strJavascript) { //synchronized (Application.getEventLock()) { BrowserField field = (BrowserField)m_oMainScreen.getField(0); field.executeScript(strJavascript); } } public boolean navigationMovement(int dx, int dy, int status, int time) { //TODO: try to change navigation /* Field focField = m_oBrowserField.getLeafFieldWithFocus(); Manager focManager = focField != null ? focField.getManager() : null; boolean bHorizontal = false; if ( focManager != null && focManager instanceof HorizontalFieldManager) bHorizontal = true; */ return false; } }
package org.books.data.entity; import javax.persistence.*; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; @NamedQueries({ @NamedQuery(name = "Order.findByNumber", query = "from Order o where UPPER(o.number) = UPPER(:number)"), @NamedQuery(name = "Order.findByCustomerAndYear", query = "from Order o where o.customer = :customer AND EXTRACT(YEAR from o.date) = :year") }) @Entity @Table(name="command") public class Order extends BaseEntity { public enum Status { accepted, processing, shipped, canceled } @Column(nullable = false, name = "command_number") private String number; @Temporal(TemporalType.DATE) @Column(nullable = false) private Date date; @Column(nullable = false) private BigDecimal amount; @Enumerated(EnumType.STRING) private Status status; @ManyToOne(optional = false) @JoinColumn(name = "customer_id") private Customer customer; @Embedded private Address address; @Embedded private CreditCard creditCard; @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true) @JoinColumn(name = "order_id") private List<OrderItem> items = new ArrayList<>(); public Order() { } public Order(String number, Date date, BigDecimal amount, Status status, Customer customer, Address address, CreditCard creditCard, List<OrderItem> items) { this.number = number; this.date = date; this.amount = amount; this.status = status; this.customer = customer; this.address = address; this.creditCard = creditCard; this.items = items; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public CreditCard getCreditCard() { return creditCard; } public void setCreditCard(CreditCard card) { this.creditCard = card; } public List<OrderItem> getItems() { return items; } public void setItems(List<OrderItem> items) { this.items = items; } }
package com.intellij.patterns; import com.intellij.util.ProcessingContext; import org.jetbrains.annotations.NotNull; /** * @author peter */ public class CharPattern extends ObjectPattern<Character, CharPattern> { private final CharPattern myJavaIdentifierPartPattern = with(new PatternCondition<Character>("javaIdentifierPart") { @Override public boolean accepts(@NotNull final Character character, final ProcessingContext context) { return Character.isJavaIdentifierPart(character.charValue()); } }); private final CharPattern myJavaIdentifierStartPattern = with(new PatternCondition<Character>("javaIdentifierStart") { @Override public boolean accepts(@NotNull final Character character, final ProcessingContext context) { return Character.isJavaIdentifierStart(character.charValue()); } }); private final CharPattern myWhitespacePattern = with(new PatternCondition<Character>("whitespace") { @Override public boolean accepts(@NotNull final Character character, final ProcessingContext context) { return Character.isWhitespace(character.charValue()); } }); private final CharPattern myLetterOrDigitPattern = with(new PatternCondition<Character>("letterOrDigit") { @Override public boolean accepts(@NotNull final Character character, final ProcessingContext context) { return Character.isLetterOrDigit(character.charValue()); } }); protected CharPattern() { super(Character.class); } public CharPattern javaIdentifierPart() { return myJavaIdentifierPartPattern; } public CharPattern javaIdentifierStart() { return myJavaIdentifierStartPattern; } public CharPattern whitespace() { return myWhitespacePattern; } public CharPattern letterOrDigit() { return myLetterOrDigitPattern; } }
package com.intellij.idea; import com.intellij.diagnostic.LogMessage; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.plugins.PluginManager; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ex.ApplicationInfoEx; import com.intellij.openapi.application.impl.ApplicationImpl; import com.intellij.openapi.application.impl.ApplicationInfoImpl; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.diagnostic.*; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.ExceptionUtil; import org.apache.log4j.DefaultThrowableRenderer; import org.apache.log4j.Logger; import org.apache.log4j.spi.LoggerRepository; import org.apache.log4j.spi.ThrowableRenderer; import org.apache.log4j.spi.ThrowableRendererSupport; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author Mike */ public class IdeaLogger extends Log4jBasedLogger { @SuppressWarnings("StaticNonFinalField") public static String ourLastActionId = ""; @SuppressWarnings("StaticNonFinalField") public static Exception ourErrorsOccurred; // when not null, holds the first of errors that occurred private static final ApplicationInfoProvider ourApplicationInfoProvider; private static final ThrowableRenderer ourThrowableRenderer; static { ourApplicationInfoProvider = () -> { ApplicationInfoEx info = ApplicationInfoImpl.getShadowInstance(); return info.getFullApplicationName() + " " + "Build #" + info.getBuild().asString(); }; ourThrowableRenderer = t -> { String[] lines = DefaultThrowableRenderer.render(t); int maxStackSize = 1024; int maxExtraSize = 256; if (lines.length > maxStackSize + maxExtraSize) { String[] res = new String[maxStackSize + maxExtraSize + 1]; System.arraycopy(lines, 0, res, 0, maxStackSize); res[maxStackSize] = "\t..."; System.arraycopy(lines, lines.length - maxExtraSize, res, maxStackSize + 1, maxExtraSize); return res; } return lines; }; } @Nullable public static String getOurCompilationTimestamp() { return null; } @NotNull public static ThrowableRenderer getThrowableRenderer() { return ourThrowableRenderer; } IdeaLogger(@NotNull Logger logger) { super(logger); LoggerRepository repository = myLogger.getLoggerRepository(); if (repository instanceof ThrowableRendererSupport) { ((ThrowableRendererSupport)repository).setThrowableRenderer(ourThrowableRenderer); } } @Override public void error(Object message) { if (message instanceof IdeaLoggingEvent) { myLogger.error(message); } else { super.error(message); } } @Override public void error(String message, @Nullable Throwable t, @NotNull Attachment... attachments) { myLogger.error(LogMessage.createEvent(t != null ? t : new Throwable(), message, attachments)); } @Override public void warn(String message, @Nullable Throwable t) { super.warn(message, checkException(t)); } @Override public void error(String message, @Nullable Throwable t, @NotNull String... details) { if (t instanceof ControlFlowException) { myLogger.error(message, checkException(t)); ExceptionUtil.rethrow(t); } String detailString = StringUtil.join(details, "\n"); if (!detailString.isEmpty()) { detailString = "\nDetails: " + detailString; } if (ourErrorsOccurred == null) { String mess = "Logger errors occurred. See IDEA logs for details. " + (StringUtil.isEmpty(message) ? "" : "Error message is '" + message + "'"); //noinspection AssignmentToStaticFieldFromInstanceMethod ourErrorsOccurred = new Exception(mess + detailString, t); } myLogger.error(message + detailString, t); logErrorHeader(t); } private void logErrorHeader(@Nullable Throwable t) { myLogger.error(ourApplicationInfoProvider.getInfo()); myLogger.error("JDK: " + System.getProperties().getProperty("java.version", "unknown")+ "; VM: " + System.getProperties().getProperty("java.vm.name", "unknown") + "; Vendor: " + System.getProperties().getProperty("java.vendor", "unknown")); myLogger.error("OS: " + System.getProperties().getProperty("os.name", "unknown")); IdeaPluginDescriptor plugin = t == null ? null : PluginManager.findPluginIfInitialized(t); if (plugin != null && (!plugin.isBundled() || plugin.allowBundledUpdate())) { myLogger.error("Plugin to blame: " + plugin.getName() + " version: " + plugin.getVersion()); } ApplicationImpl application = (ApplicationImpl)ApplicationManager.getApplication(); if (application != null && application.isComponentsCreated() && !application.isDisposed()) { String lastPreformedActionId = ourLastActionId; if (lastPreformedActionId != null) { myLogger.error("Last Action: " + lastPreformedActionId); } CommandProcessor commandProcessor = CommandProcessor.getInstance(); if (commandProcessor != null) { String currentCommandName = commandProcessor.getCurrentCommandName(); if (currentCommandName != null) { myLogger.error("Current Command: " + currentCommandName); } } } } }
package ch.mlutz.plugins.t4e.tapestry.editor; import org.eclipse.ui.editors.text.TextEditor; import ch.mlutz.plugins.t4e.Activator; public class TapestryEditor extends TextEditor { private ColorManager colorManager; public TapestryEditor() { super(); colorManager = new ColorManager(); setSourceViewerConfiguration(new TapestryConfiguration(colorManager)); setDocumentProvider(new TapestryDocumentProvider()); } public void dispose() { Activator.getDefault().getTapestryIndex().removeDocumentToFileMapping( this.getSourceViewer().getDocument()); colorManager.dispose(); super.dispose(); } }
package org.apereo.cas.config; import org.apereo.cas.MongoDbPropertySourceLocator; import lombok.val; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory; import java.util.Objects; /** * This is {@link MongoDbCloudConfigBootstrapConfiguration}. * * @author Misagh Moayyed * @since 5.0.0 */ @Configuration("mongoDbCloudConfigBootstrapConfiguration") public class MongoDbCloudConfigBootstrapConfiguration { /** * MongoDb CAS configuration key prefix. */ public static final String CAS_CONFIGURATION_MONGODB_URI = "cas.spring.cloud.mongo.uri"; @Autowired private ConfigurableEnvironment environment; @Bean public MongoDbPropertySourceLocator mongoDbPropertySourceLocator() { val mongoTemplate = mongoDbCloudConfigurationTemplate(); return new MongoDbPropertySourceLocator(mongoTemplate); } @Bean public MongoTemplate mongoDbCloudConfigurationTemplate() { val uri = Objects.requireNonNull(environment.getProperty(CAS_CONFIGURATION_MONGODB_URI)); return new MongoTemplate(new SimpleMongoClientDatabaseFactory(uri)); } }
package org.envirocar.server.etl; import org.envirocar.server.etl.constants.RDFDumpNames; import org.envirocar.server.etl.dataSetDump.DatasetDump; import org.envirocar.server.etl.dataSetDump.POJODatasetDump; import org.envirocar.server.etl.entity.Cloner; import org.envirocar.server.etl.entity.MongoCloner; import org.envirocar.server.etl.loader.FusekiLoader; import org.envirocar.server.etl.loader.RDFDumpWriter; import org.envirocar.server.etl.loader.SPARQLGraphProtocolLoader; import org.envirocar.server.etl.utils.ConfigReader; import org.envirocar.server.etl.utils.RDFUtils; import java.net.UnknownHostException; /** * @author deepaknair on 14/07/15 * Creates an RDF dump of file of all envirocar data , usefuel for updating through sparql protocolo. */ public class MongoToRDFFile implements ETLProcess { MongoCloner mongoCloner; POJODatasetDump dataSetDump; SPARQLGraphProtocolLoader sparqlGraphProtocolLoader; MongoToRDFFile() throws UnknownHostException { this.mongoCloner = new MongoCloner(); this.sparqlGraphProtocolLoader = new SPARQLGraphProtocolLoader(); } public static void main(String[] args) throws Exception { MongoToRDFFile etl = new MongoToRDFFile(); etl.dataSetDump = etl.mongoCloner.cloneIntoMemory(); RDFDumpWriter.writeIntoFile(RDFUtils.encodeTracks(etl.dataSetDump.trackPOJOList), RDFDumpNames.TRACKS_RDF_LOCATION); RDFDumpWriter.writeIntoFile(RDFUtils.encodeMeasurements(etl.dataSetDump.measurementPOJOList), RDFDumpNames.MEASUREMENTS_RDF_LOCATION); RDFDumpWriter.writeIntoFile(RDFUtils.encodePhenomenons(etl.dataSetDump.phenomenonPOJOList), RDFDumpNames.PHENOMENONS_RDF_LOCATION); RDFDumpWriter.writeIntoFile(RDFUtils.encodeSensors(etl.dataSetDump.sensorPOJOList), RDFDumpNames.SENSORS_RDF_LOCATION); etl.sparqlGraphProtocolLoader.load(ConfigReader.ENDPOINT_URL, ConfigReader.DUMP_LOCATION); } @Override public Cloner getCloner() { return this.mongoCloner; } @Override public DatasetDump getDataSetDump() { return dataSetDump; } @Override public FusekiLoader getDumpWriter() { return null; } }
package de.dakror.vloxlands.game.world; import java.util.Iterator; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.RenderableProvider; import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Pool; import de.dakror.vloxlands.game.entity.Entity; import de.dakror.vloxlands.render.Mesher; import de.dakror.vloxlands.util.Tickable; /** * @author Dakror */ public class World implements RenderableProvider, Tickable { public static final Color SELECTION = Color.valueOf("ff9900"); public static final int MAXHEIGHT = 512; public static final short GROUND_FLAG = 1 << 8; public static final short ENTITY_FLAG = 1 << 9; public static final short ALL_FLAG = -1; static Material opaque, transp, highlight; Island[] islands; int width, depth; public int visibleChunks, chunks, visibleEntities; public static Mesh chunkCube, blockCube; public static final float gap = 0.01f; Array<Entity> entities = new Array<Entity>(); // btCollisionConfiguration collisionConfiguration; // btBroadphaseInterface broadphaseInterface; // btCollisionDispatcher collisionDispatcher; // btDiscreteDynamicsWorld collisionWorld; // btSequentialImpulseConstraintSolver constraintSolver; // btGhostPairCallback ghostPairCallback; // DebugDrawer debugDrawer; // public boolean debug; public World(int width, int depth) { this.width = width; this.depth = depth; islands = new Island[width * depth]; Texture tex = new Texture(Gdx.files.internal("img/voxelTextures.png")); Texture tex2 = new Texture(Gdx.files.internal("img/transparent.png")); opaque = new Material(TextureAttribute.createDiffuse(tex)); transp = new Material(TextureAttribute.createDiffuse(tex), new BlendingAttribute()); highlight = new Material(TextureAttribute.createDiffuse(tex2), ColorAttribute.createDiffuse(SELECTION)); chunkCube = Mesher.genCubeWireframe(Chunk.SIZE + gap); blockCube = Mesher.genCubeWireframe(1 + gap); // collisionConfiguration = new btDefaultCollisionConfiguration(); // collisionDispatcher = new btCollisionDispatcher(collisionConfiguration); // broadphaseInterface = new btDbvtBroadphase(); // ghostPairCallback = new btGhostPairCallback(); // broadphaseInterface.getOverlappingPairCache().setInternalGhostPairCallback(ghostPairCallback); // constraintSolver = new btSequentialImpulseConstraintSolver(); // collisionWorld = new btDiscreteDynamicsWorld(collisionDispatcher, broadphaseInterface, constraintSolver, collisionConfiguration); // collisionWorld.setGravity(new Vector3(0, -9.81f, 0)); // debugDrawer = new DebugDrawer(); // debugDrawer.setDebugMode(DebugDrawModes.DBG_DrawAabb); // collisionWorld.setDebugDrawer(debugDrawer); } /** * @param x in index space * @param y in pos space * @param z in index space */ public void addIsland(int x, int z, Island island) { islands[z * width + x] = island; chunks += Island.CHUNKS * Island.CHUNKS * Island.CHUNKS; } public void update() { for (Iterator<Entity> iter = entities.iterator(); iter.hasNext();) { Entity e = iter.next(); e.update(); } // collisionWorld.stepSimulation(Gdx.graphics.getDeltaTime(), 5, 1 / 60f); for (Iterator<Entity> iter = entities.iterator(); iter.hasNext();) { Entity e = iter.next(); e.updateTransform(); } } @Override public void tick(int tick) { for (Island island : islands) if (island != null) island.tick(tick); for (Iterator<Entity> iter = entities.iterator(); iter.hasNext();) { Entity e = iter.next(); if (e.isMarkedForRemoval()) { e.dispose(); iter.remove(); } else e.tick(tick); } } public Island[] getIslands() { return islands; } public Array<Entity> getEntities() { return entities; } public int getWidth() { return width; } public int getDepth() { return depth; } public int getEntityCount() { return entities.size; } public void addEntity(Entity e) { entities.add(e); e.onSpawn(); } // public btDiscreteDynamicsWorld getCollisionWorld() // return collisionWorld; @Override public void getRenderables(Array<Renderable> renderables, Pool<Renderable> pool) { visibleChunks = 0; for (Island island : islands) { if (island != null) { island.getRenderables(renderables, pool); visibleChunks += island.visibleChunks; } } } public void render(ModelBatch batch, Environment environment) { // if (debugDrawer != null && debugDrawer.getDebugMode() > 0 && debug) // Gdx.gl.glEnable(GL20.GL_DEPTH_TEST); // debugDrawer.begin(batch.getCamera()); // debugDrawer.shapeRenderer.identity(); // debugDrawer.shapeRenderer.translate(0.5f, 0.5f, 0.5f); // collisionWorld.debugDrawWorld(); // debugDrawer.end(); // System.gc(); batch.render(this, environment); visibleEntities = 0; for (Iterator<Entity> iter = entities.iterator(); iter.hasNext();) { Entity e = iter.next(); if (e.inFrustum) { e.render(batch, environment); visibleEntities++; } } } public static float calculateUplift(float height) { return (1 - height / MAXHEIGHT) * 4 + 0.1f; } }
package hudson.slaves; import hudson.Extension; import hudson.Util; import hudson.model.Computer; import hudson.model.Descriptor; import hudson.model.DescriptorVisibilityFilter; import hudson.model.TaskListener; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import jenkins.model.Jenkins; import jenkins.slaves.RemotingWorkDirSettings; import org.jenkinsci.Symbol; import org.kohsuke.accmod.Restricted; import org.kohsuke.accmod.restrictions.NoExternalUse; import org.kohsuke.stapler.DataBoundConstructor; /** * {@link ComputerLauncher} via JNLP. * * @author Stephen Connolly * @author Kohsuke Kawaguchi */ public class JNLPLauncher extends ComputerLauncher { /** * If the agent needs to tunnel the connection to the master, * specify the "host:port" here. This can include the special * syntax "host:" and ":port" to indicate the default host/port * shall be used. * * <p> * Null if no tunneling is necessary. * * @since 1.250 */ @CheckForNull public final String tunnel; /** * Additional JVM arguments. Can be null. * @since 1.297 */ @CheckForNull public final String vmargs; @Nonnull private RemotingWorkDirSettings workDirSettings; @DataBoundConstructor public JNLPLauncher(@CheckForNull String tunnel, @CheckForNull String vmargs, @CheckForNull RemotingWorkDirSettings workDirSettings) { this.tunnel = Util.fixEmptyAndTrim(tunnel); this.vmargs = Util.fixEmptyAndTrim(vmargs); this.workDirSettings = workDirSettings; } @Deprecated public JNLPLauncher(String tunnel, String vmargs) { // TODO: Enable workDir by default in API? Otherwise classes inheriting from JNLPLauncher // will need to enable the feature by default as well. this(tunnel, vmargs, RemotingWorkDirSettings.getDisabledDefaults()); } /** * @deprecated This Launcher does not enable the work directory. * It is recommended to use {@link #JNLPLauncher(boolean)} */ @Deprecated public JNLPLauncher() { this(false); } /** * Constructor with default options. * * @param enableWorkDir If {@code true}, the work directory will be enabled with default settings. */ public JNLPLauncher(boolean enableWorkDir) { this(null, null, enableWorkDir ? RemotingWorkDirSettings.getEnabledDefaults() : RemotingWorkDirSettings.getDisabledDefaults()); } protected Object readResolve() { if (workDirSettings == null) { // For the migrated code agents are always disabled workDirSettings = RemotingWorkDirSettings.getDisabledDefaults(); } return this; } /** * Returns work directory settings. * * @since 2.72 */ @Nonnull public RemotingWorkDirSettings getWorkDirSettings() { return workDirSettings; } @Override public boolean isLaunchSupported() { return false; } @Override public void launch(SlaveComputer computer, TaskListener listener) { // do nothing as we cannot self start } /** * @deprecated as of 1.XXX * Use {@link Jenkins#getDescriptor(Class)} */ public static /*almost final*/ Descriptor<ComputerLauncher> DESCRIPTOR; /** * Gets work directory options as a String. * * In public API {@code getWorkDirSettings().toCommandLineArgs(computer)} should be used instead * @param computer Computer * @return Command line options for launching with the WorkDir */ @Nonnull @Restricted(NoExternalUse.class) public String getWorkDirOptions(@Nonnull Computer computer) { if(!(computer instanceof SlaveComputer)) { return ""; } return workDirSettings.toCommandLineString((SlaveComputer)computer); } @Extension @Symbol("jnlp") public static class DescriptorImpl extends Descriptor<ComputerLauncher> { public DescriptorImpl() { DESCRIPTOR = this; } public String getDisplayName() { return Messages.JNLPLauncher_displayName(); } /** * Checks if Work Dir settings should be displayed. * * This flag is checked in {@code config.jelly} before displaying the * {@link JNLPLauncher#workDirSettings} property. * By default the configuration is displayed only for {@link JNLPLauncher}, * but the implementation can be overridden. * @return {@code true} if work directories are supported by the launcher type. * @since 2.73 */ public boolean isWorkDirSupported() { // This property is included only for JNLPLauncher by default. // Causes JENKINS-45895 in the case of includes otherwise return DescriptorImpl.class.equals(getClass()); } }; /** * Hides the JNLP launcher when the JNLP agent port is not enabled. * * @since 2.16 */ @Extension public static class DescriptorVisibilityFilterImpl extends DescriptorVisibilityFilter { /** * {@inheritDoc} */ @Override public boolean filter(@CheckForNull Object context, @Nonnull Descriptor descriptor) { return descriptor.clazz != JNLPLauncher.class || Jenkins.getInstance().getTcpSlaveAgentListener() != null; } /** * {@inheritDoc} */ @Override public boolean filterType(@Nonnull Class<?> contextClass, @Nonnull Descriptor descriptor) { return descriptor.clazz != JNLPLauncher.class || Jenkins.getInstance().getTcpSlaveAgentListener() != null; } } }
package edu.umd.cs.findbugs.cloud; import java.io.IOException; import java.io.PrintWriter; import java.net.URL; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.annotation.CheckForNull; import edu.umd.cs.findbugs.AppVersion; import edu.umd.cs.findbugs.BugCollection; import edu.umd.cs.findbugs.BugDesignation; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.I18N; import edu.umd.cs.findbugs.PackageStats; import edu.umd.cs.findbugs.ProjectStats; import edu.umd.cs.findbugs.PropertyBundle; import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.cloud.username.NameLookup; import edu.umd.cs.findbugs.util.ClassName; import edu.umd.cs.findbugs.util.Multiset; /** * @author William Pugh */ public abstract class AbstractCloud implements Cloud { public static long MIN_TIMESTAMP; protected static final boolean THROW_EXCEPTION_IF_CANT_CONNECT = false; private static final Mode DEFAULT_VOTING_MODE = Mode.COMMUNAL; private static final Logger LOGGER = Logger.getLogger(AbstractCloud.class.getName()); private static final String LEADERBOARD_BLACKLIST = SystemProperties.getProperty("findbugs.leaderboard.blacklist"); private static final Pattern LEADERBOARD_BLACKLIST_PATTERN; static { Pattern p = null; if (LEADERBOARD_BLACKLIST != null) { try { p = Pattern.compile(LEADERBOARD_BLACKLIST.replace(',', '|')); } catch (Exception e) { LOGGER.log(Level.WARNING, "Could not load leaderboard blacklist pattern", e); } } LEADERBOARD_BLACKLIST_PATTERN = p; try { MIN_TIMESTAMP = DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.US).parse("Jan 23, 1996").getTime(); } catch (ParseException e) { throw new IllegalStateException(e); } } protected final CloudPlugin plugin; protected final BugCollection bugCollection; protected final PropertyBundle properties; @CheckForNull private Pattern sourceFileLinkPattern; private String sourceFileLinkFormat; private String sourceFileLinkFormatWithLine; private String sourceFileLinkToolTip; private CopyOnWriteArraySet<CloudListener> listeners = new CopyOnWriteArraySet<CloudListener>(); private CopyOnWriteArraySet<CloudStatusListener> statusListeners = new CopyOnWriteArraySet<CloudStatusListener>(); private Mode mode = Mode.COMMUNAL; private String statusMsg; private SigninState signinState = SigninState.NOT_SIGNED_IN_YET; protected AbstractCloud(CloudPlugin plugin, BugCollection bugs, Properties properties) { this.plugin = plugin; this.bugCollection = bugs; this.properties = plugin.getProperties().copy(); if (!properties.isEmpty()) { this.properties.loadProperties(properties); } } public boolean initialize() throws IOException { String modeString = getCloudProperty("votingmode"); Mode newMode = DEFAULT_VOTING_MODE; if (modeString != null) { try { newMode = Mode.valueOf(modeString.toUpperCase()); } catch (IllegalArgumentException e) { LOGGER.log(Level.WARNING, "No such voting mode " + modeString, e); } } setMode(newMode); String sp = properties.getProperty("findbugs.sourcelink.pattern"); String sf = properties.getProperty("findbugs.sourcelink.format"); String sfwl = properties.getProperty("findbugs.sourcelink.formatWithLine"); String stt = properties.getProperty("findbugs.sourcelink.tooltip"); if (sp != null && sf != null) { try { this.sourceFileLinkPattern = Pattern.compile(sp); this.sourceFileLinkFormat = sf; this.sourceFileLinkToolTip = stt; this.sourceFileLinkFormatWithLine = sfwl; } catch (RuntimeException e) { LOGGER.log(Level.WARNING, "Could not compile pattern " + sp, e); if (THROW_EXCEPTION_IF_CANT_CONNECT) throw e; } } return true; } public Mode getMode() { return mode; } public void setMode(Mode mode) { this.mode = mode; } public CloudPlugin getPlugin() { return plugin; } public BugCollection getBugCollection() { return bugCollection; } public boolean supportsBugLinks() { return false; } public boolean supportsClaims() { return false; } public boolean supportsCloudReports() { return true; } public String claimedBy(BugInstance b) { throw new UnsupportedOperationException(); } public boolean claim(BugInstance b) { throw new UnsupportedOperationException(); } public URL getBugLink(BugInstance b) { throw new UnsupportedOperationException(); } public String getBugLinkType(BugInstance instance) { return null; } public URL fileBug(BugInstance bug) { throw new UnsupportedOperationException(); } public BugFilingStatus getBugLinkStatus(BugInstance b) { throw new UnsupportedOperationException(); } public boolean canSeeCommentsByOthers(BugInstance bug) { switch(getMode()) { case SECRET: return false; case COMMUNAL : return true; case VOTING : return hasVoted(bug); } throw new IllegalStateException(); } public boolean hasVoted(BugInstance bug) { for(BugDesignation bd : getLatestDesignationFromEachUser(bug)) if (getUser().equals(bd.getUser())) return true; return false; } public String getCloudReport(BugInstance b) { SimpleDateFormat format = new SimpleDateFormat("MM/dd, yyyy"); StringBuilder builder = new StringBuilder(); long firstSeen = getFirstSeen(b); builder.append(String.format("First seen %s%n", format.format(new Date(firstSeen)))); builder.append("\n"); I18N i18n = I18N.instance(); boolean canSeeCommentsByOthers = canSeeCommentsByOthers(b); if (canSeeCommentsByOthers && supportsBugLinks()) { BugFilingStatus bugLinkStatus = getBugLinkStatus(b); if (bugLinkStatus != null && bugLinkStatus.bugIsFiled()) { //if (bugLinkStatus.) builder.append("\nBug status is ").append(getBugStatus(b)); //else // builder.append("\nBug assigned to " + bd.bugAssignedTo + ", status is " + bd.bugStatus); builder.append("\n\n"); } } String me = getUser(); for(BugDesignation d : getLatestDesignationFromEachUser(b)) { if ((me != null && me.equals(d.getUser()))|| canSeeCommentsByOthers ) { builder.append(String.format("%s @ %s: %s%n", d.getUser(), format.format(new Date(d.getTimestamp())), i18n.getUserDesignation(d.getDesignationKey()))); String annotationText = d.getAnnotationText(); if (annotationText != null && annotationText.length() > 0) { builder.append(annotationText); builder.append("\n\n"); } } } return builder.toString(); } protected String getBugStatus(BugInstance b) { return null; } protected abstract Iterable<BugDesignation> getLatestDesignationFromEachUser(BugInstance bd); public Date getUserDate(BugInstance b) { return new Date(getUserTimestamp(b)); } public void addListener(CloudListener listener) { if (listener == null) throw new NullPointerException(); if (!listeners.contains(listener)) listeners.add(listener); } public void removeListener(CloudListener listener) { listeners.remove(listener); } public void addStatusListener(CloudStatusListener listener) { if (listener == null) throw new NullPointerException(); if (!statusListeners.contains(listener)) statusListeners.add(listener); } public void removeStatusListener(CloudStatusListener listener) { statusListeners.remove(listener); } public String getStatusMsg() { return statusMsg; } public void shutdown() { } public boolean getIWillFix(BugInstance b) { return getUserDesignation(b) == UserDesignation.I_WILL_FIX; } public UserDesignation getConsensusDesignation(BugInstance b) { Multiset<UserDesignation> designations = new Multiset<UserDesignation>(); int count = 0; int totalCount = 0; double total = 0.0; int isAProblem = 0; int notAProblem = 0; for (BugDesignation designation : getLatestDesignationFromEachUser(b)) { UserDesignation d = UserDesignation.valueOf(designation.getDesignationKey()); if (d == UserDesignation.I_WILL_FIX) d = UserDesignation.MUST_FIX; else if (d == UserDesignation.UNCLASSIFIED) continue; switch (d) { case I_WILL_FIX: case MUST_FIX: case SHOULD_FIX: isAProblem++; break; case BAD_ANALYSIS: case NOT_A_BUG: case MOSTLY_HARMLESS: case OBSOLETE_CODE: notAProblem++; break; } designations.add(d); totalCount++; if (d.nonVoting()) continue; count++; total += d.score(); } if (totalCount == 0) return UserDesignation.UNCLASSIFIED; UserDesignation mostCommonVotingDesignation = null; UserDesignation mostCommonDesignation = null; for(Map.Entry<UserDesignation,Integer> e : designations.entriesInDecreasingFrequency()) { UserDesignation d = e.getKey(); if (mostCommonVotingDesignation == null && !d.nonVoting()) { mostCommonVotingDesignation = d; if (e.getValue() > count/2) return d; } if (mostCommonDesignation == null && d != UserDesignation.UNCLASSIFIED) { mostCommonDesignation = d; if (e.getValue() > count/2) return d; } } double score = total/count; if (score >= UserDesignation.SHOULD_FIX.score() || isAProblem > notAProblem) return UserDesignation.SHOULD_FIX; if (score <= UserDesignation.NOT_A_BUG.score()) return UserDesignation.NOT_A_BUG; if (score <= UserDesignation.MOSTLY_HARMLESS.score() || notAProblem > isAProblem) return UserDesignation.MOSTLY_HARMLESS; return UserDesignation.NEEDS_STUDY; } public double getClassificationScore(BugInstance b) { int count = 0; double total = 0.0; for (BugDesignation designation : getLatestDesignationFromEachUser(b)) { UserDesignation d = UserDesignation.valueOf(designation.getDesignationKey()); if (d.nonVoting()) continue; count++; total += d.score(); } return total / count; } public double getClassificationVariance(BugInstance b) { int count = 0; double total = 0.0; double totalSquares = 0.0; for (BugDesignation designation : getLatestDesignationFromEachUser(b)) { UserDesignation d = UserDesignation.valueOf(designation.getDesignationKey()); if (d.nonVoting()) continue; count++; total += d.score(); totalSquares += d.score() * d.score(); } double average = total/count; return totalSquares / count - average*average; } public double getPortionObsoleteClassifications(BugInstance b) { int count = 0; double total = 0.0; for (BugDesignation designation : getLatestDesignationFromEachUser(b)) { count++; UserDesignation d = UserDesignation.valueOf(designation.getDesignationKey()); if ( d == UserDesignation.OBSOLETE_CODE) total++; } return total / count; } public int getNumberReviewers(BugInstance b) { int count = 0; Iterable<BugDesignation> designations = getLatestDesignationFromEachUser(b); for (BugDesignation designation : designations) { count++; } return count; } @SuppressWarnings("boxing") public void printCloudSummary(PrintWriter w, Iterable<BugInstance> bugs, String[] packagePrefixes) { Multiset<String> evaluations = new Multiset<String>(); Multiset<String> designations = new Multiset<String>(); Multiset<String> bugStatus = new Multiset<String>(); int issuesWithThisManyReviews [] = new int[100]; I18N i18n = I18N.instance(); int packageCount = 0; int classCount = 0; int ncss = 0; ProjectStats projectStats = bugCollection.getProjectStats(); for(PackageStats ps : projectStats.getPackageStats()) { int num = ps.getNumClasses(); if (ClassName.matchedPrefixes(packagePrefixes, ps.getPackageName()) && num > 0) { packageCount++; ncss += ps.size(); classCount += num; } } if (classCount == 0) { w.println("No classes were analyzed"); return; } if (packagePrefixes != null && packagePrefixes.length > 0) { String lst = Arrays.asList(packagePrefixes).toString(); w.println("Code analyzed in " + lst.substring(1, lst.length()-1)); } else { w.println("Code analyzed"); } w.printf("%,7d packages%n%,7d classes%n", packageCount, classCount); if (ncss > 0) w.printf("%,7d thousands of lines of non-commenting source statements%n", (ncss+999)/1000); w.println(); int count = 0; for(BugInstance bd : bugs) { count++; HashSet<String> reviewers = new HashSet<String>(); String status = supportsBugLinks() ? getBugStatus(bd) : null; if (status != null) bugStatus.add(status); for(BugDesignation d : getLatestDesignationFromEachUser(bd)) if (reviewers.add(d.getUser())) { evaluations.add(d.getUser()); designations.add(i18n.getUserDesignation(d.getDesignationKey())); } int numReviews = Math.min( reviewers.size(), issuesWithThisManyReviews.length -1); issuesWithThisManyReviews[numReviews]++; } if (count == getBugCollection().getCollection().size()) w.printf("Summary for %d issues%n%n", count); else w.printf("Summary for %d issues that are in the current view%n%n", count); if (evaluations.numKeys() == 0) { w.println("No evaluations found"); } else { w.println("People who have performed the most reviews"); printLeaderBoard(w, evaluations, 9, getUser(), true, "reviewer"); w.println(); w.println("Distribution of evaluations"); printLeaderBoard(w, designations, 100, " --- ", false, "designation"); } if (supportsBugLinks()) { if (bugStatus.numKeys() == 0) { w.println(); w.println("No bugs filed"); } else { w.println(); w.println("Distribution of bug status"); printLeaderBoard(w, bugStatus, 100, " --- ", false, "status of filed bug"); }} w.println(); w.println("Distribution of number of reviews"); for(int i = 0; i < issuesWithThisManyReviews.length; i++) if (issuesWithThisManyReviews[i] > 0) { w.printf("%4d with %3d review", issuesWithThisManyReviews[i], i); if (i != 1) w.print("s"); w.println(); } } @SuppressWarnings("boxing") public static void printLeaderBoard2(PrintWriter w, Multiset<String> evaluations, int maxRows, String alwaysPrint, String format, String title) { int row = 1; int position = 0; int previousScore = -1; boolean foundAlwaysPrint = false; for(Map.Entry<String,Integer> e : evaluations.entriesInDecreasingFrequency()) { int num = e.getValue(); if (num != previousScore) { position = row; previousScore = num; } String key = e.getKey(); if (LEADERBOARD_BLACKLIST_PATTERN != null && LEADERBOARD_BLACKLIST_PATTERN.matcher(key).matches()) continue; boolean shouldAlwaysPrint = key.equals(alwaysPrint); if (row <= maxRows || shouldAlwaysPrint) w.printf(format, position, num, key); if (shouldAlwaysPrint) foundAlwaysPrint = true; row++; if (row >= maxRows) { if (alwaysPrint == null) break; if (foundAlwaysPrint) { w.printf("Total of %d %ss%n", evaluations.numKeys(), title); break; } } } } public boolean supportsCloudSummaries() { return true; } public boolean canStoreUserAnnotation(BugInstance bugInstance) { return true; } public double getClassificationDisagreement(BugInstance b) { return 0; } public UserDesignation getUserDesignation(BugInstance b) { BugDesignation bd = getPrimaryDesignation(b); if (bd == null) return UserDesignation.UNCLASSIFIED; return UserDesignation.valueOf(bd.getDesignationKey()); } public String getUserEvaluation(BugInstance b) { BugDesignation bd = getPrimaryDesignation(b); if (bd == null) return ""; String result = bd.getAnnotationText(); if (result == null) return ""; return result; } public long getUserTimestamp(BugInstance b) { BugDesignation bd = getPrimaryDesignation(b); if (bd == null) return Long.MAX_VALUE; return bd.getTimestamp(); } public long getFirstSeen(BugInstance b) { long firstVersion = b.getFirstVersion(); AppVersion v = getBugCollection().getAppVersionFromSequenceNumber(firstVersion); if (v == null) return getBugCollection().getTimestamp(); return v.getTimestamp(); } protected void updatedStatus() { for (CloudListener listener : listeners) listener.statusUpdated(); } public void updatedIssue(BugInstance bug) { for (CloudListener listener : listeners) listener.issueUpdated(bug); } protected void fireIssueDataDownloadedEvent() { for (CloudStatusListener statusListener : statusListeners) statusListener.handleIssueDataDownloadedEvent(); } public SigninState getSigninState() { return signinState; } @SuppressWarnings({"ThrowableInstanceNeverThrown"}) protected void setSigninState(SigninState state) { SigninState oldState = this.signinState; if (oldState == state) return; LOGGER.log(Level.FINER, "State " + oldState + " -> " + state, new Throwable()); this.signinState = state; for (CloudStatusListener statusListener : statusListeners) statusListener.handleStateChange(oldState, state); } public BugInstance getBugByHash(String hash) { for (BugInstance instance : bugCollection.getCollection()) { if (instance.getInstanceHash().equals(hash)) { return instance; } } return null; } protected NameLookup getUsernameLookup() throws IOException { NameLookup lookup; try { lookup = plugin.getUsernameClass().newInstance(); } catch (Exception e) { throw new RuntimeException("Unable to obtain username", e); } if (!lookup.signIn(plugin, bugCollection)) { throw new RuntimeException("Unable to obtain username"); } return lookup; } public void setStatusMsg(String newMsg) { this.statusMsg = newMsg; updatedStatus(); } private static void printLeaderBoard(PrintWriter w, Multiset<String> evaluations, int maxRows, String alwaysPrint, boolean listRank, String title) { if (listRank) w.printf("%3s %4s %s%n", "rnk", "num", title); else w.printf("%4s %s%n", "num", title); printLeaderBoard2(w, evaluations, maxRows, alwaysPrint, listRank ? "%3d %4d %s%n" : "%2$4d %3$s%n" , title); } protected String getCloudProperty(String propertyName) { return properties.getProperty("findbugs.cloud." + propertyName); } public boolean supportsSourceLinks() { return sourceFileLinkPattern != null; } @SuppressWarnings("boxing") public @CheckForNull URL getSourceLink(BugInstance b) { if (sourceFileLinkPattern == null) return null; SourceLineAnnotation src = b.getPrimarySourceLineAnnotation(); String fileName = src.getSourcePath(); int startLine = src.getStartLine(); java.util.regex.Matcher m = sourceFileLinkPattern.matcher(fileName); boolean isMatch = m.matches(); if (isMatch) try { URL link; if (startLine > 0) link = new URL(String.format(sourceFileLinkFormatWithLine, m.group(1), startLine, startLine - 10)); else link = new URL(String.format(sourceFileLinkFormat, m.group(1))); return link; } catch (Exception e) { AnalysisContext.logError("Error generating source link for " + src, e); } return null; } public String getSourceLinkToolTip(BugInstance b) { return sourceFileLinkToolTip; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getBugIsUnassigned(edu.umd.cs.findbugs.BugInstance) */ public boolean getBugIsUnassigned(BugInstance b) { return true; } /* (non-Javadoc) * @see edu.umd.cs.findbugs.cloud.Cloud#getWillNotBeFixed(edu.umd.cs.findbugs.BugInstance) */ public boolean getWillNotBeFixed(BugInstance b) { return false; } public Set<String> getReviewers(BugInstance b) { HashSet<String> result = new HashSet<String>(); for(BugDesignation d : getLatestDesignationFromEachUser(b)) result.add(d.getUser()); return result; } }
package com.github.andlyticsproject; import java.util.List; import android.app.Activity; import android.content.Context; import android.view.View; import android.widget.TextView; import com.github.andlyticsproject.chart.Chart; import com.github.andlyticsproject.chart.Chart.ValueCallbackHander; import com.github.andlyticsproject.model.AppStats; import com.github.andlyticsproject.util.Utils; public class RevenueChartListAdapter extends ChartListAdapter<AppStats> { private static final int COL_REVENUE = 1; private static final int COL_DEVELOPER_CUT = 2; public RevenueChartListAdapter(Activity activity) { super(activity); } @Override public int getNumPages() { return 1; } @Override public int getNumCharts(int page) throws IndexOutOfBoundsException { switch (page) { case 0: return 3; } throw new IndexOutOfBoundsException("page=" + page); } @Override public String getChartTitle(int page, int column) throws IndexOutOfBoundsException { if (column == COL_DATE) { return ""; } switch (page) { case 0: switch (column) { case COL_REVENUE: return activity.getString(R.string.total_revenue); case COL_DEVELOPER_CUT: return "Developer cut"; } } throw new IndexOutOfBoundsException("page=" + page + " column=" + column); } @Override public void updateChartValue(int position, int page, int column, TextView tv) throws IndexOutOfBoundsException { AppStats appInfo = getItem(position); if (column == COL_DATE) { tv.setText(dateFormat.format(appInfo.getDate())); return; } int textColor = BLACK_TEXT; switch (page) { case 0: { switch (column) { case COL_REVENUE: tv.setText(Utils.safeToString(appInfo.getTotalRevenue())); tv.setTextColor(textColor); return; case COL_DEVELOPER_CUT: if (appInfo.getTotalRevenue() == null) { tv.setText(""); } else { tv.setText(appInfo.getTotalRevenue().developerCutAsString()); } tv.setTextColor(textColor); return; } } } throw new IndexOutOfBoundsException("page=" + page + " column=" + column); } public View buildChart(Context context, Chart baseChart, List<?> statsForApp, int page, int column) throws IndexOutOfBoundsException { ValueCallbackHander handler = null; switch (page) { case 0: switch (column) { case COL_REVENUE: handler = new DevConValueCallbackHander() { @Override public double getValue(Object appInfo) { AppStats stats = (AppStats) appInfo; return stats.getTotalRevenue() == null ? 0 : stats.getTotalRevenue() .getAmount(); } }; return baseChart.buildLineChart(context, statsForApp.toArray(), handler); case COL_DEVELOPER_CUT: handler = new DevConValueCallbackHander() { @Override public double getValue(Object appInfo) { AppStats stats = (AppStats) appInfo; return stats.getTotalRevenue() == null ? 0 : stats.getTotalRevenue() .getDeveloperCut(); } }; return baseChart.buildLineChart(context, statsForApp.toArray(), handler); } } throw new IndexOutOfBoundsException("page=" + page + " column=" + column); } @Override public String getSubHeadLine(int page, int column) throws IndexOutOfBoundsException { if (column == COL_DATE) { return ""; } switch (page) { case 0: Preferences.saveShowChartHint(activity, false); if (overallStats == null) { return ""; } switch (column) { case COL_REVENUE: return overallStats.getTotalRevenue() == null ? "unknown" : overallStats .getTotalRevenue().asString(); case COL_DEVELOPER_CUT: return overallStats.getTotalRevenue() == null ? "unknown" : overallStats .getTotalRevenue().developerCutAsString(); } } throw new IndexOutOfBoundsException("page=" + page + " column=" + column); } @Override public AppStats getItem(int position) { return getStats().get(position); } @Override protected boolean isSmothValue(int page, int position) { return page == 0 ? getItem(position).isSmoothingApplied() : false; } }
package edu.umd.cs.findbugs.detect; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.regex.Pattern; import org.apache.bcel.Repository; import org.apache.bcel.classfile.Attribute; import org.apache.bcel.classfile.Code; import org.apache.bcel.classfile.ConstantValue; import org.apache.bcel.classfile.ElementValue; import org.apache.bcel.classfile.Field; import org.apache.bcel.classfile.JavaClass; import org.apache.bcel.classfile.Method; import org.apache.bcel.classfile.Signature; import org.apache.bcel.generic.ObjectType; import org.apache.bcel.generic.ReferenceType; import org.apache.bcel.generic.Type; import edu.umd.cs.findbugs.BugAccumulator; import edu.umd.cs.findbugs.BugInstance; import edu.umd.cs.findbugs.BugReporter; import edu.umd.cs.findbugs.DeepSubtypeAnalysis; import edu.umd.cs.findbugs.OpcodeStack; import edu.umd.cs.findbugs.ProgramPoint; import edu.umd.cs.findbugs.SourceLineAnnotation; import edu.umd.cs.findbugs.SystemProperties; import edu.umd.cs.findbugs.ba.AnalysisContext; import edu.umd.cs.findbugs.ba.XClass; import edu.umd.cs.findbugs.ba.XFactory; import edu.umd.cs.findbugs.ba.XField; import edu.umd.cs.findbugs.ba.ch.Subtypes2; import edu.umd.cs.findbugs.ba.generic.GenericObjectType; import edu.umd.cs.findbugs.ba.generic.GenericUtilities; import edu.umd.cs.findbugs.bcel.OpcodeStackDetector; import edu.umd.cs.findbugs.classfile.CheckedAnalysisException; import edu.umd.cs.findbugs.classfile.ClassDescriptor; import edu.umd.cs.findbugs.classfile.DescriptorFactory; import edu.umd.cs.findbugs.classfile.FieldDescriptor; import edu.umd.cs.findbugs.classfile.Global; import edu.umd.cs.findbugs.internalAnnotations.DottedClassName; import edu.umd.cs.findbugs.util.Bag; import edu.umd.cs.findbugs.util.ClassName; import edu.umd.cs.findbugs.util.MultiMap; import edu.umd.cs.findbugs.util.Util; import edu.umd.cs.findbugs.visitclass.PreorderVisitor; public class UnreadFields extends OpcodeStackDetector { private static final boolean DEBUG = SystemProperties.getBoolean("unreadfields.debug"); public boolean isContainerField(XField f) { return containerFields.contains(f); } Map<XField,Set<ProgramPoint> > assumedNonNull = new HashMap<XField,Set<ProgramPoint>>(); Map<XField,ProgramPoint > threadLocalAssignedInConstructor = new HashMap<XField,ProgramPoint>(); Set<XField> nullTested = new HashSet<XField>(); Set<XField> containerFields = new TreeSet<XField>(); MultiMap<XField,String> unknownAnnotation = new MultiMap<XField,String>(LinkedList.class); Set<String> abstractClasses = new HashSet<String>(); Set<String> hasNonAbstractSubClass = new HashSet<String>(); Set<String> classesScanned = new HashSet<String>(); Set<XField> fieldsOfNativeClasses = new HashSet<XField>(); Set<XField> reflectiveFields = new HashSet<XField>(); Set<XField> fieldsOfSerializableOrNativeClassed = new HashSet<XField>(); Set<XField> staticFieldsReadInThisMethod = new HashSet<XField>(); Set<XField> allMyFields = new TreeSet<XField>(); Set<XField> myFields = new TreeSet<XField>(); Set<XField> writtenFields = new HashSet<XField>(); /** * Only for fields that are either: * * read only * * written only * * written null and read */ Map<XField,SourceLineAnnotation> fieldAccess = new HashMap<XField, SourceLineAnnotation>(); Set<XField> writtenNonNullFields = new HashSet<XField>(); Set<String> calledFromConstructors = new HashSet<String>(); Set<XField> writtenInConstructorFields = new HashSet<XField>(); Set<XField> writtenInInitializationFields = new HashSet<XField>(); Set<XField> writtenOutsideOfInitializationFields = new HashSet<XField>(); Set<XField> readFields = new HashSet<XField>(); Set<XField> constantFields = new HashSet<XField>(); Set<String> needsOuterObjectInConstructor = new HashSet<String>(); Set<String> innerClassCannotBeStatic = new HashSet<String>(); boolean hasNativeMethods; boolean isSerializable; boolean sawSelfCallInConstructor; private final BugReporter bugReporter; private final BugAccumulator bugAccumulator; boolean publicOrProtectedConstructor; public Set<? extends XField> getReadFields() { return readFields; } public Set<? extends XField> getWrittenFields() { return writtenFields; } public boolean isWrittenOutsideOfInitialization(XField f) { return writtenOutsideOfInitializationFields.contains(f); } public boolean isWrittenDuringInitialization(XField f) { return writtenInInitializationFields.contains(f); } public boolean isWrittenInConstructor(XField f) { return writtenInConstructorFields.contains(f); } static final int doNotConsider = ACC_PUBLIC | ACC_PROTECTED; ClassDescriptor externalizable = DescriptorFactory.createClassDescriptor(java.io.Externalizable.class); ClassDescriptor serializable = DescriptorFactory.createClassDescriptor(java.io.Serializable.class); ClassDescriptor remote = DescriptorFactory.createClassDescriptor(java.rmi.Remote.class); public UnreadFields(BugReporter bugReporter) { this.bugReporter = bugReporter; this.bugAccumulator = new BugAccumulator(bugReporter); AnalysisContext context = AnalysisContext.currentAnalysisContext(); context.setUnreadFields(this); } @Override public void visit(JavaClass obj) { calledFromConstructors.clear(); hasNativeMethods = false; sawSelfCallInConstructor = false; publicOrProtectedConstructor = false; isSerializable = false; if (obj.isAbstract()) { abstractClasses.add(getDottedClassName()); } else { String superClass = obj.getSuperclassName(); if (superClass != null) hasNonAbstractSubClass.add(superClass); } classesScanned.add(getDottedClassName()); boolean superClassIsObject = "java.lang.Object".equals(obj.getSuperclassName()); if (getSuperclassName().indexOf("$") >= 0 || getSuperclassName().indexOf("+") >= 0 || withinAnonymousClass.matcher(getDottedClassName()).find()) { // System.out.println("hicfsc: " + betterClassName); innerClassCannotBeStatic.add(getDottedClassName()); // System.out.println("hicfsc: " + betterSuperclassName); innerClassCannotBeStatic.add(getDottedSuperclassName()); } // Does this class directly implement Serializable? String[] interface_names = obj.getInterfaceNames(); for (String interface_name : interface_names) { if (interface_name.equals("java.io.Externalizable")) { isSerializable = true; } else if (interface_name.equals("java.io.Serializable")) { isSerializable = true; break; } } // Does this class indirectly implement Serializable? if ((!superClassIsObject || interface_names.length > 0) && !isSerializable) { try { Subtypes2 subtypes2 = AnalysisContext.currentAnalysisContext().getSubtypes2(); ClassDescriptor desc = DescriptorFactory.createClassDescriptor(obj); if (subtypes2.getSubtypes(serializable).contains(desc) || subtypes2.getSubtypes(externalizable).contains(desc) || subtypes2.getSubtypes(remote).contains(desc)) { isSerializable = true; } } catch (ClassNotFoundException e) { bugReporter.reportMissingClass(e); } } // System.out.println(getDottedClassName() + " is serializable: " + isSerializable); super.visit(obj); } public static boolean classHasParameter(JavaClass obj) { for(Attribute a : obj.getAttributes()) if (a instanceof Signature) { String sig = ((Signature)a).getSignature(); return sig.charAt(0) == '<'; } return false; } @Override public void visitAfter(JavaClass obj) { if (hasNativeMethods) { fieldsOfSerializableOrNativeClassed.addAll(myFields); fieldsOfNativeClasses.addAll(myFields); } if (isSerializable) { fieldsOfSerializableOrNativeClassed.addAll(myFields); } if (sawSelfCallInConstructor) { myFields.removeAll(writtenInConstructorFields); writtenInInitializationFields.addAll(myFields); } myFields.clear(); allMyFields.clear(); calledFromConstructors.clear(); } @Override public void visit(Field obj) { super.visit(obj); XField f = XFactory.createXField(this); allMyFields.add(f); String signature = obj.getSignature(); int flags = obj.getAccessFlags(); if (!getFieldName().equals("serialVersionUID")) { myFields.add(f); if (obj.getName().equals("_jspx_dependants")) containerFields.add(f); } if (isSeleniumWebElement(signature)) containerFields.add(f); } /** * @param signature * @return */ public static boolean isSeleniumWebElement(String signature) { return signature.equals("Lorg/openqa/selenium/RenderedWebElement;") || signature.equals("Lorg/openqa/selenium/WebElement;"); } @Override public void visitAnnotation(String annotationClass, Map<String, ElementValue> map, boolean runtimeVisible) { if (!visitingField()) return; if (isInjectionAttribute(annotationClass)) { containerFields.add(XFactory.createXField(this)); } if (!annotationClass.startsWith("edu.umd.cs.findbugs") && !annotationClass.startsWith("javax.lang")) unknownAnnotation.add(XFactory.createXField(this), annotationClass); } public static boolean isInjectionAttribute(@DottedClassName String annotationClass) { if ( annotationClass.startsWith("javax.annotation.") || annotationClass.startsWith("javax.ejb") || annotationClass.equals("org.apache.tapestry5.annotations.Persist") || annotationClass.equals("org.jboss.seam.annotations.In") || annotationClass.startsWith("javax.persistence") || annotationClass.endsWith("SpringBean") || annotationClass.equals("com.google.inject.Inject") || annotationClass.startsWith("com.google.") && annotationClass.endsWith(".Bind") && annotationClass.hashCode() == -243168318 || annotationClass.startsWith("org.nuxeo.common.xmap.annotation") || annotationClass.startsWith("com.google.gwt.uibinder.client") || annotationClass.startsWith("org.springframework.beans.factory.annotation")) return true; int lastDot = annotationClass.lastIndexOf('.'); String lastPart = annotationClass.substring(lastDot+1); if (lastPart.startsWith("Inject")) return true; return false; } @Override public void visit(ConstantValue obj) { // ConstantValue is an attribute of a field, so the instance variables // set during visitation of the Field are still valid here XField f = XFactory.createXField(this); constantFields.add(f); } int count_aload_1; private int previousOpcode; private int previousPreviousOpcode; @Override public void visit(Code obj) { count_aload_1 = 0; previousOpcode = -1; previousPreviousOpcode = -1; nullTested.clear(); seenInvokeStatic = false; seenMonitorEnter = getMethod().isSynchronized(); staticFieldsReadInThisMethod.clear(); super.visit(obj); if (getMethodName().equals("<init>") && count_aload_1 > 1 && (getClassName().indexOf('$') >= 0 || getClassName().indexOf('+') >= 0)) { needsOuterObjectInConstructor.add(getDottedClassName()); // System.out.println(betterClassName + " needs outer object in constructor"); } bugAccumulator.reportAccumulatedBugs(); } @Override public void visit(Method obj) { if (DEBUG) System.out.println("Checking " + getClassName() + "." + obj.getName()); if (getMethodName().equals("<init>") && (obj.isPublic() || obj.isProtected() )) publicOrProtectedConstructor = true; pendingGetField = null; saState = 0; super.visit(obj); int flags = obj.getAccessFlags(); if ((flags & ACC_NATIVE) != 0) hasNativeMethods = true; } boolean seenInvokeStatic; boolean seenMonitorEnter; XField pendingGetField; int saState = 0; @Override public void sawOpcode(int seen) { if (DEBUG) System.out.println(getPC() + ": " + OPCODE_NAMES[seen] + " " + saState); if (seen == MONITORENTER) seenMonitorEnter = true; switch(saState) { case 0: if (seen == ALOAD_0) saState = 1; break; case 1: if (seen == ALOAD_0) saState = 2; else saState = 0; break; case 2: if (seen == GETFIELD) saState = 3; else saState = 0; break; case 3: if (seen == PUTFIELD) saState = 4; else saState = 0; break; } boolean selfAssignment = false; if (pendingGetField != null) { if (seen != PUTFIELD && seen != PUTSTATIC) readFields.add(pendingGetField); else if ( XFactory.createReferencedXField(this).equals(pendingGetField) && (saState == 4 || seen == PUTSTATIC) ) selfAssignment = true; else readFields.add(pendingGetField); pendingGetField = null; } if (saState == 4) saState = 0; if (seen == INVOKESTATIC && getClassConstantOperand().equals("java/util/concurrent/atomic/AtomicReferenceFieldUpdater") && getNameConstantOperand().equals("newUpdater")) { String fieldName = (String) stack.getStackItem(0).getConstant(); String fieldSignature = (String) stack.getStackItem(1).getConstant(); String fieldClass = (String) stack.getStackItem(2).getConstant(); if (fieldName != null && fieldSignature != null && fieldClass != null) { XField f = XFactory.createXField(fieldClass.replace('/','.'), fieldName, ClassName.toSignature(fieldSignature), false); reflectiveFields.add(f); } } if (seen == INVOKESTATIC && getClassConstantOperand().equals("java/util/concurrent/atomic/AtomicIntegerFieldUpdater") && getNameConstantOperand().equals("newUpdater")) { String fieldName = (String) stack.getStackItem(0).getConstant(); String fieldClass = (String) stack.getStackItem(1).getConstant(); if (fieldName != null && fieldClass != null) { XField f = XFactory.createXField(fieldClass.replace('/','.'), fieldName, "I", false); reflectiveFields.add(f); } } if (seen == INVOKESTATIC && getClassConstantOperand().equals("java/util/concurrent/atomic/AtomicLongFieldUpdater") && getNameConstantOperand().equals("newUpdater")) { String fieldName = (String) stack.getStackItem(0).getConstant(); String fieldClass = (String) stack.getStackItem(1).getConstant(); if (fieldName != null && fieldClass != null) { XField f = XFactory.createXField(fieldClass.replace('/','.'), fieldName, "J", false); reflectiveFields.add(f); } } if (seen == GETSTATIC) { XField f = XFactory.createReferencedXField(this); staticFieldsReadInThisMethod.add(f); } else if (seen == INVOKESTATIC) { seenInvokeStatic = true; } else if (seen == PUTSTATIC && !getMethod().isStatic()) { XField f = XFactory.createReferencedXField(this); if (f.getName().indexOf("class$") != 0) { int priority = LOW_PRIORITY; if (!publicOrProtectedConstructor) priority if (seenMonitorEnter) priority++; if (!seenInvokeStatic && staticFieldsReadInThisMethod.isEmpty()) priority if (getThisClass().isPublic() && getMethod().isPublic()) priority if (getThisClass().isPrivate() || getMethod().isPrivate()) priority++; if (getClassName().indexOf('$') != -1 || getMethod().isSynthetic() || f.isSynthetic() || f.getName().indexOf('$') >= 0) priority++; // Decrease priority for boolean fileds used to control debug/test settings if(f.getName().indexOf("DEBUG") >= 0 || f.getName().indexOf("VERBOSE") >= 0 && f.getSignature().equals("Z")){ priority ++; priority ++; } // Eclipse bundles which implements start/stop *very* often assigns static instances there if (getMethodName().equals("start") || getMethodName().equals("stop") && getMethodSig().equals("(Lorg/osgi/framework/BundleContext;)V")) { try { JavaClass bundleClass = Repository.lookupClass("org.osgi.framework.BundleActivator"); if(getThisClass().instanceOf(bundleClass)){ priority ++; } if(f.isReferenceType()){ FieldDescriptor fieldInfo = f.getFieldDescriptor(); String dottedClass = DeepSubtypeAnalysis.getComponentClass(fieldInfo.getSignature()); JavaClass fieldClass = Repository.lookupClass(dottedClass); if(fieldClass != null && fieldClass.instanceOf(bundleClass)){ // the code "plugin = this;" unfortunately exists in the // template for new Eclipse plugin classes, so nearly every one // plugin has this pattern => decrease to very low prio priority ++; } } } catch (ClassNotFoundException e) { bugReporter.reportMissingClass(e); } } bugAccumulator.accumulateBug( new BugInstance(this, "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD", priority) .addClassAndMethod(this) .addField(f), this); } } if (seen == INVOKEVIRTUAL || seen == INVOKEINTERFACE || seen == INVOKESPECIAL || seen==INVOKESTATIC ) { String sig = getSigConstantOperand(); String invokedClassName = getClassConstantOperand(); if (invokedClassName.equals(getClassName()) && (getMethodName().equals("<init>") || getMethodName().equals("<clinit>"))) { calledFromConstructors.add(getNameConstantOperand()+":"+sig); } int pos = PreorderVisitor.getNumberArguments(sig); if (stack.getStackDepth() > pos) { OpcodeStack.Item item = stack.getStackItem(pos); boolean superCall = seen == INVOKESPECIAL && !invokedClassName .equals(getClassName()); if (DEBUG) System.out.println("In " + getFullyQualifiedMethodName() + " saw call on " + item); boolean selfCall = item.getRegisterNumber() == 0 && !superCall; if (selfCall && getMethodName().equals("<init>")) { sawSelfCallInConstructor = true; if (DEBUG) System.out.println("Saw self call in " + getFullyQualifiedMethodName() + " to " + invokedClassName + "." + getNameConstantOperand() ); } } } if ((seen == IFNULL || seen == IFNONNULL) && stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); XField f = item.getXField(); if (f != null) { nullTested.add(f); if (DEBUG) System.out.println(f + " null checked in " + getFullyQualifiedMethodName()); } } if ((seen == IF_ACMPEQ || seen == IF_ACMPNE) && stack.getStackDepth() >= 2) { OpcodeStack.Item item0 = stack.getStackItem(0); OpcodeStack.Item item1 = stack.getStackItem(1); XField field1 = item1.getXField(); if (item0.isNull() && field1 != null) nullTested.add(field1); else { XField field0 = item0.getXField(); if (item1.isNull() && field0 != null) nullTested.add(field0); } } if (seen == GETFIELD || seen == INVOKEVIRTUAL || seen == INVOKEINTERFACE || seen == INVOKESPECIAL || seen == PUTFIELD || seen == IALOAD || seen == AALOAD || seen == BALOAD || seen == CALOAD || seen == SALOAD || seen == IASTORE || seen == AASTORE || seen == BASTORE || seen == CASTORE || seen == SASTORE || seen == ARRAYLENGTH) { int pos = 0; switch(seen) { case ARRAYLENGTH: case GETFIELD : pos = 0; break; case INVOKEVIRTUAL : case INVOKEINTERFACE: case INVOKESPECIAL: String sig = getSigConstantOperand(); pos = PreorderVisitor.getNumberArguments(sig); break; case PUTFIELD : case IALOAD : case AALOAD: case BALOAD: case CALOAD: case SALOAD: pos = 1; break; case IASTORE : case AASTORE: case BASTORE: case CASTORE: case SASTORE: pos = 2; break; default: throw new RuntimeException("Impossible"); } if (stack.getStackDepth() >= pos) { OpcodeStack.Item item = stack.getStackItem(pos); XField f = item.getXField(); if (DEBUG) System.out.println("RRR: " + f + " " + nullTested.contains(f) + " " + writtenInConstructorFields.contains(f) + " " + writtenNonNullFields.contains(f)); if (f != null && !nullTested.contains(f) && ! ((writtenInConstructorFields.contains(f) || writtenInInitializationFields.contains(f)) && writtenNonNullFields.contains(f)) ) { ProgramPoint p = new ProgramPoint(this); Set <ProgramPoint> s = assumedNonNull.get(f); if (s == null) s = Collections.singleton(p); else s = Util.addTo(s, p); assumedNonNull.put(f,s); if (DEBUG) System.out.println(f + " assumed non-null in " + getFullyQualifiedMethodName()); } } } if (seen == ALOAD_1) { count_aload_1++; } else if (seen == GETFIELD || seen == GETSTATIC) { XField f = XFactory.createReferencedXField(this); pendingGetField = f; if (getMethodName().equals("readResolve") && seen == GETFIELD ) { writtenFields.add(f); writtenNonNullFields.add(f); } if (DEBUG) System.out.println("get: " + f); if (writtenFields.contains(f)) fieldAccess.remove(f); else if (!fieldAccess.containsKey(f)) fieldAccess.put(f, SourceLineAnnotation.fromVisitedInstruction(this)); } else if ((seen == PUTFIELD || seen == PUTSTATIC) && !selfAssignment) { XField f = XFactory.createReferencedXField(this); OpcodeStack.Item item = null; if (stack.getStackDepth() > 0) { item = stack.getStackItem(0); if (!item.isNull()) nullTested.add(f); } writtenFields.add(f); boolean writtingNonNull = previousOpcode != ACONST_NULL || previousPreviousOpcode == GOTO; if (writtingNonNull) { writtenNonNullFields.add(f); if (DEBUG) System.out.println("put nn: " + f); } else if (DEBUG) System.out.println("put: " + f); if (writtingNonNull && readFields.contains(f)) fieldAccess.remove(f); else if (!fieldAccess.containsKey(f)) fieldAccess.put(f, SourceLineAnnotation.fromVisitedInstruction(this)); boolean isConstructor = getMethodName().equals("<init>") || getMethodName().equals("<clinit>"); if (getMethod().isStatic() == f.isStatic() && (isConstructor || calledFromConstructors.contains(getMethodName() + ":" + getMethodSig()) || getMethodName().equals("init") || getMethodName().equals("init") || getMethodName().equals("initialize") || getMethod().isPrivate())) { if (isConstructor) { writtenInConstructorFields.add(f); if (f.getSignature().equals("Ljava/lang/ThreadLocal;") && item != null && item.isNewlyAllocated()) threadLocalAssignedInConstructor.put(f, new ProgramPoint(this)); } else writtenInInitializationFields.add(f); if (writtingNonNull) assumedNonNull.remove(f); } else { writtenOutsideOfInitializationFields.add(f); } } previousPreviousOpcode = previousOpcode; previousOpcode = seen; } public boolean isReflexive(XField f) { return reflectiveFields.contains(f); } static Pattern dontComplainAbout = Pattern.compile("class[$]"); static Pattern withinAnonymousClass = Pattern.compile("[$][0-9].*[$]"); @Override public void report() { Set<String> fieldNamesSet = new HashSet<String>(); for(XField f : writtenNonNullFields) fieldNamesSet.add(f.getName()); if (DEBUG) { System.out.println("read fields:" ); for(XField f : readFields) System.out.println(" " + f); if (!containerFields.isEmpty()) { System.out.println("ejb3 fields:" ); for(XField f : containerFields) System.out.println(" " + f); } if (!reflectiveFields.isEmpty()) { System.out.println("reflective fields:" ); for(XField f : reflectiveFields) System.out.println(" " + f); } System.out.println("written fields:" ); for (XField f : writtenFields) System.out.println(" " + f); System.out.println("written nonnull fields:" ); for (XField f : writtenNonNullFields) System.out.println(" " + f); System.out.println("assumed nonnull fields:" ); for (XField f : assumedNonNull.keySet()) System.out.println(" " + f); } Set<XField> declaredFields = new HashSet<XField>(); AnalysisContext currentAnalysisContext = AnalysisContext.currentAnalysisContext(); XFactory xFactory = AnalysisContext.currentXFactory(); for(XField f : AnalysisContext.currentXFactory().allFields()) { ClassDescriptor classDescriptor = f.getClassDescriptor(); if (currentAnalysisContext.isApplicationClass(classDescriptor) && !currentAnalysisContext.isTooBig(classDescriptor) && !xFactory.isReflectiveClass(classDescriptor) ) declaredFields.add(f); } // Don't report anything about ejb3Fields HashSet<XField> unknownAnotationAndUnwritten = new HashSet<XField>(unknownAnnotation.keySet()); unknownAnotationAndUnwritten.removeAll(writtenFields); declaredFields.removeAll(unknownAnotationAndUnwritten); declaredFields.removeAll(containerFields); declaredFields.removeAll(reflectiveFields); for(Iterator<XField> i = declaredFields.iterator(); i.hasNext(); ) { XField f = i.next(); if (f.isSynthetic() && !f.getName().startsWith("this$") || f.getName().startsWith("_")) i.remove(); } TreeSet<XField> notInitializedInConstructors = new TreeSet<XField>(declaredFields); notInitializedInConstructors.retainAll(readFields); notInitializedInConstructors.retainAll(writtenFields); notInitializedInConstructors.retainAll(assumedNonNull.keySet()); notInitializedInConstructors.removeAll(writtenInConstructorFields); notInitializedInConstructors.removeAll(writtenInInitializationFields); for(Iterator<XField> i = notInitializedInConstructors.iterator(); i.hasNext(); ) { if (i.next().isStatic()) i.remove(); } TreeSet<XField> readOnlyFields = new TreeSet<XField>(declaredFields); readOnlyFields.removeAll(writtenFields); readOnlyFields.retainAll(readFields); TreeSet<XField> nullOnlyFields = new TreeSet<XField>(declaredFields); nullOnlyFields.removeAll(writtenNonNullFields); nullOnlyFields.retainAll(readFields); Set<XField> writeOnlyFields = declaredFields; writeOnlyFields.removeAll(readFields); Map<String, Integer> count = new HashMap<String, Integer>(); Bag<String> nullOnlyFieldNames = new Bag<String>(); Bag<ClassDescriptor> classContainingNullOnlyFields = new Bag<ClassDescriptor>(); for (XField f : nullOnlyFields) { nullOnlyFieldNames.add(f.getName()); classContainingNullOnlyFields.add(f.getClassDescriptor()); int increment = 3; Collection<ProgramPoint> assumedNonNullAt = assumedNonNull.get(f); if (assumedNonNullAt != null) increment += assumedNonNullAt.size(); for(String s : unknownAnnotation.get(f)) { Integer value = count.get(s); if (value == null) count.put(s,increment); else count.put(s,value+increment); } } Map<XField, Integer> maxCount = new HashMap<XField, Integer>(); LinkedList<XField> assumeReflective = new LinkedList<XField>(); for (XField f : nullOnlyFields) { int myMaxCount = 0; for(String s : unknownAnnotation.get(f)) { Integer value = count.get(s); if (value != null && myMaxCount < value) myMaxCount = value; } if (myMaxCount > 0) maxCount.put(f, myMaxCount); if (myMaxCount > 15) assumeReflective.add(f); else if (nullOnlyFieldNames.getCount(f.getName()) > 8) assumeReflective.add(f); else if (classContainingNullOnlyFields.getCount(f.getClassDescriptor()) > 4) assumeReflective.add(f); else if (classContainingNullOnlyFields.getCount(f.getClassDescriptor()) > 2 && f.getName().length() == 1) assumeReflective.add(f); } readOnlyFields.removeAll(assumeReflective); nullOnlyFields.removeAll(assumeReflective); notInitializedInConstructors.removeAll(assumeReflective); for (XField f : notInitializedInConstructors) { String fieldName = f.getName(); String className = f.getClassName(); String fieldSignature = f.getSignature(); if (f.isResolved() && !fieldsOfNativeClasses.contains(f) && (fieldSignature.charAt(0) == 'L' || fieldSignature.charAt(0) == '[') ) { int priority = LOW_PRIORITY; if (assumedNonNull.containsKey(f)) bugReporter.reportBug(new BugInstance(this, "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", priority) .addClass(className) .addField(f)); } } for (XField f : readOnlyFields) { String fieldName = f.getName(); String className = f.getClassName(); String fieldSignature = f.getSignature(); if (f.isResolved() && !fieldsOfNativeClasses.contains(f)) { int priority = NORMAL_PRIORITY; if (!(fieldSignature.charAt(0) == 'L' || fieldSignature.charAt(0) == '[')) priority++; if (maxCount.containsKey(f)) priority++; String pattern = "UWF_UNWRITTEN_FIELD"; if (f.isProtected() || f.isPublic()) pattern = "UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD"; bugReporter.reportBug(addClassFieldAndAccess(new BugInstance(this, pattern, priority),f)); } } for (XField f : nullOnlyFields) { String fieldName = f.getName(); String className = f.getClassName(); String fieldSignature = f.getSignature(); if (DEBUG) { System.out.println("Null only: " + f); System.out.println(" : " + assumedNonNull.containsKey(f)); System.out.println(" : " + fieldsOfSerializableOrNativeClassed.contains(f)); System.out.println(" : " + fieldNamesSet.contains(f.getName())); System.out.println(" : " + abstractClasses.contains(f.getClassName())); System.out.println(" : " + hasNonAbstractSubClass.contains(f.getClassName())); System.out.println(" : " + f.isResolved()); } if (!f.isResolved()) continue; if (fieldsOfNativeClasses.contains(f)) continue; if (DEBUG) { System.out.println("Ready to report"); } int priority = NORMAL_PRIORITY; if (maxCount.containsKey(f)) priority++; if (abstractClasses.contains(f.getClassName())) { priority++; if (! hasNonAbstractSubClass.contains(f.getClassName())) priority++; } // if (fieldNamesSet.contains(f.getName())) priority++; if (assumedNonNull.containsKey(f)) { int npPriority = priority; Set<ProgramPoint> assumedNonNullAt = assumedNonNull.get(f); if (assumedNonNullAt.size() > 14) { npPriority+=2; } else if (assumedNonNullAt.size() > 6) { npPriority++; } else { priority } String pattern = (f.isPublic() || f.isProtected()) ? "NP_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD" : "NP_UNWRITTEN_FIELD"; for (ProgramPoint p : assumedNonNullAt) bugAccumulator.accumulateBug(new BugInstance(this, pattern, npPriority) .addClassAndMethod(p.method) .addField(f), p.getSourceLineAnnotation()); } else { if (f.isStatic()) priority++; if (f.isFinal()) priority++; if (fieldsOfSerializableOrNativeClassed.contains(f)) priority++; } if (!readOnlyFields.contains(f)) bugReporter.reportBug( addClassFieldAndAccess(new BugInstance(this,"UWF_NULL_FIELD",priority), f).lowerPriorityIfDeprecated() ); } for (XField f : writeOnlyFields) { String fieldName = f.getName(); String className = f.getClassName(); int lastDollar = Math.max(className.lastIndexOf('$'), className.lastIndexOf('+')); boolean isAnonymousInnerClass = (lastDollar > 0) && (lastDollar < className.length() - 1) && Character.isDigit(className.charAt(lastDollar+1)); if (DEBUG) { System.out.println("Checking write only field " + className + "." + fieldName + "\t" + constantFields.contains(f) + "\t" + f.isStatic() ); } if (!f.isResolved()) continue; if (dontComplainAbout.matcher(fieldName).find()) continue; if (lastDollar >= 0 && (fieldName.startsWith("this$") || fieldName.startsWith("this+"))) { String outerClassName = className.substring(0, lastDollar); try { JavaClass outerClass = Repository.lookupClass(outerClassName); if (classHasParameter(outerClass)) continue; ClassDescriptor cDesc = DescriptorFactory.createClassDescriptorFromDottedClassName(outerClassName); XClass outerXClass = Global.getAnalysisCache().getClassAnalysis(XClass.class, cDesc); XClass thisClass = Global.getAnalysisCache().getClassAnalysis(XClass.class, f.getClassDescriptor()); AnalysisContext analysisContext = AnalysisContext.currentAnalysisContext(); Subtypes2 subtypes2 = analysisContext.getSubtypes2(); for (XField of : outerXClass.getXFields()) if (!of.isStatic()) { String sourceSignature = of.getSourceSignature(); if (sourceSignature != null && of.getSignature().equals("Ljava/lang/ThreadLocal;")) { Type ofType = GenericUtilities.getType(sourceSignature); if (ofType instanceof GenericObjectType) { GenericObjectType gType = (GenericObjectType) ofType; for (ReferenceType r : gType.getParameters()) { if (r instanceof ObjectType) { ClassDescriptor c = DescriptorFactory.getClassDescriptor((ObjectType) r); if (subtypes2.isSubtype(f.getClassDescriptor(), c)) { ProgramPoint p = threadLocalAssignedInConstructor.get(of); int priority = p == null ? NORMAL_PRIORITY : HIGH_PRIORITY; BugInstance bug = new BugInstance(this, "SIC_THREADLOCAL_DEADLY_EMBRACE", priority) .addClass(className).addField(of); if (p != null) bug.addMethod(p.method).add(p.getSourceLineAnnotation()); bugReporter.reportBug(bug); } } } } } } boolean outerClassIsInnerClass = false; for (Field field : outerClass.getFields()) if (field.getName().equals("this$0")) outerClassIsInnerClass = true; if (outerClassIsInnerClass) continue; } catch (ClassNotFoundException e) { bugReporter.reportMissingClass(e); } catch (CheckedAnalysisException e) { bugReporter.logError("Error getting outer XClass for " + outerClassName, e); } if (!innerClassCannotBeStatic.contains(className)) { boolean easyChange = !needsOuterObjectInConstructor.contains(className); if (easyChange || !isAnonymousInnerClass) { // easyChange isAnonymousInnerClass // true false medium, SIC // true true low, SIC_ANON // false true not reported // false false low, SIC_THIS int priority = LOW_PRIORITY; if (easyChange && !isAnonymousInnerClass) priority = NORMAL_PRIORITY; String bug = "SIC_INNER_SHOULD_BE_STATIC"; if (isAnonymousInnerClass) bug = "SIC_INNER_SHOULD_BE_STATIC_ANON"; else if (!easyChange) bug = "SIC_INNER_SHOULD_BE_STATIC_NEEDS_THIS"; bugReporter.reportBug(new BugInstance(this, bug, priority) .addClass(className)); } } } else if (f.isResolved() ){ if (constantFields.contains(f)) { if (!f.isStatic()) bugReporter.reportBug(addClassFieldAndAccess(new BugInstance(this, "SS_SHOULD_BE_STATIC", NORMAL_PRIORITY), f)); } else if (fieldsOfSerializableOrNativeClassed.contains(f)) { // ignore it } else if (!writtenFields.contains(f)) bugReporter.reportBug(new BugInstance(this,( f.isPublic() || f.isProtected())? "UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD" : "UUF_UNUSED_FIELD", NORMAL_PRIORITY) .addClass(className) .addField(f).lowerPriorityIfDeprecated()); else if (f.getName().toLowerCase().indexOf("guardian") < 0) { int priority = NORMAL_PRIORITY; if (f.isStatic()) priority++; if (f.isFinal()) priority++; bugReporter.reportBug(addClassFieldAndAccess(new BugInstance(this, ( f.isPublic() || f.isProtected())? "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD" : "URF_UNREAD_FIELD", priority),f)); } } } bugAccumulator.reportAccumulatedBugs(); } /** * @param instance * @return */ private BugInstance addClassFieldAndAccess(BugInstance instance, XField f) { if (writtenNonNullFields.contains(f) && readFields.contains(f)) throw new IllegalArgumentException("No information for fields that are both read and written nonnull"); instance.addClass(f.getClassName()).addField(f); if (fieldAccess.containsKey(f)) instance.add(fieldAccess.get(f)); return instance; } }
package org.realityforge.arez; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.jetbrains.annotations.TestOnly; /** * Support class to provide access to instances of ArezContext. * The {@link ContextProvider} that is bound to this class will determine how this * achieved but it may involve using Zones (in a JavaScript runtime) or ThreadLocals * (on the JVM). The default implementation provides a singleton Context. * * <p>This class is not used by any of the tools in Core but provides support for * downstream tools such as the models annotated with annotations in the * org.realityforge.arez.annotations package and generated by the annotation processor * in the org.realityforge.arez.processor package.</p> */ @Unsupported( "This is still a work in progress and may be removed in the future" ) public final class Arez { /** * The provider that used to access context. */ private static ContextProvider c_provider; private Arez() { } /** * Interface for supplying an instance of an ArezContext to the caller. */ @FunctionalInterface public interface ContextProvider { /** * Return a ArezContext based on the providers particular strategy. * * @return the ArezContext. */ @Nonnull ArezContext context(); } /** * Return the ArezContext from the provider. * * @return the ArezContext. */ @Nonnull public static ArezContext context() { return getContextProvider().context(); } /** * Bind a ContextProvider to Arez. * This method should not be called if a provider has already been bound * or the method {@link #context()} has already been called (and created * the default provider). * * @param provider the ContextProvider to bind. */ public static void bindProvider( @Nonnull final ContextProvider provider ) { Guards.invariant( () -> null == c_provider, () -> "Attempting to bind ContextProvider " + provider + " but there is already a " + "provider bound as " + c_provider + "." ); c_provider = provider; } /** * Return the ContextProvider creating the default provider if necessary. * * @return the ContextProvider. */ @Nonnull synchronized static ContextProvider getContextProvider() { if ( null == c_provider ) { c_provider = new StaticContextProvider(); } return c_provider; } @TestOnly static void setProvider( @Nullable final ContextProvider provider ) { c_provider = provider; } /** * Default implementation of context provider that just returns a singleton context. */ static final class StaticContextProvider implements ContextProvider { private final ArezContext _context = new ArezContext(); /** * {@inheritDoc} */ @Nonnull public ArezContext context() { return _context; } } }
package com.jayantkrish.jklol.ccg.supertag; import java.io.Serializable; import java.util.Collection; import java.util.List; import java.util.Set; import joptsimple.OptionParser; import joptsimple.OptionSet; import joptsimple.OptionSpec; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.jayantkrish.jklol.ccg.CcgExample; import com.jayantkrish.jklol.ccg.HeadedSyntacticCategory; import com.jayantkrish.jklol.ccg.SyntacticCategory; import com.jayantkrish.jklol.cli.AbstractCli; import com.jayantkrish.jklol.cli.TrainCcg; import com.jayantkrish.jklol.models.parametric.ParametricFactorGraph; import com.jayantkrish.jklol.pos.WordPrefixSuffixFeatureGenerator; import com.jayantkrish.jklol.preprocessing.DictionaryFeatureVectorGenerator; import com.jayantkrish.jklol.preprocessing.FeatureGenerator; import com.jayantkrish.jklol.preprocessing.FeatureGenerators; import com.jayantkrish.jklol.preprocessing.FeatureVectorGenerator; import com.jayantkrish.jklol.sequence.ConvertingLocalContext; import com.jayantkrish.jklol.sequence.FactorGraphSequenceTagger; import com.jayantkrish.jklol.sequence.ListTaggedSequence; import com.jayantkrish.jklol.sequence.LocalContext; import com.jayantkrish.jklol.sequence.TaggedSequence; import com.jayantkrish.jklol.sequence.TaggerUtils; import com.jayantkrish.jklol.training.GradientOptimizer; import com.jayantkrish.jklol.util.CountAccumulator; import com.jayantkrish.jklol.util.IndexedList; import com.jayantkrish.jklol.util.IoUtils; /** * Trains a CCG supertagger. The supertagger takes as input a * POS-tagged sentence, and predicts a sequence of CCG syntactic * categories. * * @author jayantk */ public class TrainSupertagger extends AbstractCli { private OptionSpec<String> trainingFilename; private OptionSpec<String> modelOutput; private OptionSpec<String> syntaxMap; // Model construction options. private OptionSpec<Void> noTransitions; private OptionSpec<Void> maxMargin; private OptionSpec<Integer> commonWordCountThreshold; private OptionSpec<Integer> prefixSuffixFeatureCountThreshold; public TrainSupertagger() { super(CommonOptions.STOCHASTIC_GRADIENT, CommonOptions.LBFGS, CommonOptions.MAP_REDUCE); } @Override public void initializeOptions(OptionParser parser) { trainingFilename = parser.accepts("training").withRequiredArg() .ofType(String.class).required(); modelOutput = parser.accepts("output").withRequiredArg().ofType(String.class).required(); syntaxMap = parser.accepts("syntaxMap").withRequiredArg().ofType(String.class); noTransitions = parser.accepts("noTransitions"); maxMargin = parser.accepts("maxMargin"); commonWordCountThreshold = parser.accepts("commonWordThreshold").withRequiredArg() .ofType(Integer.class).defaultsTo(5); prefixSuffixFeatureCountThreshold = parser.accepts("commonWordThreshold").withRequiredArg() .ofType(Integer.class).defaultsTo(35); } @Override public void run(OptionSet options) { // Read in the training data as sentences, to use for // feature generation. System.out.println("Reading training data..."); List<CcgExample> ccgExamples = TrainCcg.readTrainingData(options.valueOf(trainingFilename), true, true, options.valueOf(syntaxMap)); System.out.println("Reformatting training data..."); List<TaggedSequence<WordAndPos, HeadedSyntacticCategory>> trainingData = reformatTrainingExamples(ccgExamples, true); System.out.println("Generating features..."); FeatureVectorGenerator<LocalContext<WordAndPos>> featureGen = buildFeatureVectorGenerator(trainingData, options.valueOf(commonWordCountThreshold), options.valueOf(prefixSuffixFeatureCountThreshold)); Set<HeadedSyntacticCategory> validCategories = Sets.newHashSet(); for (TaggedSequence<WordAndPos, HeadedSyntacticCategory> trainingDatum : trainingData) { validCategories.addAll(trainingDatum.getLabels()); } System.out.println(validCategories.size() + " CCG categories"); System.out.println(featureGen.getNumberOfFeatures() + " word/CCG category features"); // Build the factor graph. ParametricFactorGraph sequenceModelFamily = TaggerUtils.buildFeaturizedSequenceModel( validCategories, featureGen.getFeatureDictionary(), options.has(noTransitions)); GradientOptimizer trainer = createGradientOptimizer(trainingData.size()); FactorGraphSequenceTagger<WordAndPos, HeadedSyntacticCategory> tagger = TaggerUtils.trainSequenceModel( sequenceModelFamily, trainingData, HeadedSyntacticCategory.class, featureGen, trainer, options.has(maxMargin)); // Save model to disk. System.out.println("Serializing trained model..."); FactorGraphSupertagger supertagger = new FactorGraphSupertagger(tagger.getModelFamily(), tagger.getParameters(), tagger.getInstantiatedModel(), tagger.getFeatureGenerator()); IoUtils.serializeObjectToFile(supertagger, options.valueOf(modelOutput)); } /** * Converts {@code ccgExamples} into word sequences tagged with * syntactic categories. * * @param ccgExamples * @return */ public static List<TaggedSequence<WordAndPos, HeadedSyntacticCategory>> reformatTrainingExamples( Collection<CcgExample> ccgExamples, boolean ignoreInvalid) { List<TaggedSequence<WordAndPos, HeadedSyntacticCategory>> examples = Lists.newArrayList(); for (CcgExample example : ccgExamples) { Preconditions.checkArgument(example.hasSyntacticParse()); List<WordAndPos> taggedWords = WordAndPos.createExample(example.getWords(), example.getPosTags()); List<HeadedSyntacticCategory> syntacticCategories = example.getSyntacticParse().getAllSpannedHeadedSyntacticCategories(); if (!ignoreInvalid || !syntacticCategories.contains(null)) { examples.add(new ListTaggedSequence<WordAndPos, HeadedSyntacticCategory>(taggedWords, syntacticCategories)); } else { List<SyntacticCategory> unheadedCategories = example.getSyntacticParse().getAllSpannedLexiconEntries(); System.out.println("Discarding sentence: " + taggedWords); for (int i = 0; i < taggedWords.size(); i++) { if (syntacticCategories.get(i) == null) { System.out.println("No headed syntactic category for: " + taggedWords.get(i) + " " + unheadedCategories.get(i)); } } } } return examples; } private static FeatureVectorGenerator<LocalContext<WordAndPos>> buildFeatureVectorGenerator( List<TaggedSequence<WordAndPos, HeadedSyntacticCategory>> trainingData, int commonWordCountThreshold, int prefixSuffixCountThreshold) { List<LocalContext<WordAndPos>> contexts = TaggerUtils.extractContextsFromData(trainingData); CountAccumulator<String> wordCounts = CountAccumulator.create(); for (LocalContext<WordAndPos> context : contexts) { wordCounts.increment(context.getItem().getWord(), 1.0); } Set<String> commonWords = Sets.newHashSet(wordCounts.getKeysAboveCountThreshold( commonWordCountThreshold)); // Build a dictionary of words and POS tags which occur frequently // enough in the data set. FeatureGenerator<LocalContext<WordAndPos>, String> wordGen = new WordAndPosContextFeatureGenerator(new int[] { -2, -1, 0, 1, 2 }, commonWords); CountAccumulator<String> wordPosFeatureCounts = FeatureGenerators.getFeatureCounts(wordGen, contexts); // Generate prefix/suffix features for common prefixes and suffixes. FeatureGenerator<LocalContext<WordAndPos>, String> prefixGen = FeatureGenerators.convertingFeatureGenerator(new WordPrefixSuffixFeatureGenerator(4, 4, commonWords), new WordAndPosContextToWordContext()); // Count feature occurrences and discard infrequent features. CountAccumulator<String> prefixFeatureCounts = FeatureGenerators.getFeatureCounts(prefixGen, contexts); IndexedList<String> featureDictionary = IndexedList.create(); Set<String> frequentWordFeatures = wordPosFeatureCounts.getKeysAboveCountThreshold(commonWordCountThreshold); Set<String> frequentPrefixFeatures = prefixFeatureCounts.getKeysAboveCountThreshold(prefixSuffixCountThreshold); featureDictionary.addAll(frequentWordFeatures); featureDictionary.addAll(frequentPrefixFeatures); System.out.println(frequentWordFeatures.size() + " word and POS features"); System.out.println(frequentPrefixFeatures.size() + " prefix/suffix features"); @SuppressWarnings("unchecked") FeatureGenerator<LocalContext<WordAndPos>, String> featureGen = FeatureGenerators .combinedFeatureGenerator(wordGen, prefixGen); return new DictionaryFeatureVectorGenerator<LocalContext<WordAndPos>, String>( featureDictionary, featureGen, true); } public static void main(String[] args) { new TrainSupertagger().run(args); } private static class WordAndPosToWord implements Function<WordAndPos, String>, Serializable { private static final long serialVersionUID = 1L; @Override public String apply(WordAndPos wordAndPos) { return wordAndPos.getWord(); } } private static class WordAndPosContextToWordContext implements Function<LocalContext<WordAndPos>, LocalContext<String>>, Serializable { private static final long serialVersionUID = 1L; private final Function<WordAndPos, String> wordPosConverter; public WordAndPosContextToWordContext() { this.wordPosConverter = new WordAndPosToWord(); } @Override public LocalContext<String> apply(LocalContext<WordAndPos> context) { return new ConvertingLocalContext<WordAndPos, String>(context, wordPosConverter); } } }
package org.commcare.cases.util; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import org.javarosa.core.model.condition.EvaluationContext; import org.javarosa.core.model.instance.AbstractTreeElement; import org.javarosa.core.model.instance.TreeElement; import org.javarosa.core.model.instance.TreeReference; import org.javarosa.core.services.storage.IStorageUtilityIndexed; import org.javarosa.core.util.DataUtil; import org.javarosa.xpath.expr.XPathEqExpr; import org.javarosa.xpath.expr.XPathExpression; import org.javarosa.xpath.expr.XPathFuncExpr; import org.javarosa.xpath.expr.XPathPathExpr; /** * @author ctsims * */ public abstract class StorageBackedTreeRoot<T extends AbstractTreeElement> implements AbstractTreeElement<T> { protected Hashtable<Integer, Integer> objectIdMapping; protected abstract String getChildHintName(); protected abstract Hashtable<XPathPathExpr, String> getStorageIndexMap(); protected abstract IStorageUtilityIndexed<?> getStorage(); protected Vector<Integer> union(Vector<Integer> selectedCases, Vector<Integer> cases) { return DataUtil.union(selectedCases, cases); } protected abstract void initStorageCache(); protected String translateFilterExpr(XPathPathExpr expressionTemplate, XPathPathExpr matchingExpr, Hashtable<XPathPathExpr, String> indices) { return indices.get(expressionTemplate); } /** * Gets a potential cached mapping from a storage key that could be queried * on this tree to the storage ID of that element, rather than querying for * that through I/O. * * @param keyId The ID of a storage metadata key. * @return A table mapping the metadata key (must be unique) to the id of a * record in the storage backing this tree root. */ protected Hashtable<String, Integer> getKeyMapping(String keyId) { return null; } public Vector<TreeReference> tryBatchChildFetch(String name, int mult, Vector<XPathExpression> predicates, EvaluationContext evalContext) { //Restrict what we'll handle for now. All we want to deal with is predicate expressions on case blocks if(!name.equals(getChildHintName()) || mult != TreeReference.INDEX_UNBOUND || predicates == null) { return null; } Vector<Integer> selectedElements = null; Vector<Integer> toRemove = new Vector<Integer>(); IStorageUtilityIndexed<?> storage= getStorage(); Hashtable<XPathPathExpr, String> indices = getStorageIndexMap(); predicate: for(int i = 0 ; i < predicates.size() ; ++i) { XPathExpression xpe = predicates.elementAt(i); //what we want here is a static evaluation of the expression to see if it consists of evaluating //something we index with something static. if(xpe instanceof XPathEqExpr) { XPathExpression left = ((XPathEqExpr)xpe).a; if(left instanceof XPathPathExpr) { for(Enumeration en = indices.keys(); en.hasMoreElements() ;) { XPathPathExpr expr = (XPathPathExpr)en.nextElement(); if(expr.matches(left)) { String filterIndex = translateFilterExpr(expr, (XPathPathExpr)left, indices); //TODO: We need a way to determine that this value does not also depend on anything in the current context, not //sure the best way to do that....? Maybe tell the evaluation context to skip out here if it detects a request //to resolve in a certain area? Object o = XPathFuncExpr.unpack(((XPathEqExpr)xpe).b.eval(evalContext)); //Some storage roots will collect common iterative mappings ahead of time, //go check whether this key is loaded into cached memory. Hashtable<String, Integer> keyMapping = getKeyMapping(filterIndex); if(keyMapping != null) { //If so, go fetch that element's record id and skip the storage //lookup Integer uniqueValue = keyMapping.get(XPathFuncExpr.toString(o)); if(uniqueValue != null) { if(selectedElements == null) { selectedElements = new Vector<Integer>(); selectedElements.addElement(uniqueValue); } else { if(!selectedElements.contains(uniqueValue)) { selectedElements.addElement(uniqueValue); } } } } else { Vector<Integer> cases = null; try{ //Get all of the cases that meet this criteria cases = storage.getIDsForValue(filterIndex, o); } catch(IllegalArgumentException IAE) { //We can only get this if we have a new index type storage.registerIndex(filterIndex); try{ cases = storage.getIDsForValue(filterIndex, o); } catch(IllegalArgumentException iaeagain) { //Still didn't work, platform can't expand indices break predicate; } } // merge with any other sets of cases if(selectedElements == null) { selectedElements = cases; } else { selectedElements = union(selectedElements, cases); } } //Note that this predicate is evaluated and doesn't need to be evaluated in the future. toRemove.addElement(DataUtil.integer(i)); continue predicate; } } } } //There's only one case where we want to keep moving along, and we would have triggered it if it were going to happen, //so otherwise, just get outta here. break; } //if we weren't able to evaluate any predicates, signal that. if(selectedElements == null) { return null; } //otherwise, remove all of the predicates we've already evaluated for(int i = toRemove.size() - 1; i >= 0 ; i predicates.removeElementAt(toRemove.elementAt(i).intValue()); } TreeReference base = this.getRef(); initStorageCache(); Vector<TreeReference> filtered = new Vector<TreeReference>(); for(Integer i : selectedElements) { //this takes _waaaaay_ too long, we need to refactor this TreeReference ref = base.clone(); Integer realIndexInt = objectIdMapping.get(i); int realIndex =realIndexInt.intValue(); ref.add(this.getChildHintName(), realIndex); filtered.addElement(ref); } return filtered; } }
package com.mebigfatguy.fbcontrib.detect; import java.util.ArrayList; 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 org.apache.bcel.classfile.Code; import org.apache.bcel.generic.Type; 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; /** * finds methods that create and populate collections, and while knowing * the end size of those collections, does not pre allocate the collection * to be big enough. This just causes unneeded reallocations putting strain * on the garbage collector. */ public class PresizeCollections extends BytecodeScanningDetector { private static final Set<String> PRESIZEABLE_COLLECTIONS = new HashSet<String>(); static { PRESIZEABLE_COLLECTIONS.add("java/util/ArrayBlockingQueue"); PRESIZEABLE_COLLECTIONS.add("java/util/ArrayDeque"); PRESIZEABLE_COLLECTIONS.add("java/util/ArrayList"); PRESIZEABLE_COLLECTIONS.add("java/util/HashSet"); PRESIZEABLE_COLLECTIONS.add("java/util/LinkedBlockingQueue"); PRESIZEABLE_COLLECTIONS.add("java/util/LinkedHashSet"); PRESIZEABLE_COLLECTIONS.add("java/util/PriorityBlockingQueue"); PRESIZEABLE_COLLECTIONS.add("java/util/PriorityQueue"); PRESIZEABLE_COLLECTIONS.add("java/util/TreeSet"); PRESIZEABLE_COLLECTIONS.add("java/util/Vector"); } private BugReporter bugReporter; private OpcodeStack stack; private int allocNumber; private Map<Integer, Integer> allocLocation; private Map<Integer, List<Integer>> allocToAddPCs; private List<DownBranch> downBranches; public PresizeCollections(BugReporter bugReporter) { this.bugReporter = bugReporter; } /** * overrides the visitor to initialize the opcode stack * * @param classContext the context object that holds the JavaClass being parsed */ public void visitClassContext(ClassContext classContext) { try { stack = new OpcodeStack(); allocLocation = new HashMap<Integer, Integer>(); allocToAddPCs = new HashMap<Integer, List<Integer>>(); downBranches = new ArrayList<DownBranch>(); super.visitClassContext(classContext); } finally { stack = null; allocLocation = null; allocToAddPCs = null; downBranches = null; } } /** * implements the visitor to reset the opcode stack * @param obj the context object of the currently parsed code block */ @Override public void visitCode(Code obj) { stack.resetForMethodEntry(this); allocNumber = 0; allocLocation.clear(); allocToAddPCs.clear(); downBranches.clear(); super.visitCode(obj); for (List<Integer> pcs : allocToAddPCs.values()) { if (pcs.size() > 16) { bugReporter.reportBug(new BugInstance(this, "PSC_PRESIZE_COLLECTIONS", NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this, pcs.get(0))); } } } /** * implements the visitor to look for creation of collections * that are then populated with a known number of elements usually * based on another collection, but the new collection is not presized. * @param seen the opcode of the currently parsed instruction */ @Override public void sawOpcode(int seen) { boolean sawAlloc = false; try { switch (seen) { case INVOKESPECIAL: String clsName = getClassConstantOperand(); if (PRESIZEABLE_COLLECTIONS.contains(clsName)) { String methodName = getNameConstantOperand(); if ("<init>".equals(methodName)) { String signature = getSigConstantOperand(); if ("()V".equals(signature)) { sawAlloc = true; } } } break; case INVOKEINTERFACE: String methodName = getNameConstantOperand(); if ("add".equals(methodName) || "addAll".equals(methodName)) { String signature = getSigConstantOperand(); Type[] argTypes = Type.getArgumentTypes(signature); if ((argTypes.length == 1) && (stack.getStackDepth() > 1)) { OpcodeStack.Item item = stack.getStackItem(1); Integer allocNum = (Integer) item.getUserValue(); if (allocNum != null) { List<Integer> lines = allocToAddPCs.get(allocNum); if (lines == null) { lines = new ArrayList<Integer>(); allocToAddPCs.put(allocNum, lines); } lines.add(getPC()); } } } break; case IFEQ: case IFNE: case IFLT: case IFGE: case IFGT: case IFLE: case IF_ICMPEQ: case IF_ICMPNE: case IF_ICMPLT: case IF_ICMPGE: case IF_ICMPGT: case IF_ICMPLE: case IF_ACMPEQ: case IF_ACMPNE: case GOTO: case GOTO_W: if (getBranchOffset() < 0) { int target = getBranchTarget(); Iterator<Map.Entry<Integer, List<Integer>>> it = allocToAddPCs.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Integer, List<Integer>> entry = it.next(); Integer allocLoc = allocLocation.get(entry.getKey()); if ((allocLoc != null) && (allocLoc.intValue() < target)) { List<Integer> pcs = entry.getValue(); for (Integer pc : pcs) { if (pc > target) { int numDownBranches = countDownBranches(target, pc); if (numDownBranches <= 1) { bugReporter.reportBug(new BugInstance(this, "PSC_PRESIZE_COLLECTIONS", NORMAL_PRIORITY) .addClass(this) .addMethod(this) .addSourceLine(this, pc)); it.remove(); } break; } } } } } else { DownBranch db = new DownBranch(getPC(), getBranchTarget()); downBranches.add(db); } } } finally { stack.sawOpcode(this, seen); if (sawAlloc) { if (stack.getStackDepth() > 0) { OpcodeStack.Item item = stack.getStackItem(0); ++allocNumber; item.setUserValue(Integer.valueOf(allocNumber)); allocLocation.put(Integer.valueOf(allocNumber), Integer.valueOf(getPC())); } } } } private int countDownBranches(int loopTop, int addPC) { int numDownBranches = 0; for (DownBranch db : downBranches) { if ((db.fromPC > loopTop) && (db.toPC > addPC)) { numDownBranches++; } } return numDownBranches; } static class DownBranch { public int fromPC; public int toPC; public DownBranch(int from, int to) { fromPC = from; toPC = to; } @Override public String toString() { return "DownBranch[From: " + fromPC + " To: " + toPC + "]"; } } }
package ch.elexis.data; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.Hashtable; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import javax.xml.datatype.XMLGregorianCalendar; import org.eclipse.core.runtime.Status; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ch.elexis.admin.AccessControl; import ch.elexis.core.constants.Preferences; import ch.elexis.core.constants.StringConstants; import ch.elexis.core.data.activator.CoreHub; import ch.elexis.core.data.cache.IPersistentObjectCache; import ch.elexis.core.data.cache.MultiGuavaCache; import ch.elexis.core.data.constants.ElexisSystemPropertyConstants; import ch.elexis.core.data.events.ElexisEvent; import ch.elexis.core.data.events.ElexisEventDispatcher; import ch.elexis.core.data.extension.AbstractCoreOperationAdvisor; import ch.elexis.core.data.extension.CoreOperationExtensionPoint; import ch.elexis.core.data.interfaces.events.MessageEvent; import ch.elexis.core.data.status.ElexisStatus; import ch.elexis.core.data.util.DBUpdate; import ch.elexis.core.data.util.SqlRunner; import ch.elexis.core.exceptions.PersistenceException; import ch.elexis.core.jdt.NonNull; import ch.elexis.core.jdt.Nullable; import ch.elexis.core.model.IChangeListener; import ch.elexis.core.model.IPersistentObject; import ch.elexis.core.model.ISticker; import ch.elexis.core.model.IXid; import ch.elexis.data.Xid.XIDException; import ch.rgw.compress.CompEx; import ch.rgw.io.Settings; import ch.rgw.io.SqlSettings; import ch.rgw.tools.ExHandler; import ch.rgw.tools.JdbcLink; import ch.rgw.tools.JdbcLink.Stm; import ch.rgw.tools.JdbcLinkConcurrencyException; import ch.rgw.tools.JdbcLinkException; import ch.rgw.tools.JdbcLinkResourceException; import ch.rgw.tools.JdbcLinkSyntaxException; import ch.rgw.tools.Log; import ch.rgw.tools.StringTool; import ch.rgw.tools.TimeTool; import ch.rgw.tools.VersionInfo; import ch.rgw.tools.VersionedResource; import ch.rgw.tools.net.NetTool; public abstract class PersistentObject implements IPersistentObject { public static final String MAPPING_ERROR_MARKER = "**ERROR:"; /** predefined field name for the GUID */ public static final String FLD_ID = "id"; /** predefined property to handle a field that is a compressed HashMap */ public static final String FLD_EXTINFO = "ExtInfo"; /** predefined property to hande a field that marks the Object as deleted */ public static final String FLD_DELETED = "deleted"; /** * predefined property that holds an automatically updated field containing the last update of * this object as long value (milliseconds as in Date()) */ public static final String FLD_LASTUPDATE = "lastupdate"; /** * predefined property that holds the date of creation of this object in the form YYYYMMDD */ public static final String FLD_DATE = "Datum"; protected static final String DATE_COMPOUND = "Datum=S:D:Datum"; // initialize cache public static final int CACHE_DEFAULT_LIFETIME = 15; public static final int CACHE_MIN_LIFETIME = 5; public static final int CACHE_TIME_MAX = 300; protected static int default_lifetime; private static IPersistentObjectCache<String> cache = new MultiGuavaCache<String>(CACHE_DEFAULT_LIFETIME, TimeUnit.SECONDS); // maximum character length of int fields in tables private static int MAX_INT_LENGTH = 10; private static JdbcLink j = null; private static JdbcLink testJdbcLink = null; protected static Logger log = LoggerFactory.getLogger(PersistentObject.class.getName()); private String id; private static Hashtable<String, String> mapping; private static String username; private static String pcname; private static String tracetable; private static boolean runningFromScratch = false; private static String dbUser; private static String dbPw; private static File runFromScratchDB = null; protected static AbstractCoreOperationAdvisor cod = CoreOperationExtensionPoint.getCoreOperationAdvisor(); static { mapping = new Hashtable<String, String>(); default_lifetime = CoreHub.localCfg.get(Preferences.ABL_CACHELIFETIME, CACHE_DEFAULT_LIFETIME); if (default_lifetime < CACHE_MIN_LIFETIME) { default_lifetime = CACHE_MIN_LIFETIME; CoreHub.localCfg.set(Preferences.ABL_CACHELIFETIME, CACHE_MIN_LIFETIME); } log.info("Cache setup: default_lifetime " + default_lifetime); } public static enum FieldType { TEXT, LIST, JOINT }; /** * the possible states of a tristate checkbox: true/checked, false/unchecked, undefined/ * "filled with a square"/"partly selected" * * @since 3.0.0 */ static public enum TristateBoolean { TRUE, FALSE, UNDEF }; public static boolean connect(final Settings cfg){ dbUser = System.getProperty(ElexisSystemPropertyConstants.CONN_DB_USERNAME); dbPw = System.getProperty(ElexisSystemPropertyConstants.CONN_DB_PASSWORD); String dbFlavor = System.getProperty(ElexisSystemPropertyConstants.CONN_DB_FLAVOR); String dbSpec = System.getProperty(ElexisSystemPropertyConstants.CONN_DB_SPEC); if (ElexisSystemPropertyConstants.RUN_MODE_FROM_SCRATCH .equals(System.getProperty(ElexisSystemPropertyConstants.RUN_MODE))) { runningFromScratch = true; } log.debug("osgi.install.area: " + System.getProperty("osgi.install.area")); String demoDBLocation = System.getProperty(ElexisSystemPropertyConstants.DEMO_DB_LOCATION); if (demoDBLocation == null) { demoDBLocation = CoreHub.getWritableUserDir() + File.separator + "demoDB"; } File demo = new File(demoDBLocation); log.info("Checking demo database availability in " + demo.getAbsolutePath()); // returns if either, demo db, direct connection or run from scratch if (demo.exists() && demo.isDirectory()) { // open demo database connection log.info("Using demoDB in " + demo.getAbsolutePath()); j = JdbcLink.createH2Link(demo.getAbsolutePath() + File.separator + "db"); try { String username = System.getProperty(ElexisSystemPropertyConstants.CONN_DB_USERNAME); if (username == null) username = "sa"; String password = System.getProperty(ElexisSystemPropertyConstants.CONN_DB_PASSWORD); if (password == null) password = StringTool.leer; getConnection().connect(username, password); return connect(getConnection()); } catch (JdbcLinkException je) { ElexisStatus status = translateJdbcException(je); status.setMessage(status.getMessage() + " Fehler mit Demo-Datenbank: Es wurde zwar ein demoDB-Verzeichnis gefunden, aber dort ist keine verwendbare Datenbank"); throw new PersistenceException(status); } } else if (dbFlavor != null && dbFlavor.length() >= 2 && dbSpec != null && dbSpec.length() > 5 && dbUser != null && dbPw != null) { // open direct database connection according to system properties return PersistentObject.connect(dbFlavor, dbSpec, dbUser, dbPw, true); } else if (runningFromScratch) { // run from scratch configuration with a temporary database try { runFromScratchDB = File.createTempFile("elexis", "db"); log.info("RunFromScratch test database created in " + runFromScratchDB.getAbsolutePath()); dbUser = "sa"; dbPw = StringTool.leer; j = JdbcLink.createH2Link(runFromScratchDB.getAbsolutePath()); if (getConnection().connect(dbUser, dbPw)) { testJdbcLink = j; return connect(getConnection()); } else { log.error("can't create test database"); System.exit(-6); } } catch (Exception ex) { log.error("can't create test database"); System.exit(-7); } } // initialize a regular database connection String driver = ""; String user = ""; String pwd = ""; String typ = ""; String connectstring = ""; Hashtable<Object, Object> hConn = getConnectionHashtable(); if (hConn != null) { driver = checkNull((String) hConn.get(Preferences.CFG_FOLDED_CONNECTION_DRIVER)); user = checkNull((String) hConn.get(Preferences.CFG_FOLDED_CONNECTION_USER)); pwd = checkNull((String) hConn.get(Preferences.CFG_FOLDED_CONNECTION_PASS)); typ = checkNull((String) hConn.get(Preferences.CFG_FOLDED_CONNECTION_TYPE)); connectstring = checkNull((String) hConn.get(Preferences.CFG_FOLDED_CONNECTION_CONNECTSTRING)); } log.info("Driver is " + driver); try { log.info("Current work directory is " + new java.io.File(".").getCanonicalPath()); } catch (IOException e) { log.error("Error determining current work directory", e); } if (StringTool.leer.equals(driver)) { cod.requestDatabaseConnectionConfiguration(); MessageEvent.fireInformation("Datenbankverbindung geändert", "Bitte starten Sie Elexis erneut"); System.exit(-1); } else { j = new JdbcLink(driver, connectstring, typ); } try { getConnection().connect(user, pwd); } catch (JdbcLinkException je) { ElexisStatus status = translateJdbcException(je); status.setLogLevel(ElexisStatus.LOG_FATALS); throw new PersistenceException(status); } log.debug("Verbunden mit " + getConnection().dbDriver() + ", " + connectstring); return connect(getConnection()); } /** * * @return a {@link Hashtable} containing the connection parameters, use * {@link Preferences#CFG_FOLDED_CONNECTION} to retrieve the required parameters, * castable to {@link String} */ public static @NonNull Hashtable<Object, Object> getConnectionHashtable(){ Hashtable<Object, Object> ret = new Hashtable<>(); String cnt = CoreHub.localCfg.get(Preferences.CFG_FOLDED_CONNECTION, null); if (cnt != null) { log.debug("Read connection string from localCfg"); ret = fold(StringTool.dePrintable(cnt)); } return ret; } /** * Directly connect to the database using the combined connection information. * * @param dbFlavor * either <code>mysql</code>, <code>postgresql</code> or <code>h2</code> * @param dbSpec * connection string fitting to dbFlavor, e.g. * <code>jdbc:postgresql://192.168.0.3:5432/elexis</code> * @param dbUser * the <code>username</code> to connect to the database with * @param dbPw * the <code>password</code> to connect to the database with * @param exitOnFail * @return * @since 3.0.0 */ private static boolean connect(String dbFlavor, String dbSpec, String dbUser, String dbPw, boolean exitOnFail){ String msg = "Connecting to DB using " + dbFlavor + " " + dbSpec + " " + dbUser; System.out.println(msg); log.info(msg); String driver; if (dbFlavor.equalsIgnoreCase("mysql")) driver = "com.mysql.jdbc.Driver"; else if (dbFlavor.equalsIgnoreCase("postgresql")) driver = "org.postgresql.Driver"; else if (dbFlavor.equalsIgnoreCase("h2")) driver = "org.h2.Driver"; else driver = "invalid"; if (!driver.equalsIgnoreCase("invalid")) { try { j = new JdbcLink(driver, dbSpec, dbFlavor); if (getConnection().connect(dbUser, dbPw)) { testJdbcLink = j; return connect(getConnection()); } else { msg = "can't connect to test database: " + dbSpec + " using " + dbFlavor; log.error(msg); System.out.println(msg); if (exitOnFail) System.exit(-6); return false; } } catch (Exception ex) { msg = "Exception connecting to test database:" + dbSpec + " using " + dbFlavor + ": " + ex.getMessage(); log.error(msg); System.out.println(msg); if (exitOnFail) System.exit(-7); return false; } } msg = "can't connect to test database invalid. dbFlavor" + dbFlavor; log.error(msg); System.out.println(msg); if (exitOnFail) { System.exit(-7); } return false; } public static boolean connect(final JdbcLink jd){ j = jd; if (runningFromScratch) { deleteAllTables(); } if (tableExists("CONFIG")) { CoreHub.globalCfg = new SqlSettings(getConnection(), "CONFIG"); String created = CoreHub.globalCfg.get("created", null); log.debug("Database version " + created); } else { log.debug("No Version found. Creating new Database"); Stm stm = null; try (InputStream is = PersistentObject.class.getResourceAsStream("/rsc/createDB.script")) { stm = getConnection().getStatement(); if (stm.execScript(is, true, true) == true) { executeDBInitScriptForClass(User.class, null); executeDBInitScriptForClass(Role.class, null); CoreHub.globalCfg = new SqlSettings(getConnection(), "CONFIG"); CoreHub.globalCfg.undo(); CoreHub.globalCfg.set("created", new TimeTool().toString(TimeTool.FULL_GER)); Mandant.initializeAdministratorUser(); CoreHub.pin.initializeGrants(); CoreHub.pin.initializeGlobalPreferences(); if (runningFromScratch) { Mandant m = new Mandant("007", "topsecret"); String clientEmail = System.getProperty(ElexisSystemPropertyConstants.CLIENT_EMAIL); if (clientEmail == null) clientEmail = "james@bond.invalid"; m.set(new String[] { Person.NAME, Person.FIRSTNAME, Person.TITLE, Person.SEX, Person.FLD_E_MAIL, Person.FLD_PHONE1, Person.FLD_FAX, Kontakt.FLD_STREET, Kontakt.FLD_ZIP, Kontakt.FLD_PLACE }, "Bond", "James", "Dr. med.", Person.MALE, clientEmail, "0061 555 55 55", "0061 555 55 56", "10, Baker Street", "9999", "Elexikon"); } else { cod.requestInitialMandatorConfiguration(); } CoreHub.globalCfg.flush(); CoreHub.localCfg.flush(); if (!runningFromScratch) { MessageEvent.fireInformation("Neue Datenbank", "Es wurde eine neue Datenbank angelegt."); } } else { log.error("Kein create script für Datenbanktyp " + getConnection().DBFlavor + " gefunden."); return false; } } catch (Throwable ex) { ExHandler.handle(ex); return false; } finally { getConnection().releaseStatement(stm); } } // Zugriffskontrolle initialisieren VersionInfo vi = new VersionInfo(CoreHub.globalCfg.get("dbversion", "0.0.0")); log.info("Verlangte Datenbankversion: " + CoreHub.DBVersion); log.info("Gefundene Datenbankversion: " + vi.version()); if (vi.isOlder(CoreHub.DBVersion)) { log.warn("Ältere Version der Datenbank gefunden "); DBUpdate.doUpdate(); } vi = new VersionInfo(CoreHub.globalCfg.get("ElexisVersion", "0.0.0")); log.info("Verlangte Elexis-Version: " + vi.version()); log.info("Vorhandene Elexis-Version: " + CoreHub.Version); VersionInfo v2 = new VersionInfo(CoreHub.Version); if (vi.isNewerMinor(v2)) { String msg = String.format( "Die Datenbank %1s ist für eine neuere Elexisversion '%2s' als die aufgestartete '%3s'. Wollen Sie trotzdem fortsetzen?", jd.getConnectString(), vi.version().toString(), v2.version().toString()); log.error(msg); if (!cod.openQuestion("Diskrepanz in der Datenbank-Version ", msg)) { System.exit(2); } else { log.error("User continues with Elexis / database version mismatch"); } } setTrace(CoreHub.globalCfg.get(Preferences.ABL_TRACE, null)); // diese // Station eingeschaltet sein if (tracetable == null) { setTrace(CoreHub.localCfg.get(Preferences.ABL_TRACE, null)); } return true; } public static JdbcLink getConnection(){ return j; } static protected void addMapping(final String prefix, final String... map){ for (String s : map) { String[] def = s.trim().split("[ \t]*=[ \t]*"); if (def.length != 2) { mapping.put(prefix + def[0], def[0]); } else { mapping.put(prefix + def[0], def[1]); } } mapping.put(prefix + "deleted", "deleted"); mapping.put(prefix + "lastupdate", "lastupdate"); } public static void setTrace(String Tablename){ if ((Tablename != null) && (Tablename.equals("none") || Tablename.equals(""))) { Tablename = null; } tracetable = Tablename; username = JdbcLink.wrap(System.getProperty("user.name")); pcname = JdbcLink.wrap(NetTool.hostname); } public static synchronized String lock(final String name, final boolean wait){ Stm stm = getConnection().getStatement(); String lockname = "lock" + name; String lockid = StringTool.unique("lock"); try { while (true) { long timestamp = System.currentTimeMillis(); // Gibt es das angeforderte Lock schon? String oldlock = stm .queryString("SELECT wert FROM CONFIG WHERE param=" + JdbcLink.wrap(lockname)); if (!StringTool.isNothing(oldlock)) { // Ja, wie alt ist es? String[] def = oldlock.split(" long locktime = Long.parseLong(def[1]); long age = timestamp - locktime; if (age > 2000L) { stm.exec("DELETE FROM CONFIG WHERE param=" + JdbcLink.wrap(lockname)); } else { if (wait == false) { return null; } else { continue; } } } // Neues Lock erstellen String lockstring = lockid + "#" + Long.toString(System.currentTimeMillis()); StringBuilder sb = new StringBuilder(); sb.append("INSERT INTO CONFIG (param,wert) VALUES (") .append(JdbcLink.wrap(lockname)).append(",").append("'").append(lockstring) .append("')"); stm.exec(sb.toString()); // schneller war. String check = stm .queryString("SELECT wert FROM CONFIG WHERE param=" + JdbcLink.wrap(lockname)); if (check.equals(lockstring)) { break; } } return lockid; } finally { getConnection().releaseStatement(stm); } } /** * Exklusivzugriff wieder aufgeben * * @param name * Name des Locks * @param id * bei "lock" erhaltene LockID * @return true bei Erfolg */ public static synchronized boolean unlock(final String name, final String id){ String lockname = "lock" + name; String lock = getConnection() .queryString("SELECT wert from CONFIG WHERE param=" + JdbcLink.wrap(lockname)); if (StringTool.isNothing(lock)) { return false; } String[] res = lock.split(" if (res[0].equals(id)) { getConnection().exec("DELETE FROM CONFIG WHERE param=" + JdbcLink.wrap(lockname)); return true; } return false; } protected String getConstraint(){ return ""; } protected void setConstraint(){ /* Standardimplementation ist leer */ } abstract public String getLabel(); /** * Jede abgeleitete Klasse muss deklarieren, in welcher Tabelle sie gespeichert werden will. * * @return Der Name einer bereits existierenden Tabelle der Datenbank */ abstract protected String getTableName(); public boolean isValid(){ if (state() < EXISTS) { return false; } return true; } public String getId(){ return id; } /** * Die ID in einen datenbankgeeigneten Wrapper verpackt (je nach Datenbank; meist Hochkommata). */ public String getWrappedId(){ return JdbcLink.wrap(id); } /** Der Konstruktor erstellt die ID */ protected PersistentObject(){ id = StringTool.unique("prso"); } /** * Konstruktor mit vorgegebener ID (zum Deserialisieren) Wird nur von xx::load gebraucht. */ protected PersistentObject(final String id){ this.id = id; } public String storeToString(){ return getClass().getName() + StringConstants.DOUBLECOLON + getId(); } /** An object with this ID does not exist */ public static final int INEXISTENT = 0; /** This id is not valid */ public static final int INVALID_ID = 1; /** An object with this ID exists but is marked deleted */ public static final int DELETED = 2; /** This is an existing object */ public static final int EXISTS = 3; /** * Check the state of an object with this ID Note: This method accesses the database and * therefore is much more costly than the simple instantaniation of a PersistentObject * * @return a value between INEXISTENT and EXISTS */ public int state(){ if (StringTool.isNothing(getId())) { return INVALID_ID; } StringBuilder sb = new StringBuilder("SELECT ID FROM "); sb.append(getTableName()).append(" WHERE ID=").append(getWrappedId()); try { String obj = j.queryString(sb.toString()); if (id.equalsIgnoreCase(obj)) { String deleted = get("deleted"); if (deleted == null) { // if we cant't find the column called // 'deleted', the object exists anyway return EXISTS; } return deleted.equals("1") ? DELETED : EXISTS; } else { return INEXISTENT; } } catch (JdbcLinkSyntaxException ex) { return INEXISTENT; } } public boolean exists(){ return state() == EXISTS; } /** * Check whether the object exists in the database. This is the case for all objects in the * database for which state() returns neither INVALID_ID nor INEXISTENT. Note: objects marked as * deleted will also return true! * * @return true, if the object is available in the database, false otherwise */ public boolean isAvailable(){ return (state() >= DELETED); } /** * Return a xid (domain_id) for a specified domain * * @param domain * @return an identifier that may be empty but will never be null */ public String getXid(final String domain){ if (domain.equals(Xid.DOMAIN_ELEXIS)) { return getId(); } Query<Xid> qbe = new Query<Xid>(Xid.class); qbe.add(Xid.FLD_OBJECT, Query.EQUALS, getId()); qbe.add(Xid.FLD_DOMAIN, Query.EQUALS, domain); List<Xid> res = qbe.execute(); if (res.size() > 0) { return res.get(0).get(Xid.FLD_ID_IN_DOMAIN); } return ""; } /** * return the "best" xid for a given object. This is the xid with the highest quality. If no xid * is given for this object, a newly created xid of local quality will be returned */ public IXid getXid(){ List<IXid> res = getXids(); if (res.size() == 0) { try { return new Xid(this, Xid.DOMAIN_ELEXIS, getId()); } catch (XIDException xex) { // Should never happen, uh? ExHandler.handle(xex); return null; } } int quality = 0; IXid ret = null; for (IXid xid : res) { if (xid.getQuality() > quality) { quality = xid.getQuality(); ret = xid; } } if (ret == null) { return res.get(0); } return ret; } /** * retrieve all XIDs of this object * * @return a List that might be empty but is never null */ public List<IXid> getXids(){ Query<IXid> qbe = new Query<IXid>(Xid.class); qbe.add(Xid.FLD_OBJECT, Query.EQUALS, getId()); return qbe.execute(); } /** * Assign a XID to this object. * * @param domain * the domain whose ID will be assigned * @param domain_id * the id out of the given domain fot this object * @param updateIfExists * if true update values if Xid with same domain and domain_id exists. Otherwise the * method will fail if a collision occurs. * @return true on success, false on failure */ public boolean addXid(final String domain, final String domain_id, final boolean updateIfExists){ Xid oldXID = Xid.findXID(this, domain); if (oldXID != null) { if (updateIfExists) { oldXID.set(Xid.FLD_ID_IN_DOMAIN, domain_id); return true; } return false; } try { new Xid(this, domain, domain_id); return true; } catch (XIDException e) { ExHandler.handle(e); if (updateIfExists) { Xid xid = Xid.findXID(domain, domain_id); if (xid != null) { xid.set(Xid.FLD_OBJECT, getId()); return true; } } return false; } } public ISticker getSticker(){ List<ISticker> list = getStickers(); return list.size() > 0 ? list.get(0) : null; } /** * get all stickers of this object * * @return a List of Sticker objects */ private static String queryStickersString = "SELECT etikette FROM " + Sticker.FLD_LINKTABLE + " WHERE obj=?"; /** * Return all Stickers attributed to this objecz * * @return A possibly empty list of Stickers */ @SuppressWarnings("unchecked") public List<ISticker> getStickers(){ String ID = new StringBuilder().append("ETK").append(getId()).toString(); ArrayList<ISticker> ret = (ArrayList<ISticker>) cache.get(ID, getCacheTime()); if (ret != null) { return ret; } ret = new ArrayList<ISticker>(); PreparedStatement queryStickers = j.getPreparedStatement(queryStickersString); try { queryStickers.setString(1, id); ResultSet res = queryStickers.executeQuery(); while (res.next()) { Sticker et = Sticker.load(res.getString(1)); if (et != null && et.exists()) { ret.add(Sticker.load(res.getString(1))); } } res.close(); } catch (Exception ex) { ExHandler.handle(ex); return ret; } finally { try { queryStickers.close(); } catch (SQLException e) { // ignore } j.releasePreparedStatement(queryStickers); } Collections.sort(ret); cache.put(ID, ret, getCacheTime()); return ret; } /** * Remove a Sticker from this object * * @param et * the Sticker to remove */ @SuppressWarnings("unchecked") public void removeSticker(ISticker et){ String ID = new StringBuilder().append("ETK").append(getId()).toString(); ArrayList<Sticker> ret = (ArrayList<Sticker>) cache.get(ID, getCacheTime()); if (ret != null) { ret.remove(et); } StringBuilder sb = new StringBuilder(); sb.append("DELETE FROM ").append(Sticker.FLD_LINKTABLE).append(" WHERE obj=") .append(getWrappedId()).append(" AND etikette=").append(JdbcLink.wrap(et.getId())); getConnection().exec(sb.toString()); } /** * Add a Sticker to this object * * @param st * the Sticker to add */ @SuppressWarnings("unchecked") public void addSticker(ISticker st){ String ID = new StringBuilder().append("STK").append(getId()).toString(); List<ISticker> ret = (List<ISticker>) cache.get(ID, getCacheTime()); if (ret == null) { ret = getStickers(); } if (!ret.contains(st)) { ret.add(st); Collections.sort(ret); StringBuilder sb = new StringBuilder(); sb.append("INSERT INTO ").append(Sticker.FLD_LINKTABLE) .append("(obj,etikette) VALUES (").append(getWrappedId()).append(",") .append(JdbcLink.wrap(st.getId())).append(");"); getConnection().exec(sb.toString()); } } public boolean isDeleted(){ return get("deleted").equals("1"); } /** * Darf dieses Objekt mit Drag&Drop verschoben werden? * * @return true wenn ja. */ public boolean isDragOK(){ return false; } public String map(final String f){ String prefix = getTableName(); return map(prefix, f); } /** * Return the database field corresponding to an internal Elexis field valud * * @param tableName * the tableName * @param field * the field name * @return the database field or **ERROR** if no mapping exists * @since 3.1 */ public static String map(final String tableName, final String field){ if (field.equals("ID")) return field; String res = mapping.get(tableName + field); if (res == null) { log.info("field is not mapped " + field); return MAPPING_ERROR_MARKER + field + "**"; } return res; } public FieldType getFieldType(final String f){ String mapped = map(f); if (mapped.startsWith("LIST:")) { return FieldType.LIST; } else if (mapped.startsWith("JOINT:")) { return FieldType.JOINT; } else { return FieldType.TEXT; } } public String get(final String field){ String key = getKey(field); Object ret = cache.get(key, getCacheTime()); if (ret instanceof String) { return (String) ret; } boolean decrypt = false; StringBuffer sql = new StringBuffer(); String mapped = map(field); String table = getTableName(); if (mapped.startsWith("EXT:")) { int ix = mapped.indexOf(':', 5); if (ix == -1) { log.error("Fehlerhaftes Mapping bei " + field); return MAPPING_ERROR_MARKER + " " + field + "**"; } table = mapped.substring(4, ix); mapped = mapped.substring(ix + 1); } else if (mapped.startsWith("S:")) { mapped = mapped.substring(4); decrypt = true; } else if (mapped.startsWith("JOINT:")) { String[] dwf = mapped.split(":"); if (dwf.length > 4) { String objdef = dwf[4] + "::"; StringBuilder sb = new StringBuilder(); List<String[]> list = getList(field, new String[0]); PersistentObjectFactory fac = new PersistentObjectFactory(); for (String[] s : list) { PersistentObject po = fac.createFromString(objdef + s[0]); sb.append(po.getLabel()).append("\n"); } return sb.toString(); } } else if (mapped.startsWith("LIST:")) { String[] dwf = mapped.split(":"); if (dwf.length > 4) { String objdef = dwf[4] + "::"; StringBuilder sb = new StringBuilder(); List<String> list = getList(field, false); PersistentObjectFactory fac = new PersistentObjectFactory(); for (String s : list) { PersistentObject po = fac.createFromString(objdef + s); sb.append(po.getLabel()).append("\n"); } return sb.toString(); } } else if (mapped.startsWith(MAPPING_ERROR_MARKER)) { // If the field // could not be // mapped String exi = map(FLD_EXTINFO); // Try to find it in ExtInfo if (!exi.startsWith(MAPPING_ERROR_MARKER)) { Map ht = getMap(FLD_EXTINFO); Object res = ht.get(field); if (res instanceof String) { return (String) res; } } // try to find an XID with that name String xid = getXid(field); if (xid.length() > 0) { return xid; } // or try to find a "getter" Method // for the field String method = "get" + field; try { Method mx = getClass().getMethod(method, new Class[0]); Object ro = mx.invoke(this, new Object[0]); if (ro == null) { return ""; } else if (ro instanceof String) { return (String) ro; } else if (ro instanceof Integer) { return Integer.toString((Integer) ro); } else if (ro instanceof PersistentObject) { return ((PersistentObject) ro).getLabel(); } else { return "?invalid field? " + mapped; } } catch (NoSuchMethodException nmex) { log.warn("Fehler bei Felddefinition " + field); ElexisStatus status = new ElexisStatus(ElexisStatus.WARNING, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NOFEEDBACK, "Fehler bei Felddefinition", nmex); ElexisEventDispatcher.fireElexisStatusEvent(status); return mapped; } catch (Exception ex) { // ignore the exceptions calling functions look for // MAPPING_ERROR_MARKER ExHandler.handle(ex); return mapped; } } sql.append("SELECT ").append(mapped).append(" FROM ").append(table).append(" WHERE ID='") .append(id).append("'"); Stm stm = getConnection().getStatement(); String res = null; try (ResultSet rs = executeSqlQuery(sql.toString(), stm)) { if ((rs != null) && (rs.next() == true)) { if (decrypt) { res = decode(field, rs); } else { res = rs.getString(mapped); } if (res == null) { res = ""; } cache.put(key, res, getCacheTime()); } } catch (SQLException ex) { ExHandler.handle(ex); } finally { getConnection().releaseStatement(stm); } return res; } public byte[] getBinary(final String field){ String key = getKey(field); Object o = cache.get(key, getCacheTime()); if (o instanceof byte[]) { return (byte[]) o; } byte[] ret = getBinaryRaw(field); cache.put(key, ret, getCacheTime()); return ret; } private byte[] getBinaryRaw(final String field){ StringBuilder sql = new StringBuilder(); String mapped = (field); String table = getTableName(); sql.append("SELECT ").append(mapped).append(" FROM ").append(table).append(" WHERE ID='") .append(id).append("'"); Stm stm = getConnection().getStatement(); try (ResultSet rs = executeSqlQuery(sql.toString(), stm)) { if ((rs != null) && (rs.next() == true)) { return rs.getBytes(mapped); } } catch (Exception ex) { ExHandler.handle(ex); } finally { getConnection().releaseStatement(stm); } return null; } protected VersionedResource getVersionedResource(final String field, final boolean flushCache){ String key = getKey(field); if (flushCache == false) { Object o = cache.get(key, getCacheTime()); if (o instanceof VersionedResource) { return (VersionedResource) o; } } byte[] blob = getBinaryRaw(field); VersionedResource ret = VersionedResource.load(blob); cache.put(key, ret, getCacheTime()); return ret; } /** * Eine Hashtable auslesen * * @param field * Feldname der Hashtable * @return eine Hashtable (ggf. leer). Nie null. */ @SuppressWarnings({ "rawtypes", "unchecked" }) public @NonNull Map getMap(final String field){ String key = getKey(field); Object o = cache.get(key, getCacheTime()); if (o instanceof Hashtable) { return (Hashtable) o; } byte[] blob = getBinaryRaw(field); if (blob == null) { return new Hashtable(); } Hashtable<Object, Object> ret = fold(blob); if (ret == null) { return new Hashtable(); } cache.put(key, ret, getCacheTime()); return ret; } /** * Retrieves an object out of the {@link #FLD_EXTINFO} if it exists * * @param key * @return the {@link Object} stored for the given key in ExtInfo, or <code>null</code> * @since 3.0 */ public @Nullable Object getExtInfoStoredObjectByKey(final Object key){ // query cache? byte[] binaryRaw = getBinaryRaw(FLD_EXTINFO); if (binaryRaw == null) return null; @SuppressWarnings("unchecked") Map<Object, Object> ext = getMap(FLD_EXTINFO); return ext.get(key); } /** * Set a value in the {@link #FLD_EXTINFO} field, will create an ExtInfo field if required * * @param key * @param value * @since 3.0 */ public void setExtInfoStoredObjectByKey(final Object key, final Object value){ Map extinfo = getMap(FLD_EXTINFO); extinfo.put(key, value); setMap(FLD_EXTINFO, extinfo); } /** * Bequemlichkeitsmethode zum lesen eines Integer. * * @param field * @return einen Integer. 0 bei 0 oder unlesbar */ public int getInt(final String field){ return checkZero(get(field)); } /** * convenience method to read a boolean value, write it using {@link #ts(Object)} and * {@link #set(String, String)} * * @param field * @return <code>true</code> iff the stored value is <code>1</code> * @since 3.1 */ public boolean getBoolean(final String field){ String val = get(field); return (StringConstants.ONE.equals(val)) ? true : false; } /** * returns the selected TristateBoolean value (for a tristate checkbox) * * @param field * the name of the field to be tested * @return the current tristate selection state, one of TristateBoolean (TRUE/FALSE/UNDEF) * @author H. Marlovits * @since 3.0.0 */ public TristateBoolean getTriStateBoolean(final String field){ String value = get(field); if (value == null) return TristateBoolean.UNDEF; if (value.equalsIgnoreCase(StringConstants.ONE)) return TristateBoolean.TRUE; else if (value.equalsIgnoreCase(StringConstants.ZERO)) return TristateBoolean.FALSE; else return TristateBoolean.UNDEF; } /** * save the selected TristateBoolean value (of a tristate checkbox) * * @param field * the name of the field to be set * @param newVal * the new state to save to the cb, one of TristateBoolean (TRUE/FALSE/UNDEF) * @author H. Marlovits * @since 3.0.0 */ public void setTriStateBoolean(final String field, TristateBoolean newVal) throws IllegalArgumentException, PersistenceException{ if (newVal == null) throw new IllegalArgumentException( "PersistentObject.setTriStateBoolean(): param newVal == null"); String saveVal = ""; if (newVal == TristateBoolean.TRUE) saveVal = StringConstants.ONE; if (newVal == TristateBoolean.FALSE) saveVal = StringConstants.ZERO; if (newVal == TristateBoolean.UNDEF) saveVal = StringConstants.EMPTY; boolean result = set(field, saveVal); if (!result) { throw new PersistenceException( new ElexisStatus(Status.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, "PersistentObject.setTriStateBoolean(): Error on saving value " + newVal + " to field " + field, null)); } } @SuppressWarnings("unchecked") public List<String> getList(final String field, final boolean reverse){ StringBuffer sql = new StringBuffer(); String mapped = map(field); if (mapped.startsWith("LIST:")) { // LIST:EigeneID:Tabelle:orderby[:type] String[] m = mapped.split(":"); if (m.length > 2) { // String order=null; sql.append("SELECT ID FROM ").append(m[2]).append(" WHERE "); sql.append("deleted=").append(JdbcLink.wrap("0")).append(" AND "); sql.append(m[1]).append("=").append(getWrappedId()); if (m.length > 3) { sql.append(" ORDER by ").append(m[3]); if (reverse) { sql.append(" DESC"); } } Stm stm = getConnection().getStatement(); List<String> ret = stm.queryList(sql.toString(), new String[] { "ID" }); getConnection().releaseStatement(stm); return ret; } } else { log.error("Fehlerhaftes Mapping " + mapped); } return null; } @SuppressWarnings("unchecked") public List<String[]> getList(final String field, String[] extra){ if (extra == null) { extra = new String[0]; } String mapped = map(field); if (mapped.startsWith("JOINT:")) { // query cache String cacheId = field + "$" + mapped + "$" + Arrays.toString(extra) + "$" + getWrappedId(); Object cached = cache.get(cacheId, getCacheTime()); if (cached != null) return (List<String[]>) cached; StringBuffer sql = new StringBuffer(); String[] abfr = mapped.split(":"); sql.append("SELECT ").append(abfr[1]); for (String ex : extra) { sql.append(",").append(ex); } sql.append(" FROM ").append(abfr[3]).append(" WHERE ").append(abfr[2]).append("=") .append(getWrappedId()); Stm stm = getConnection().getStatement(); LinkedList<String[]> list = new LinkedList<String[]>(); try (ResultSet rs = executeSqlQuery(sql.toString(), stm)) { while ((rs != null) && rs.next()) { String[] line = new String[extra.length + 1]; line[0] = rs.getString(abfr[1]); for (int i = 1; i < extra.length + 1; i++) { line[i] = rs.getString(extra[i - 1]); } list.add(line); } cache.put(cacheId, list, getCacheTime()); return list; } catch (Exception ex) { ElexisStatus status = new ElexisStatus(ElexisStatus.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, "Fehler beim Lesen der Liste ", ex, ElexisStatus.LOG_ERRORS); // This is not an exception but a misconfiguration. No need to // stop program flow. // Just return null // as the documentation of the method states. // throw new PersistenceException(status); return null; } finally { getConnection().releaseStatement(stm); } } else { log.error("Fehlerhaftes Mapping " + mapped); } return null; } public boolean set(final String field, String value){ String mapped = map(field); String table = getTableName(); String key = getKey(field); StringBuilder sql = new StringBuilder(); long ts = System.currentTimeMillis(); if (value == null) { cache.remove(key); sql.append("UPDATE ").append(table).append(" SET ").append(mapped) .append("=NULL, lastupdate=" + Long.toString(ts) + " WHERE ID=") .append(getWrappedId()); getConnection().exec(sql.toString()); return true; } Object oldval = cache.get(key, getCacheTime()); cache.put(key, value, getCacheTime()); // refresh cache if (value.equals(oldval)) { return true; // no need to write data if it ws already in cache } if (mapped.startsWith("EXT:")) { int ix = mapped.indexOf(':', 5); if (ix == -1) { log.error("Fehlerhaftes Mapping bei " + field); return false; } table = mapped.substring(4, ix); mapped = mapped.substring(ix + 1); sql.append("UPDATE ").append(table).append(" SET ").append(mapped); } else { sql.append("UPDATE ").append(table).append(" SET "); if (mapped.startsWith("S:")) { sql.append(mapped.substring(4)); } else { sql.append(mapped); } } sql.append("=?, lastupdate=? WHERE ID=").append(getWrappedId()); String cmd = sql.toString(); PreparedStatement pst = getConnection().getPreparedStatement(cmd); encode(1, pst, field, value); if (tracetable != null) { StringBuffer params = new StringBuffer(); params.append("["); params.append(value); params.append("]"); doTrace(cmd + " " + params); } try { pst.setLong(2, ts); pst.executeUpdate(); // ElexisEventDispatcher.getInstance().fire(new // ElexisEvent(this,this.getClass(),ElexisEvent.EVENT_UPDATE)); return true; } catch (Exception ex) { ElexisStatus status = new ElexisStatus(ElexisStatus.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, "Fehler bei: " + cmd + "(" + field + "=" + value + ")", ex, ElexisStatus.LOG_ERRORS); throw new PersistenceException(status); // See api doc. check this // whether it breaks // existing code. // return false; // See api doc. Return false on errors. } finally { try { pst.close(); } catch (SQLException e) {} getConnection().releasePreparedStatement(pst); } } @SuppressWarnings("rawtypes") public void setMap(final String field, final Map<Object, Object> map){ if (map == null) { throw new PersistenceException(new ElexisStatus(Status.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, "Attempt to store Null map", null)); } byte[] bin = flatten((Hashtable) map); cache.put(getKey(field), map, getCacheTime()); setBinary(field, bin); } protected void setVersionedResource(final String field, final String entry){ String lockid = lock("VersionedResource", true); VersionedResource old = getVersionedResource(field, true); if (old.update(entry, CoreHub.actUser.getLabel()) == true) { cache.put(getKey(field), old, getCacheTime()); setBinary(field, old.serialize()); } unlock("VersionedResource", lockid); } public void setBinary(final String field, final byte[] value){ String key = getKey(field); cache.put(key, value, getCacheTime()); setBinaryRaw(field, value); } private void setBinaryRaw(final String field, final byte[] value){ StringBuilder sql = new StringBuilder(1000); sql.append("UPDATE ").append(getTableName()).append(" SET ").append(/* map */(field)) .append("=?, lastupdate=?").append(" WHERE ID=").append(getWrappedId()); String cmd = sql.toString(); if (tracetable != null) { doTrace(cmd); } PreparedStatement stm = getConnection().getPreparedStatement(cmd); try { stm.setBytes(1, value); stm.setLong(2, System.currentTimeMillis()); stm.executeUpdate(); } catch (Exception ex) { log.error("Fehler beim Ausführen der Abfrage " + cmd, ex); throw new PersistenceException( new ElexisStatus(Status.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, "setBytes: Es trat ein Fehler beim Schreiben auf. " + ex.getMessage(), ex, Log.ERRORS)); } finally { try { stm.close(); } catch (SQLException e) { ExHandler.handle(e); throw new PersistenceException("Could not close statement " + e.getMessage()); } getConnection().releasePreparedStatement(stm); } } /** * Set a value of type int. * * @param field * a table field of numeric type * @param value * the value to be set * @return true on success, false else */ public boolean setInt(final String field, final int value){ String stringValue = new Integer(value).toString(); if (stringValue.length() <= MAX_INT_LENGTH) { return set(field, stringValue); } else { return false; } } private void doTrace(final String sql){ StringBuffer tracer = new StringBuffer(); tracer.append("INSERT INTO ").append(tracetable); tracer.append(" (logtime,Workstation,Username,action) VALUES ("); tracer.append(System.currentTimeMillis()).append(","); tracer.append(pcname).append(","); tracer.append(username).append(","); tracer.append(JdbcLink.wrap(sql.replace('\'', '/'))).append(")"); getConnection().exec(tracer.toString()); } public int addToList(final String field, final String oID, final String... extra){ String mapped = map(field); if (mapped.startsWith("JOINT:")) { String[] m = mapped.split(":");// m[1] FremdID, m[2] eigene ID, m[3] // Name Joint if (m.length > 3) { StringBuffer head = new StringBuffer(100); StringBuffer tail = new StringBuffer(100); head.append("INSERT INTO ").append(m[3]).append("(ID,").append(m[2]).append(",") .append(m[1]); tail.append(") VALUES (").append(JdbcLink.wrap(StringTool.unique("aij"))) .append(",").append(getWrappedId()).append(",").append(JdbcLink.wrap(oID)); if (extra != null) { for (String s : extra) { String[] def = s.split("="); if (def.length != 2) { log.error("Fehlerhafter Aufruf addToList " + s); return 0; } head.append(",").append(def[0]); tail.append(",").append(JdbcLink.wrap(def[1])); } } head.append(tail).append(")"); if (tracetable != null) { String sql = head.toString(); doTrace(sql); return getConnection().exec(sql); } return getConnection().exec(head.toString()); } } else if (mapped.startsWith("LIST:")) { // LIST:EigeneID:Tabelle:orderby[:type] String[] m = mapped.split(":"); if (m.length > 2) { try { String psString = "INSERT INTO " + m[2] + " (ID, deleted, " + m[1] + ") VALUES (?, 0, ?);"; PreparedStatement ps = getConnection().getPreparedStatement(psString); ps.setString(1, oID); ps.setString(2, getId()); int result = ps.executeUpdate(); getConnection().releasePreparedStatement(ps); return result; } catch (SQLException e) { log.error("Error executing prepared statement.", e); } } } log.error("Fehlerhaftes Mapping: " + mapped); return 0; } /** * Remove all relations to this object from link * * @param field */ public void removeFromList(String field){ String mapped = map(field); if (mapped.startsWith("JOINT:")) { String[] m = mapped.split(":");// m[1] FremdID, m[2] eigene ID, m[3] // Name Joint if (m.length > 3) { StringBuilder sql = new StringBuilder(200); sql.append("DELETE FROM ").append(m[3]).append(" WHERE ").append(m[2]).append("=") .append(getWrappedId()); if (tracetable != null) { String sq = sql.toString(); doTrace(sq); } getConnection().exec(sql.toString()); return; } } log.error("Fehlerhaftes Mapping: " + mapped); } /** * Remove a relation to this object from link * * @param field * @param oID */ public void removeFromList(String field, String oID){ String mapped = map(field); String[] m = mapped.split(":"); if (mapped.startsWith("JOINT:")) { //m: m[1] FremdID, m[2] eigene ID, m[3] table if (m.length > 3) { StringBuilder sql = new StringBuilder(200); sql.append("DELETE FROM ").append(m[3]).append(" WHERE ").append(m[2]).append("=") .append(getWrappedId()).append(" AND ").append(m[1]).append("=") .append(JdbcLink.wrap(oID)); if (tracetable != null) { String sq = sql.toString(); doTrace(sq); } getConnection().exec(sql.toString()); return; } } else if (mapped.startsWith("LIST:")) { //m: m[1] FremdID, m[2] table if (m.length > 2) { try { String psString = "DELETE FROM " + m[2] + " WHERE " + m[1] + "= ? AND ID = ?;"; PreparedStatement ps = getConnection().getPreparedStatement(psString); ps = getConnection().getPreparedStatement(psString); ps.setString(1, getId()); ps.setString(2, oID); ps.executeUpdate(); getConnection().releasePreparedStatement(ps); } catch (SQLException e) { log.error("Error executing prepared statement.", e); } return; } } log.error("Fehlerhaftes Mapping: " + mapped); } /** * Ein neues Objekt erstellen und in die Datenbank eintragen * * @param customID * Wenn eine ID (muss eindeutig sein!) vorgegeben werden soll. Bei null wird eine * generiert. * @return true bei Erfolg */ protected boolean create(final String customID){ // String pattern=this.getClass().getSimpleName(); if (customID != null) { id = customID; } StringBuffer sql = new StringBuffer(300); sql.append("INSERT INTO ").append(getTableName()).append("(ID) VALUES (") .append(getWrappedId()).append(")"); if (getConnection().exec(sql.toString()) != 0) { setConstraint(); ElexisEventDispatcher.getInstance() .fire(new ElexisEvent(this, getClass(), ElexisEvent.EVENT_CREATE)); return true; } return false; } public boolean delete(){ if (set(FLD_DELETED, StringConstants.ONE)) { List<Xid> xids = new Query<Xid>(Xid.class, Xid.FLD_OBJECT, getId()).execute(); for (Xid xid : xids) { xid.delete(); } new DBLog(this, DBLog.TYP.DELETE); IPersistentObject sel = ElexisEventDispatcher.getSelected(this.getClass()); if ((sel != null) && sel.equals(this)) { ElexisEventDispatcher.clearSelection(this.getClass()); } ElexisEventDispatcher.getInstance().fire( new ElexisEvent(this, getClass(), ElexisEvent.EVENT_DELETE)); cache.remove(getKey(FLD_DELETED)); return true; } return false; } public boolean deleteList(final String field){ String mapped = map(field); if (!mapped.startsWith("JOINT:")) { ElexisStatus status = new ElexisStatus(ElexisStatus.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, "Feld " + field + " ist keine n:m Verknüpfung", null, ElexisStatus.LOG_ERRORS); ElexisEventDispatcher.fireElexisStatusEvent(status); return false; } String[] m = mapped.split(":");// m[1] FremdID, m[2] eigene ID, m[3] // Name Joint getConnection().exec("DELETE FROM " + m[3] + " WHERE " + m[2] + "=" + getWrappedId()); return true; } /** * We can undelete any object by simply clearing the deleted-flag and reanimate dependend XID's * * @return true on success */ public boolean undelete(){ if (set("deleted", "0")) { Query<Xid> qbe = new Query<Xid>(Xid.class); qbe.clear(true); qbe.add(Xid.FLD_OBJECT, Query.EQUALS, getId()); List<Xid> xids = qbe.execute(); for (Xid xid : xids) { xid.undelete(); } new DBLog(this, DBLog.TYP.UNDELETE); ElexisEventDispatcher.getInstance() .fire(new ElexisEvent(this, getClass(), ElexisEvent.EVENT_CREATE)); return true; } return false; } /** * Mehrere Felder auf einmal setzen (Effizienter als einzelnes set) * * @param fields * die Feldnamen * @param values * die Werte * @return false bei Fehler */ public boolean set(final String[] fields, final String... values){ if ((fields == null) || (values == null) || (fields.length != values.length)) { log.error("Falsche Felddefinition für set"); return false; } StringBuffer sql = new StringBuffer(200); sql.append("UPDATE ").append(getTableName()).append(" SET "); for (int i = 0; i < fields.length; i++) { String mapped = map(fields[i]); if (mapped.startsWith("S:")) { sql.append(mapped.substring(4)); } else { sql.append(mapped); } sql.append("=?,"); cache.put(getKey(fields[i]), values[i], getCacheTime()); } sql.append("lastupdate=?"); // sql.delete(sql.length() - 1, 100000); sql.append(" WHERE ID=").append(getWrappedId()); String cmd = sql.toString(); PreparedStatement pst = getConnection().getPreparedStatement(cmd); for (int i = 0; i < fields.length; i++) { encode(i + 1, pst, fields[i], values[i]); } if (tracetable != null) { StringBuffer params = new StringBuffer(); params.append("["); params.append(StringTool.join(values, ", ")); params.append("]"); doTrace(cmd + " " + params); } try { pst.setLong(fields.length + 1, System.currentTimeMillis()); pst.executeUpdate(); ElexisEventDispatcher.getInstance() .fire(new ElexisEvent(this, this.getClass(), ElexisEvent.EVENT_UPDATE)); return true; } catch (Exception ex) { ExHandler.handle(ex); StringBuilder sb = new StringBuilder(); sb.append("Fehler bei ").append(cmd).append("\nFelder:\n"); for (int i = 0; i < fields.length; i++) { sb.append(fields[i]).append("=").append(values[i]).append("\n"); } ElexisStatus status = new ElexisStatus(ElexisStatus.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, sb.toString(), ex, ElexisStatus.LOG_ERRORS); // DONT Throw an Exception. The API doc states: return false on // errors!! // throw new PersistenceException(status); return false; } finally { try { pst.close(); } catch (SQLException e) {} getConnection().releasePreparedStatement(pst); } } /** * @param checkNulls * wether the returned values should be <code>null</code> safe, that is no * <code>null</code> values, but only "" * @param fields * @return array containing the required fields in order * @since 3.1 */ public String[] get(boolean checkNulls, String... fields){ String[] ret = new String[fields.length]; get(fields, ret); if (checkNulls) { for (int i = 0; i < ret.length; i++) { ret[i] = checkNull(ret[i]); } } return ret; } /** * Read multiple fields, as defined in fields into the values array * * @param fields * the field to read * @param values * the storage array for the fields * @return true if values were set, else <code>false</code> and exception is created */ public boolean get(final String[] fields, final String[] values){ if ((fields == null) || (values == null) || (fields.length != values.length)) { log.error("Falscher Aufruf von get(String[],String[]"); return false; } StringBuffer sql = new StringBuffer(200); sql.append("SELECT "); boolean[] decode = new boolean[fields.length]; for (int i = 0; i < fields.length; i++) { String key = getKey(fields[i]); Object ret = cache.get(key, getCacheTime()); if (ret instanceof String) { values[i] = (String) ret; } else { String f1 = map(fields[i]); if (f1.startsWith("S:")) { sql.append(f1.substring(4)); decode[i] = true; } else { sql.append(f1); } sql.append(","); } } if (sql.length() < 8) { return true; } sql.delete(sql.length() - 1, 1000); sql.append(" FROM ").append(getTableName()).append(" WHERE ID=").append(getWrappedId()); Stm stm = getConnection().getStatement(); try (ResultSet rs = executeSqlQuery(sql.toString(), stm)) { if ((rs != null) && rs.next()) { for (int i = 0; i < values.length; i++) { if (values[i] == null) { if (decode[i] == true) { values[i] = decode(fields[i], rs); } else { values[i] = checkNull(rs.getString(map(fields[i]))); } cache.put(getKey(fields[i]), values[i], getCacheTime()); } } } return true; } catch (Exception ex) { ExHandler.handle(ex); return false; } finally { getConnection().releaseStatement(stm); } } /** * Apply some magic to the input parameters, and return a decoded string object. TODO describe * magic * * @param field * @param rs * @return decoded string or null if decode was not possible */ private String decode(final String field, final ResultSet rs){ try { String mapped = map(field); if (mapped.startsWith("S:")) { char mode = mapped.charAt(2); switch (mode) { case 'D': String dat = rs.getString(mapped.substring(4)); if (dat == null) { return ""; } TimeTool t = new TimeTool(); if (t.set(dat) == true) { return t.toString(TimeTool.DATE_GER); } else { return ""; } case 'N': int val = rs.getInt(mapped.substring(4)); return Integer.toString(val); case 'C': InputStream is = rs.getBinaryStream(mapped.substring(4)); if (is == null) { return ""; } byte[] exp = CompEx.expand(is); return StringTool.createString(exp); case 'V': byte[] in = rs.getBytes(mapped.substring(4)); VersionedResource vr = VersionedResource.load(in); return vr.getHead(); } } } catch (Exception ex) { log.error("Fehler bei decode ", ex); // Dont throw an exception. Null is an acceptable (and normally // testes) return value if something went wrong. // throw new PersistenceException(status); } return null; } private String encode(final int num, final PreparedStatement pst, final String field, final String value){ String mapped = map(field); String ret = value; try { if (mapped.startsWith("S:")) { String typ = mapped.substring(2, 3); mapped = mapped.substring(4); byte[] enc; if (typ.startsWith("D")) { // datum TimeTool t = new TimeTool(); if ((!StringTool.isNothing(value)) && (t.set(value) == true)) { ret = t.toString(TimeTool.DATE_COMPACT); pst.setString(num, ret); } else { ret = ""; pst.setString(num, ""); } } else if (typ.startsWith("C")) { // string enocding enc = CompEx.Compress(value, CompEx.ZIP); pst.setBytes(num, enc); } else if (typ.startsWith("N")) { // Number encoding pst.setInt(num, Integer.parseInt(value)); } else { log.error("Unbekannter encode code " + typ); } } else { pst.setString(num, value); } } catch (Exception ex) { ElexisStatus status = new ElexisStatus(ElexisStatus.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, "Fehler beim String encoder", ex, ElexisStatus.LOG_ERRORS); // Dont throw an exeption. returning the original value is an // acceptable way if encoding // is not possible. Frequently it's just // a configuration problem, so just log it and let the user decide // if they want to fix // it later. // DONT throw new PersistenceException(status); log.error("Fehler beim String encoder: " + ex.getMessage()); } return ret; } /** Strings must match exactly (but ignore case) */ public static final int MATCH_EXACT = 0; /** String must start with test (ignoring case) */ public static final int MATCH_START = 1; /** String must match as regular expression */ public static final int MATCH_REGEXP = 2; /** String must contain test (ignoring case) */ public static final int MATCH_CONTAINS = 3; /** * Try to find match method. * <ul> * <li>If test starts with % or * use MATCH_CONTAINS</li> * <li>If test is enclosed in / use MATCH_REGEXP</li> * </ul> * */ public static final int MATCH_AUTO = 4; public boolean isMatching(final IPersistentObject other, final int mode, final String... fields){ if (getClass().equals(other.getClass())) { String[] others = new String[fields.length]; other.get(fields, others); return isMatching(fields, mode, others); } return false; } public boolean isMatching(final String[] fields, final int mode, final String... others){ String[] mine = new String[fields.length]; get(fields, mine); for (int i = 0; i < fields.length; i++) { if (mine[i] == null) { if (others[i] == null) { return true; } return false; } if (others[i] == null) { return false; } switch (mode) { case MATCH_EXACT: if (!mine[i].toLowerCase().equals(others[i].toLowerCase())) { return false; } break; case MATCH_START: if (!mine[i].toLowerCase().startsWith(others[i].toLowerCase())) { return false; } break; case MATCH_REGEXP: if (!mine[i].matches(others[i])) { return false; } case MATCH_CONTAINS: if (!mine[i].toLowerCase().contains(others[i].toLowerCase())) { return false; } } } return true; } public boolean isMatching(final Map<String, String> fields, final int mode, final boolean bSkipInexisting){ for (Entry<String, String> entry : fields.entrySet()) { String mine = get(entry.getKey()); String others = entry.getValue(); if (bSkipInexisting) { if (mine.startsWith(MAPPING_ERROR_MARKER) || others.startsWith(MAPPING_ERROR_MARKER)) { continue; } } switch (mode) { case MATCH_EXACT: if (!mine.toLowerCase().equals(others.toLowerCase())) { return false; } break; case MATCH_START: if (!mine.toLowerCase().startsWith(others.toLowerCase())) { return false; } break; case MATCH_REGEXP: if (!mine.matches(others)) { return false; } case MATCH_CONTAINS: if (!mine.toLowerCase().contains(others.toLowerCase())) { return false; } case MATCH_AUTO: String my = mine.toLowerCase(); if (others.startsWith("%") || others.startsWith("*")) { if (!my.contains(others.substring(1).toLowerCase())) { return false; } } else { if (!my.startsWith(others.toLowerCase())) { return false; } } } } return true; } /** * Get a unique key for a value, suitable for identifying a key in a cache. The current * implementation uses the table name, the id of the PersistentObject and the field name. * * @param field * the field to get a key for * @return a unique key */ private String getKey(final String field){ return getTableName() + "." + getId() + "#" + field; } /** * Verbindung zur Datenbank trennen * */ public static void disconnect(){ if (getConnection() != null) { if (getConnection().DBFlavor.startsWith("hsqldb")) { getConnection().exec("SHUTDOWN COMPACT"); } getConnection().disconnect(); j = null; log.info("Verbindung zur Datenbank getrennt."); if (runFromScratchDB != null) { File dbFile = new File(runFromScratchDB.getAbsolutePath() + ".h2.db"); log.info("Deleting runFromScratchDB was " + runFromScratchDB + " and " + dbFile); dbFile.delete(); runFromScratchDB.delete(); } cache.stat(); } } @Override public boolean equals(final Object arg0){ if (arg0 instanceof PersistentObject) { return getId().equals(((PersistentObject) arg0).getId()); } return false; } /** * Return a String field making sure that it will never be null * * @param in * name of the field to retrieve * @return the field contents or "" if it was null */ public static String checkNull(final Object in){ if (in == null) { return ""; } if (!(in instanceof String)) { return ""; } return (String) in; } public static int checkZero(final Object in){ if (StringTool.isNothing(in)) { return 0; } try { return Integer.parseInt(((String) in).trim()); // We're sure in is a // String at this // point } catch (NumberFormatException ex) { ExHandler.handle(ex); return 0; } } public static double checkZeroDouble(final String in){ if (StringTool.isNothing(in)) { return 0.0; } try { return Double.parseDouble(in.trim()); } catch (NumberFormatException ex) { ExHandler.handle(ex); return 0.0; } } /** * return the time of the last update of this object * * @return the time (as given in System.currentTimeMillis()) of the last write operation on this * object or 0 if there was no valid lastupdate time */ public long getLastUpdate(){ try { return Long.parseLong(get("lastupdate")); } catch (Exception ex) { // ExHandler.handle(ex); return 0L; } } @Override public int hashCode(){ return getId().hashCode(); } public static void clearCache(){ synchronized (cache) { cache.clear(); } } public static void resetCache(){ synchronized (cache) { cache.reset(); } } /** * Return time-to-live in cache for this object * * @return the time in seconds */ public int getCacheTime(){ return default_lifetime; } public static void setDefaultCacheLifetime(int seconds){ default_lifetime = seconds; } public static int getDefaultCacheLifetime(){ return default_lifetime; } /** * Utility function to create or modify a table consistently. Should be used by all plugins that * contribute data types derived from PersistentObject * * @param sqlScript * create string */ protected static void createOrModifyTable(final String sqlScript){ String[] sql = new String[1]; sql[0] = sqlScript; SqlRunner runner = new SqlRunner(sql, CoreHub.PLUGIN_ID); runner.runSql(); } /** * public helper to execute an sql script iven as file path. SQL Errors will be * handeld/displayed by SqlWithUiRunner * * @param filepath * where the script is * @param plugin * name of the originating plugin * @throws IOException * file not found or not readable */ public static void executeSQLScript(String filepath, String plugin) throws IOException{ FileInputStream is = new FileInputStream(filepath); InputStreamReader isr = new InputStreamReader(is); char[] buf = new char[4096]; int l = 0; StringBuilder sb = new StringBuilder(); while ((l = isr.read(buf)) > 0) { sb.append(buf, 0, l); } new SqlRunner(new String[] { sb.toString() }, plugin).runSql(); } protected static boolean executeScript(final String pathname){ Stm stm = getConnection().getStatement(); try { FileInputStream is = new FileInputStream(pathname); return stm.execScript(is, true, true); } catch (Exception ex) { ExHandler.handle(ex); return false; } finally { getConnection().releaseStatement(stm); } } /** * Utility function to remove a table and all objects defined therein consistentliy To make sure * dependent data are deleted as well, we call each object's delete operator individually before * dropping the table * * @param name * the name of the table */ @SuppressWarnings({ "unchecked", "rawtypes" }) protected static void removeTable(final String name, final Class oclas){ Query qbe = new Query(oclas); for (Object o : qbe.execute()) { ((PersistentObject) o).delete(); } getConnection().exec("DROP TABLE " + name); } /** * Convert a Hashtable into a compressed byte array. Note: the resulting array is java-specific, * but stable through jre Versions (serialVersionUID: 1421746759512286392L) * * @param hash * the hashtable to store * @return */ @SuppressWarnings("unchecked") public static byte[] flatten(final Hashtable hash){ return flattenObject(hash); } /** * * @param object * @return * @since 3.1 */ public static byte[] flattenObject(final Object object){ try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); zos.putNextEntry(new ZipEntry("hash")); ObjectOutputStream oos = new ObjectOutputStream(zos); oos.writeObject(object); zos.close(); baos.close(); return baos.toByteArray(); } catch (Exception ex) { ExHandler.handle(ex); return null; } } @SuppressWarnings("unchecked") public static Hashtable<Object, Object> fold(final byte[] flat){ return (Hashtable<Object, Object>) foldObject(flat); } /** * * @param flat * @return * @since 3.1 */ public static Object foldObject(final byte[] flat){ try { ByteArrayInputStream bais = new ByteArrayInputStream(flat); ZipInputStream zis = new ZipInputStream(bais); zis.getNextEntry(); ObjectInputStream ois = new ObjectInputStream(zis); Object res = ois.readObject(); ois.close(); bais.close(); return res; } catch (Exception ex) { log.error("Error unfolding object", ex); return null; } } /** * Returns array of field names of the database fields.<br> * Used for export functionality */ protected String[] getExportFields(){ try { ResultSet res = getConnection().getStatement().query("Select count(id) from " + getTableName()); ResultSetMetaData rmd = res.getMetaData(); String[] ret = new String[rmd.getColumnCount()]; for (int i = 0; i < ret.length; i++) { ret[i] = rmd.getColumnName(i + 1); } return ret; } catch (Exception ex) { ExHandler.handle(ex); return null; } } /** * Returns uid value. The uid should be world wide universal.<br> * If this code changes, then the method getExportUIDVersion has to be overwritten<br> * and the returned value incremented. * */ protected String getExportUIDValue(){ throw new IllegalArgumentException( "No export uid value for " + getClass().getSimpleName() + " available"); } /** * Checks the version of the export functionality. If the method<br> * getExportUIDValue() changes, this method should return a new number.<br> */ protected String getExportUIDVersion(){ return "1"; } /** * Exports a persistentobject to an xml string * * @return */ public String exportData(){ return XML2Database.exportData(this); } /** * Execute the sql string and handle exceptions appropriately. * <p> * <b>ATTENTION:</b> JdbcLinkResourceException will trigger a restart of Elexis in * at.medevit.medelexis.ui.statushandler. * </p> * * @param sql * @return */ private ResultSet executeSqlQuery(String sql, Stm stm){ ResultSet res = null; try { res = stm.query(sql); } catch (JdbcLinkException je) { ElexisStatus status = translateJdbcException(je); // trigger restart for severe communication error if (je instanceof JdbcLinkResourceException) { status.setCode(ElexisStatus.CODE_RESTART | ElexisStatus.CODE_NOFEEDBACK); status.setMessage(status.getMessage() + "\nACHTUNG: Elexis wird neu gestarted!\n"); status.setLogLevel(ElexisStatus.LOG_FATALS); // TODO throw PersistenceException to UI code ... // calling StatusManager directly here was not intended, // but throwing the exception without handling it apropreately // in the UI code makes it impossible for the status handler // to display a blocking error dialog // (this is executed in a Runnable where Exception handling is // not blocking UI // thread) ElexisEventDispatcher.fireElexisStatusEvent(status); } else { status.setLogLevel(ElexisStatus.LOG_FATALS); throw new PersistenceException(status); } } return res; } private static ElexisStatus translateJdbcException(JdbcLinkException jdbc){ if (jdbc instanceof JdbcLinkSyntaxException) { return new ElexisStatus(ElexisStatus.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, "Fehler in der Datenbanksyntax.", jdbc, ElexisStatus.LOG_ERRORS); } else if (jdbc instanceof JdbcLinkConcurrencyException) { return new ElexisStatus(ElexisStatus.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, "Fehler bei einer Datenbanktransaktion.", jdbc, ElexisStatus.LOG_ERRORS); } else if (jdbc instanceof JdbcLinkResourceException) { return new ElexisStatus(ElexisStatus.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, "Fehler bei der Datenbankkommunikation.", jdbc, ElexisStatus.LOG_ERRORS); } else { return new ElexisStatus(ElexisStatus.ERROR, CoreHub.PLUGIN_ID, ElexisStatus.CODE_NONE, "Fehler in der Datenbankschnittstelle.", jdbc, ElexisStatus.LOG_ERRORS); } } /** * Utility procedure for unit tests which need to start with a clean database */ public static boolean deleteAllTables(){ int nrTables = 0; String tableName = "none"; DatabaseMetaData dmd; Connection conn = null; try { conn = j.getConnection(); dmd = conn.getMetaData(); // we drop views before dropping the tables ResultSet rsViews = dmd.getTables(null, null, "%", new String[] { "VIEW" }); if (rsViews != null) { while (rsViews.next()) { // DatabaseMetaData#getTables() specifies TABLE_NAME is in // column 3 tableName = rsViews.getString(3); getConnection().exec("DROP VIEW " + tableName); nrTables++; } } ResultSet rsTables = dmd.getTables(null, null, "%", new String[] { "TABLE" }); if (rsTables != null) { while (rsTables.next()) { // DatabaseMetaData#getTables() specifies TABLE_NAME is in // column 3 tableName = rsTables.getString(3); getConnection().exec("DROP TABLE " + tableName); nrTables++; } } } catch (SQLException e1) { log.error("Error deleting table " + tableName); return false; } finally { try { if (conn != null) { conn.close(); } } catch (SQLException e) { log.error("Error closing connection" + e); } } log.info("Deleted " + nrTables + " tables"); return true; } public static boolean tableExistsSelect(String tableName){ try { getConnection().exec("SELECT 1 FROM " + tableName); return true; } catch (Exception e) { return false; } } /** * Utility procedure * * @param tableName * name of the table to check existence for */ public static boolean tableExists(String tableName){ int nrFounds = 0; // Vergleich schaut nicht auf Gross/Klein-Schreibung, da thomas // schon H2-DB gesehen hat, wo entweder alles gross oder alles klein war Connection conn = null; try { conn = j.getConnection(); DatabaseMetaData dmd = conn.getMetaData(); String[] onlyTables = { "TABLE" }; ResultSet rs = dmd.getTables(null, null, "%", onlyTables); if (rs != null) { while (rs.next()) { // DatabaseMetaData#getTables() specifies TABLE_NAME is in // column 3 if (rs.getString(3).equalsIgnoreCase(tableName)) nrFounds++; } } } catch (SQLException je) { log.error("Fehler beim abrufen der Datenbank Tabellen Information.", je); } finally { try { if (conn != null) { conn.close(); } } catch (SQLException e) { log.error("Error closing connection " + e); } } if (nrFounds > 1) { // Dies kann vorkommen, wenn man eine MySQL-datenbank von Windows -> // Linuz kopiert // und dort nicht die System-Variable lower_case_table_names nicht // gesetzt ist // Anmerkung von Niklaus Giger log.error("Tabelle " + tableName + " " + nrFounds + "-mal gefunden!!"); } return nrFounds == 1; } /** * Convert an arbitrary value into the database format * * @author Marco Descher * @since 2.1.6 * @since 3.1 supports {@link List}; will be returned as comma-separated-values * @param in * {@link Object} * @return String representing the value in database storage conform format */ public static String ts(Object in){ if (in == null) return ""; if (in instanceof String) return (String) in; if (in instanceof Boolean) { return ((Boolean) in) ? StringConstants.ONE : StringConstants.ZERO; } if (in instanceof Long) return Long.toString((Long) in); if (in instanceof Integer) return Integer.toString((Integer) in); if (in instanceof Double) return Double.toString((Double) in); if (in instanceof Date) { return new SimpleDateFormat("dd.MM.yyyy").format((Date) in); } if (in instanceof XMLGregorianCalendar) { XMLGregorianCalendar dt = (XMLGregorianCalendar) in; return new SimpleDateFormat("dd.MM.yyyy").format(dt.toGregorianCalendar().getTime()); } if (in instanceof List) { List<?> inList = (List<?>) in; return (String) inList.stream().map(o -> o.toString()) .reduce((u, t) -> u + StringConstants.COMMA + t).get(); } return ""; } public void addChangeListener(IChangeListener listener, String fieldToObserve){ } public void removeChangeListener(IChangeListener listener, String fieldObserved){ } /** * put the value into the cache, will use the cache time as delievered by * {@link PersistentObject#getCacheTime()} * * @param field * name, must map to a database column, see {@link PersistentObject#map(String)} * @param value * the value to cache * @since 3.1 */ public void putInCache(String field, Object value){ String key = getKey(field); if (value == null) value = ""; cache.put(key, value, getCacheTime()); } /** * * @param clazz * @since 3.1 */ public static void executeDBInitScriptForClass(Class<?> clazz, @Nullable VersionInfo vi){ String resourceName = "/rsc/dbScripts/" + clazz.getName(); if (vi == null) { resourceName += ".sql"; } else { resourceName += "_" + vi.version() + ".sql"; } Stm stm = getConnection().getStatement(); try (InputStream is = PersistentObject.class.getResourceAsStream(resourceName)) { boolean result = stm.execScript(is, true, true); if (!result) { log.warn("Error in executing script from " + resourceName); } } catch (IOException e) { log.error("Error executing script from " + resourceName, e); } finally { getConnection().releaseStatement(stm); } } }
package ru.job4j.monitore; import net.jcip.annotations.GuardedBy; import net.jcip.annotations.ThreadSafe; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; /** * class UserStorage. */ @ThreadSafe public class UserStorage { /** storage to keep users.*/ @GuardedBy("this") private TreeMap<Integer, User> storage = new TreeMap<>(); /** * method add. * @param user - user. */ public void add(User user) { synchronized (this) { storage.put(user.getId(), user); } } /** * method delete. * @param id - id. */ public void delete(int id) { synchronized (this) { storage.remove(id); } } /** * method findUser. * @param id - id. * @return user. */ public User findUser(int id) { synchronized (this) { return storage.get(id); } } /** * method upDate. * @param user - user. * @return boolean. */ public boolean upDate(User user) { synchronized (this) { boolean result = false; if (storage.containsKey(user.getId())) { add(user); result = true; } return result; } } /** * method transfer. * @param idFrom - id user from. * @param idTo - id user to. * @param value - value. * @return boolean. */ public boolean transfer(int idFrom, int idTo, int value) { synchronized (this) { boolean result = false; User userFrom = storage.get(idFrom); User userTo = storage.get(idTo); if (userFrom != null && userTo != null) { if (userFrom.takeValue(value)) { result = userTo.addValue(value); } } return result; } } /** * method toString. * @return string. */ @Override public String toString() { StringBuilder str = new StringBuilder(); for (Map.Entry<Integer, User> entry : storage.entrySet()) { str.append(entry.getValue()).append("\n"); } return str.toString(); } }
package org.inventivetalent.npclib; import com.google.common.base.Strings; import com.google.common.collect.Maps; import lombok.Getter; import org.bukkit.entity.EntityType; import org.inventivetalent.npclib.npc.NPCAbstract; import org.inventivetalent.npclib.npc.NPCExperienceOrb; import org.inventivetalent.npclib.npc.NPCItem; import org.inventivetalent.npclib.npc.living.NPCArmorStand; import org.inventivetalent.npclib.npc.living.insentient.NPCEnderDragon; import org.inventivetalent.npclib.npc.living.insentient.NPCPigZombie; import org.inventivetalent.npclib.npc.living.insentient.NPCSlime; import org.inventivetalent.npclib.npc.living.insentient.NPCZombie; import org.inventivetalent.npclib.npc.living.insentient.creature.ageable.NPCVillager; import org.inventivetalent.npclib.npc.living.insentient.creature.ageable.animal.*; import org.inventivetalent.npclib.npc.living.insentient.creature.ageable.animal.tameable.NPCOcelot; import org.inventivetalent.npclib.npc.living.insentient.creature.ageable.animal.tameable.NPCWolf; import org.inventivetalent.npclib.npc.living.insentient.creature.golem.NPCIronGolem; import org.inventivetalent.npclib.npc.living.insentient.creature.golem.NPCShulker; import org.inventivetalent.npclib.npc.living.insentient.creature.golem.NPCSnowman; import org.inventivetalent.npclib.npc.living.insentient.creature.monster.*; import org.inventivetalent.npclib.npc.living.insentient.flying.NPCGhast; import org.inventivetalent.npclib.npc.living.insentient.water.NPCSquid; import java.util.Map; import static com.google.common.base.Preconditions.checkNotNull; public enum NPCType { DROPPED_ITEM(EntityType.DROPPED_ITEM, NPCItem.class), EXPERIENCE_ORB(EntityType.EXPERIENCE_ORB, NPCExperienceOrb.class), // LEASH_KNOT(EntityType.LEASH_HITCH, NPCLeashKnot.class), // PAINTING(EntityType.PAINTING,NPCPainting.class), // ARROW(EntityType.ARROW,NPCArrow.class), // SNOWBALL(EntityType.SNOWBALL,NPCSnowball.class), // LARGE_FIREBALL(EntityType.FIREBALL,NPCLargeFireball.class), // SMALL_FIREBALL(EntityType.SMALL_FIREBALL,NPCSmallFireball.class), // ENDER_PEARL(EntityType.ENDER_PEARL,NPCEnderPearl.class), // ENDER_SIGNAL(EntityType.ENDER_SIGNAL,NPCEnderSignal.class), // THROWN_EXP_BOTTLE(EntityType.THROWN_EXP_BOTTLE,NPCExpBottle.class), // ITEM_FRAME(EntityType.ITEM_FRAME,NPCItemFrame.class), // WITHER_SKULL(EntityType.WITHER_SKULL,NPCWitherSkull.class), // PRIMED_TNT(EntityType.PRIMED_TNT,NPCPrimedTnt.class), // FALLING_BLOCK(EntityType.FALLING_BLOCK,NPCFallingBlock.class), // FIREWORK(EntityType.FIREWORK,NPCFirework.class), // TIPPED_ARROW(EntityType.TIPPED_ARROW,NPCTippedArrow.class), // SPECTRAL_ARROW(EntityType.SPECTRAL_ARROW,NPCSpectralArrow.class), // SHULKER_BULLET(EntityType.SHULKER_BULLET,NPCShulkerBullet.class), // DRAGON_FIREBALL(EntityType.DRAGON_FIREBALL,NPCDragonFireball.class), ARMOR_STAND(EntityType.ARMOR_STAND, NPCArmorStand.class), // MINECART_COMMAND(EntityType.MINECART_COMMAND,NPCMinecartCommand.class), // BOAT(EntityType.BOAT,NPCBoat.class), // MINECART_RIDEABLE(EntityType.MINECART,NPCMinecartRideable.class), // MINECART_CHEST(EntityType.MINECART_CHEST,NPCMinecartChest.class), // MINECART_FURNACE(EntityType.MINECART_FURNACE,NPCMinecartFurnace.class), // MINECART_TNT(EntityType.MINECART_TNT,NPCMinecartTnt.class), // MINECART_HOPPER(EntityType.MINECART_HOPPER,NPCMinecartHopper.class), // MINECART_MOB_SPAWNER(EntityType.MINECART_MOB_SPAWNER,NPCMinecartMobSpawner.class), CREEPER(EntityType.CREEPER, NPCCreeper.class), SKELETON(EntityType.SKELETON, NPCSkeleton.class), SPIDER(EntityType.SPIDER, NPCSpider.class), GIANT(EntityType.GIANT, NPCGiant.class), ZOMBIE(EntityType.ZOMBIE, NPCZombie.class), SLIME(EntityType.SLIME, NPCSlime.class), GHAST(EntityType.GHAST, NPCGhast.class), PIG_ZOMBIE(EntityType.PIG_ZOMBIE, NPCPigZombie.class), ENDERMAN(EntityType.ENDERMAN, NPCEnderman.class), CAVE_SPIDER(EntityType.CAVE_SPIDER, NPCCaveSpider.class), // SILVERFISH(EntityType.SILVERFISH, NPCSilverfish.class), // BLAZE(EntityType.BLAZE, NPCBlaze.class), // MAGMA_CUBE(EntityType.MAGMA_CUBE, NPCMagmaCube.class), ENDER_DRAGON(EntityType.ENDER_DRAGON, NPCEnderDragon.class), WITHER(EntityType.WITHER, NPCWither.class), // BAT(EntityType.BAT, NPCBat.class), WITCH(EntityType.WITCH, NPCWitch.class), ENDERMITE(EntityType.ENDERMITE, NPCEndermite.class), GUARDIAN(EntityType.GUARDIAN, NPCGuardian.class), SHULKER(EntityType.SHULKER, NPCShulker.class), PIG(EntityType.PIG, NPCPig.class), SHEEP(EntityType.SHEEP, NPCSheep.class), COW(EntityType.COW, NPCCow.class), CHICKEN(EntityType.CHICKEN, NPCChicken.class), SQUID(EntityType.SQUID, NPCSquid.class), WOLF(EntityType.WOLF, NPCWolf.class), MUSHROOM_COW(EntityType.MUSHROOM_COW, NPCMushroomCow.class), SNOWMAN(EntityType.SNOWMAN, NPCSnowman.class), OCELOT(EntityType.OCELOT, NPCOcelot.class), IRON_GOLEM(EntityType.IRON_GOLEM, NPCIronGolem.class), HORSE(EntityType.HORSE, NPCHorse.class), RABBIT(EntityType.RABBIT, NPCRabbit.class), POLAR_BEAR(EntityType.POLAR_BEAR, NPCPolarBear.class), VILLAGER(EntityType.VILLAGER, NPCVillager.class), // ENDER_CRYSTAL(EntityType.ENDER_CRYSTAL,NPCEnderCrystal.class), ; private static final Map<EntityType, NPCType> entityTypeMap = Maps.newHashMap(); private static final Map<Class<? extends NPCAbstract>, NPCType> classMap = Maps.newHashMap(); static { for (NPCType npcType : values()) { entityTypeMap.put(npcType.entityType, npcType); classMap.put(npcType.npcClass, npcType); } } @Getter private final EntityType entityType; @Getter private Class<? extends NPCAbstract> npcClass; NPCType(EntityType entityType, Class<? extends NPCAbstract> npcClass) { this.entityType = entityType; this.npcClass = npcClass; } public static NPCType forEntityType(EntityType entityType) { return entityTypeMap.get(checkNotNull(entityType)); } public static NPCType fromString(String string) { if (Strings.isNullOrEmpty(string)) { return null; } NPCType type; if ((type = valueOfOrNull(string.toUpperCase())) != null) { return type; } if ((type = valueOfOrNull(string.toUpperCase().replace(" ", "_"))) != null) { return type; } if ((type = valueOfOrNull(string.toUpperCase().replaceAll("\\s", ""))) != null) { return type; } for (NPCType npcType : values()) { String combined = npcType.name().replace("_", ""); if (combined.equals(string.toUpperCase())) { return npcType; } } return null; } private static NPCType valueOfOrNull(String string) { try { return valueOf(string); } catch (IllegalArgumentException e) { return null; } } }
package de.devboost.featuremapper.splevo.builder.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.LinkedList; import java.util.List; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.common.util.URI; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.resource.Resource; import org.eclipse.emf.ecore.resource.impl.ResourceImpl; import org.emftext.language.java.classifiers.Class; import org.emftext.language.java.classifiers.ClassifiersFactory; import org.featuremapper.models.feature.Feature; import org.featuremapper.models.feature.FeatureModel; import org.featuremapper.models.featuremapping.ElementMapping; import org.featuremapper.models.featuremapping.FeatureMappingModel; import org.featuremapper.models.featuremapping.FeatureRef; import org.featuremapper.models.featuremapping.Mapping; import org.featuremapper.models.featuremapping.SolutionModelRef; import org.splevo.fm.builder.FeatureModelWrapper; import org.splevo.jamopp.vpm.software.JaMoPPSoftwareElement; import org.splevo.jamopp.vpm.software.softwareFactory; import org.splevo.vpm.variability.Variant; import org.splevo.vpm.variability.VariationPoint; import org.splevo.vpm.variability.VariationPointGroup; import org.splevo.vpm.variability.VariationPointModel; import org.splevo.vpm.variability.variabilityFactory; import com.google.common.base.Joiner; import com.google.common.base.Splitter; import de.devboost.featuremapper.splevo.builder.FeatureMapperModelSet; import de.devboost.featuremapper.splevo.builder.FeatureMapperModelsBuilder; import de.devboost.natspec.annotations.TextSyntax; // CHECKSTYLE:OFF public class FeatureMapperBuilderTestSupport { private variabilityFactory factory = variabilityFactory.eINSTANCE; @TextSyntax(" public void matchAllPattern(List<String> words) { System.out.println(Joiner.on(" ").join(words)); } @TextSyntax("If there is for example a variation point model named public VariationPointModel forAnExampleVariationPointModelNamed(String VPM1) { VariationPointModel vpm; vpm = factory.createVariationPointModel(); return vpm; } @TextSyntax("With a variation point public VariationPoint withAVariationPointGroupThatHasVariationsAnd( String pointName, VariationPointModel vpm) { VariationPointGroup vpg = factory.createVariationPointGroup(); vpg.setName(pointName); vpm.getVariationPointGroups().add(vpg); EList<VariationPoint> variationPoints = vpg.getVariationPoints(); VariationPoint vpa = factory.createVariationPoint(); vpa.setRefactored(true); variationPoints.add(vpa); return vpa; } @TextSyntax("That has a variant #1 mapped to class #2 in resource #3") public void thatHasVariationMappedToClass(String variantName, String exampleClassName, String resourceName, VariationPoint point) { Variant aVariant = factory.createVariant(); aVariant.setId(variantName); JaMoPPSoftwareElement softwareEntity = softwareFactory.eINSTANCE .createJaMoPPSoftwareElement(); Class jamoppClass = ClassifiersFactory.eINSTANCE.createClass(); jamoppClass.setName(exampleClassName); Resource res = new ResourceImpl(); URI uri = URI.createURI(resourceName); res.setURI(uri); res.getContents().add(jamoppClass); softwareEntity.setJamoppElement(jamoppClass); aVariant.getImplementingElements().add(softwareEntity); // variantToEntityMap.put(variantA.getVariantId(), jamoppClass); point.getVariants().add(aVariant); } @TextSyntax("Then the FeatureMapper Models Builder generates") public FeatureMapperModelSet theModelsBuilderWillGenerate( VariationPointModel vpm) { // we use a test mock of the FeatureMapperModelsBuilder here, to avoid dependency on eclipse workspace FeatureMapperModelsBuilder builder = new FeatureMapperModelsBuilderMock(); FeatureModelWrapper<FeatureMapperModelSet> fmWrapper = builder.build(vpm, "RootFeature"); FeatureMapperModelSet featureModelSet = fmWrapper.getModel(); return featureModelSet; } @TextSyntax("A Feature Model") public FeatureModel aFeatureModel(FeatureMapperModelSet set) { FeatureModel featureModel = set.getFeatureModel(); assertNotNull(featureModel); return featureModel; } @TextSyntax("A Mapping Model") public FeatureMappingModel MappingModel(FeatureMapperModelSet set) { FeatureMappingModel mappingModel = set.getMappingModel(); assertNotNull(mappingModel); return mappingModel; } @TextSyntax("With a root feature public Feature withARootFeature(String rootFeatureName, FeatureModel model) { String foundName = model.getRoot().getName(); assertEquals(rootFeatureName, foundName); return model.getRoot(); } @TextSyntax("With #1 child features named #2") public void withChildFeaturesNamed(int childSize, List<String> childNames, Feature feature) { Iterable<String> childNamesFiltered = Splitter.on(" and ").split( Joiner.on(" ").join(childNames)); EList<Feature> childFeatures = feature.getGroups().get(0) .getChildFeatures(); assertEquals(childSize, childFeatures.size()); List<String> foundChilds = new LinkedList<String>(); for (Feature f : childFeatures) { String name = f.getName(); foundChilds.add(name); } for (String expectedChild : childNamesFiltered) { assertTrue("Expected child " + expectedChild, foundChilds.contains(expectedChild)); } } @TextSyntax("With feature #1 that contains #2 child features named #3") public void withFeatureThatContainsChildFeaturesNamedAnd( String featurename, int childSize, List<String> childNames, FeatureModel model) { EList<Feature> allFeatures = model.getAllFeatures(); Feature parentFeature = null; for (Feature feature : allFeatures) { if (feature.getName().equals(featurename)) { parentFeature = feature; break; } } assertNotNull(parentFeature); withChildFeaturesNamed(childSize, childNames, parentFeature); } @TextSyntax("With a mapping of feature #1 to #2") public void withAMappingOfFeatureTo(String featureName, String artifactName, FeatureMappingModel mappingModel) { for (Mapping mapping : mappingModel.getMappings()) { if (!(mapping instanceof ElementMapping)) { continue; } ElementMapping em = (ElementMapping) mapping; assertTrue(em.getTerm() instanceof FeatureRef); FeatureRef featureRef = (FeatureRef) em.getTerm(); String featureNameFound = featureRef.getFeature().getName(); if (featureNameFound.equals(featureName)) { EObject element = em.getElement(); assertEquals(artifactName, ((Class) element).getName()); return; } } fail("No mapping found for feature " + featureName); } @TextSyntax("With solution space model public void withSolutionSpaceModel(String resourceName, FeatureMappingModel model) { EList<SolutionModelRef> solutionModels = model.getSolutionModels(); assertTrue("No solution space models set.", solutionModels.size() > 0); for (SolutionModelRef solutionModelRef : solutionModels) { Class jamoppClass = (Class) solutionModelRef.getValue(); if (jamoppClass.eResource().getURI().toString().equals(resourceName)) { return; // correct resource found. } } fail("Could not find solution space model: " + resourceName); } }
package dr.app.beagle.evomodel.parsers; //import dr.app.beagle.evomodel.treelikelihood.RestrictedPartialsSequenceLikelihood; import dr.app.beagle.evomodel.substmodel.FrequencyModel; import dr.evolution.alignment.PatternList; import dr.evolution.alignment.Patterns; import dr.evolution.alignment.SitePatterns; import dr.app.beagle.evomodel.sitemodel.BranchSiteModel; import dr.app.beagle.evomodel.sitemodel.GammaSiteRateModel; import dr.app.beagle.evomodel.sitemodel.HomogenousBranchSiteModel; import dr.app.beagle.evomodel.treelikelihood.BeagleTreeLikelihood; import dr.app.beagle.evomodel.treelikelihood.PartialsRescalingScheme; import dr.evolution.tree.Tree; import dr.evolution.util.TaxonList; import dr.evomodel.branchratemodel.BranchRateModel; import dr.evomodel.newtreelikelihood.TreeLikelihood; import dr.evomodel.tree.TreeModel; import dr.inference.model.Likelihood; import dr.inference.model.CompoundLikelihood; import dr.inference.model.Parameter; import dr.xml.*; import java.util.*; /** * @author Andrew Rambaut * @author Alexei Drummond * @author Marc Suchard * @version $Id$ */ public class TreeLikelihoodParser extends AbstractXMLObjectParser { public static final String BEAGLE_INSTANCE_COUNT = "beagle.instance.count"; public static final String TREE_LIKELIHOOD = TreeLikelihood.TREE_LIKELIHOOD; public static final String USE_AMBIGUITIES = "useAmbiguities"; public static final String INSTANCE_COUNT = "instanceCount"; // public static final String DEVICE_NUMBER = "deviceNumber"; // public static final String PREFER_SINGLE_PRECISION = "preferSinglePrecision"; public static final String SCALING_SCHEME = "scalingScheme"; public static final String PARTIALS_RESTRICTION = "partialsRestriction"; public String getParserName() { return TREE_LIKELIHOOD; } protected BeagleTreeLikelihood createTreeLikelihood(PatternList patternList, TreeModel treeModel, BranchSiteModel branchSiteModel, GammaSiteRateModel siteRateModel, BranchRateModel branchRateModel, boolean useAmbiguities, PartialsRescalingScheme scalingScheme, Map<Set<String>, Parameter> partialsRestrictions, XMLObject xo) throws XMLParseException { return new BeagleTreeLikelihood( patternList, treeModel, branchSiteModel, siteRateModel, branchRateModel, useAmbiguities, scalingScheme, partialsRestrictions ); } public Object parseXMLObject(XMLObject xo) throws XMLParseException { boolean useAmbiguities = xo.getAttribute(USE_AMBIGUITIES, false); int instanceCount = xo.getAttribute(INSTANCE_COUNT, 1); if (instanceCount < 1) { instanceCount = 1; } String ic = System.getProperty(BEAGLE_INSTANCE_COUNT); if (ic != null && ic.length() > 0) { instanceCount = Integer.parseInt(ic); } PatternList patternList = (PatternList) xo.getChild(PatternList.class); TreeModel treeModel = (TreeModel) xo.getChild(TreeModel.class); GammaSiteRateModel siteRateModel = (GammaSiteRateModel) xo.getChild(GammaSiteRateModel.class); FrequencyModel rootFreqModel = (FrequencyModel) xo.getChild(FrequencyModel.class); BranchSiteModel branchSiteModel = new HomogenousBranchSiteModel( siteRateModel.getSubstitutionModel(), (rootFreqModel != null ? rootFreqModel : siteRateModel.getSubstitutionModel().getFrequencyModel()) ); BranchRateModel branchRateModel = (BranchRateModel) xo.getChild(BranchRateModel.class); PartialsRescalingScheme scalingScheme = PartialsRescalingScheme.DEFAULT; if (xo.hasAttribute(SCALING_SCHEME)) { scalingScheme = PartialsRescalingScheme.parseFromString(xo.getStringAttribute(SCALING_SCHEME)); if (scalingScheme == null) throw new XMLParseException("Unknown scaling scheme '"+xo.getStringAttribute(SCALING_SCHEME)+"' in "+ "BeagleTreeLikelihood object '"+xo.getId()); } Map<Set<String>, Parameter> partialsRestrictions = null; if (xo.hasChildNamed(PARTIALS_RESTRICTION)) { XMLObject cxo = (XMLObject) xo.getChild(PARTIALS_RESTRICTION); TaxonList taxonList = (TaxonList) cxo.getChild(TaxonList.class); Parameter parameter = (Parameter) cxo.getChild(Parameter.class); try { Tree.Utils.getLeavesForTaxa(treeModel, taxonList); } catch (Tree.MissingTaxonException e) { throw new XMLParseException("Unable to parse taxon list: " + e.getMessage()); } throw new XMLParseException("Restricting internal nodes is not yet implemented. Contact Marc"); } if (instanceCount == 1 || patternList.getPatternCount() < instanceCount) { return createTreeLikelihood( patternList, treeModel, branchSiteModel, siteRateModel, branchRateModel, useAmbiguities, scalingScheme, partialsRestrictions, xo ); } List<Likelihood> likelihoods = new ArrayList<Likelihood>(); for (int i = 0; i < instanceCount; i++) { Patterns subPatterns = new Patterns((SitePatterns)patternList, 0, 0, 1, i, instanceCount); BeagleTreeLikelihood treeLikelihood = createTreeLikelihood( subPatterns, treeModel, branchSiteModel, siteRateModel, branchRateModel, useAmbiguities, scalingScheme, partialsRestrictions, xo); treeLikelihood.setId(xo.getId() + "_" + instanceCount); likelihoods.add(treeLikelihood); } return new CompoundLikelihood(instanceCount, likelihoods); }