answer
stringlengths
17
10.2M
package org.jetel.metadata; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.regex.Pattern; import org.jetel.data.DataField; import org.jetel.data.DataFieldFactory; import org.jetel.data.Defaults; import org.jetel.exception.ConfigurationProblem; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.ConfigurationStatus.Priority; import org.jetel.exception.ConfigurationStatus.Severity; import org.jetel.exception.InvalidGraphObjectNameException; import org.jetel.util.ExceptionUtils; import org.jetel.util.bytes.CloverBuffer; import org.jetel.util.formatter.BooleanFormatter; import org.jetel.util.formatter.BooleanFormatterFactory; import org.jetel.util.formatter.DateFormatter; import org.jetel.util.formatter.DateFormatterFactory; import org.jetel.util.formatter.ParseBooleanException; import org.jetel.util.primitive.TypedProperties; import org.jetel.util.string.StringUtils; import sun.reflect.ReflectionFactory.GetReflectionFactoryAction; /** * A class that represents metadata describing one particular data field.<br> * Handles encoding of characters. * * @author David Pavlis, Javlin a.s. &lt;david.pavlis@javlin.eu&gt; * @author Martin Janik, Javlin a.s. &lt;martin.janik@javlin.eu&gt; * * @version 13th March 2009 * @since 26th March 2002 * * @see org.jetel.metadata.DataRecordMetadata * */ public class DataFieldMetadata implements Serializable { private static final long serialVersionUID = -880873886732472663L; public static final int INTEGER_LENGTH = 9; public static final int LONG_LENGTH = 18; public static final int DOUBLE_SCALE = 323; public static final int DOUBLE_LENGTH = DOUBLE_SCALE + 615; public static final String BINARY_FORMAT_STRING = "binary"; public static final String BLOB_FORMAT_STRING = "blob"; public static final String LENGTH_ATTR = "length"; public static final String SCALE_ATTR = "scale"; public static final String SIZE_ATTR = "size"; /** Characters that can be contained in format of date. */ private static final Pattern DATE_ONLY_PATTERN = Pattern.compile("[GyMwWDdFE]"); /** Characters that can be contained in format of time. */ private static final Pattern TIME_ONLY_PATTERN = Pattern.compile("[aHhKkmsSzZ]"); public static final String EMPTY_NAME = "_"; /** Parent data record metadata. */ private DataRecordMetadata dataRecordMetadata; /** Ordinal number of the field within data record metadata. */ private int number; /** Name of the field. */ protected String name; /** Description of the field. */ private String description; /** Original name of the field. */ private String label; /** The type of the field. */ private DataFieldType type = DataFieldType.UNKNOWN; /** Delimiter of the field (could be empty if field belongs to fixLength record). */ private String delimiter = null; /** If this switch is set to true, EOF works as delimiter for this field. It's useful for last field in the record. */ private boolean eofAsDelimiter = false; /** Format of Number, Date, DateTime, String (RegExp) or empty if not applicable. */ private String formatStr = null; /** Length of the field (in bytes) if the field belongs to fixLength record. */ private int size = 0; /** Relative shift of the beginning of the field. */ private short shift = 0; /** Indicates if when reading from file try to trim string value to obtain value */ private Boolean trim; /** Fields can assume null value by default. */ private boolean nullable = true; /** String value that is considered as null (in addition to null itself). */ private String nullValue = null; /** The default value. */ private Object defaultValue; /** The default value as a string. */ private String defaultValueStr; /** The auto-filling value. */ private String autoFilling; /** * Field can be populated by execution of Java code which can include references to fields from input records. The * code corresponds to a body of a method which has to return a value that has a type of the field type. * * The syntax for the field references is as follows: * * [record name].[field name] */ private TypedProperties fieldProperties; /** * Locale string. Both language and country can be specified - if both are specified then language string & country * string have to be delimited by "." (dot) -> e.g. "en.UK" , "fr.CA". If only language should be specified, then * use language code according to ISO639 -> e.g. "en" , "de". * * @see java.util.Locale */ private String localeStr = null; /** * Timezone string. * * @see java.util.TimeZone */ private String timeZoneStr = null; /** * See Collator.setStregth(String strength). It is used only in string fields. */ private String collatorSensitivity = null; /** * Container type of data field - SINGLE, LIST, MAP. */ private DataFieldContainerType containerType = DataFieldContainerType.SINGLE; /** * Constructor for a delimited type of field. * * @param name the name of the field * @param fieldType the type of this field * @param delimiter a string to be used as a delimiter for this field * @deprecated use {@link DataFieldMetadata#DataFieldMetadata(String, DataFieldType, String)} instead */ @Deprecated public DataFieldMetadata(String name, char fieldType, String delimiter) { this(name, DataFieldType.fromChar(fieldType), delimiter); } /** * Constructor for a delimited type of field. * @param name * @param fieldType * @param delimiter */ public DataFieldMetadata(String name, DataFieldType fieldType, String delimiter) { setName(name); this.type = fieldType; this.delimiter = delimiter; if (isTrimType()) { this.trim = true; } setFieldProperties(new Properties()); } /** * Constructor for a delimited type of field with specified container type. * @param name * @param fieldType * @param delimiter * @param containerType */ public DataFieldMetadata(String name, DataFieldType fieldType, String delimiter, DataFieldContainerType containerType) { this(name, fieldType, delimiter); setContainerType(containerType); } /** * Constructor for a default (String) delimited type of field. * * @param name the name of the field * @param delimiter a string to be used as a delimiter for this field */ public DataFieldMetadata(String name, String delimiter) { this(name, DataFieldType.STRING, delimiter); } /** * Constructor for a fixed-length type of field. * * @param name the name of the field * @param fieldType the type of this field * @param size the size of the field (in bytes) * @deprecated use {@link DataFieldMetadata#DataFieldMetadata(String, DataFieldType, int)} instead */ @Deprecated public DataFieldMetadata(String name, char fieldType, int size) { this(name, DataFieldType.fromChar(fieldType), size); } /** * Constructor for a fixed-length type of field. * @param name * @param fieldType * @param size */ public DataFieldMetadata(String name, DataFieldType fieldType, int size) { setName(name); this.type = fieldType; this.size = size; setFieldProperties(new Properties()); } /** * Constructor for a default (String) fixed-length type of field. * * @param name the name of the field * @param size the size of the field (in bytes) */ public DataFieldMetadata(String name, int size) { this(name, DataFieldType.STRING, size); } /** * Private constructor used in the duplicate() method. */ private DataFieldMetadata() { } /** * Sets the parent data record metadata. * * @param dataRecordMetadata the new parent data record metadata */ public void setDataRecordMetadata(DataRecordMetadata dataRecordMetadata) { this.dataRecordMetadata = dataRecordMetadata; } /** * @return the parent data record metadata */ public DataRecordMetadata getDataRecordMetadata() { return dataRecordMetadata; } /** * Sets the ordinal number of the data field. * * @param number the new ordinal number */ public void setNumber(int number) { this.number = number; } /** * @return the ordinal number of the data field */ public int getNumber() { return number; } /** * Sets the name of the field. * * @param name the new name of the field */ public void setName(String name) { if (!StringUtils.isValidObjectName(name)) { throw new InvalidGraphObjectNameException(name, "FIELD"); } this.name = name; } /** * @return the name of the field */ public String getName() { return name; } /** * Sets the description of the field. * * @param name the new description of the field */ public void setDescription(String description) { this.description = description; } /** * @return the description of the field */ public String getDescription() { return description; } /** * Sets the original name of the field. * * @param label the original name of the field */ public void setLabel(String label) { this.label = label; } /** * Returns the original name of the field. * * @return original name of the field */ public String getLabel() { return label; } /** * Returns the label of the field. * If it is not set, returns the name of the field. * * @return label of the field */ public String getLabelOrName() { if (label == null) { return getName(); } return label; } /** * Sets the type of the data field. * * @param type the new type of the data field * * @since 30th October 2002 * @deprecated use {@link #setDataType(DataFieldType)} instead */ @Deprecated public void setType(char type) { setDataType(DataFieldType.fromChar(type)); } /** * Sets the type of the data field. * @param type */ public void setDataType(DataFieldType type) { this.type = type; } /** * @return the type of the data field * * @since 30th October 2002 * @deprecated use {@link #getDataType()} instead */ @Deprecated public char getType() { return getDataType().getObsoleteIdentifier(); } /** * @return the type of the data field */ public DataFieldType getDataType() { return type; } /** * Sets the type of the data field using the full string form. * * @param type the new type of the data field as a string * @deprecated use {@link #setDataType(DataFieldType) in combination with {@link DataFieldType#fromName(String)} instead */ @Deprecated public void setTypeAsString(String type) { setDataType(DataFieldType.fromName(type)); } /** * @return the type of the data field as a string * @deprecated use {@link #getDataType()} and {@link DataFieldType#getName()} instead */ @Deprecated public String getTypeAsString() { return getDataType().getName(); } /** * @return container type of this field - SINGLE, LIST, MAP */ public DataFieldContainerType getContainerType() { return containerType; } /** * Sets container type of this field - SINGLE, LIST, MAP. * @param containerType */ public void setContainerType(DataFieldContainerType containerType) { if (containerType == null) { throw new NullPointerException("Data field container type cannot be null."); } this.containerType = containerType; } /** * @return <code>true</code> if this data field is numeric, <code>false</code> otherwise * @deprecated use {@link #getDataType()} and {@link DataFieldType#isNumeric()} instead */ @Deprecated public boolean isNumeric() { return getDataType().isNumeric(); } /** * @deprecated use {@link #getDataType()} and {@link DataFieldType#isTrimType()} instead */ @Deprecated private boolean isTrimType() { return getDataType().isTrimType(); } /** * Sets the delimiter string. * * @param delimiter the new delimiter string */ public void setDelimiter(String delimiter) { this.delimiter = delimiter; } /** * @return the delimiter string */ public String getDelimiter() { return delimiter; } /** * Returns an array of all field delimiters assigned to this field. In case no field delimiters are defined, default * field delimiters from parent metadata are returned. Delimiters for last field are extended by a record delimiter. * * @return the array of all field delimiters */ public String[] getDelimiters() { if (isDelimited()) { String[] delimiters = null; if (delimiter != null) { delimiters = delimiter.split(Defaults.DataFormatter.DELIMITER_DELIMITERS_REGEX); if (isLastNonAutoFilledField()) { // if field is last if (getDataRecordMetadata().isSpecifiedRecordDelimiter()) { List<String> tempDelimiters = new ArrayList<String>(); for (int i = 0; i < delimiters.length; i++) { // combine each field delimiter with each record delimiter String[] recordDelimiters = getDataRecordMetadata().getRecordDelimiters(); for (int j = 0; j < recordDelimiters.length; j++) { tempDelimiters.add(delimiters[i] + recordDelimiters[j]); } } delimiters = tempDelimiters.toArray(new String[tempDelimiters.size()]); } } } else { if (!isLastNonAutoFilledField()) { // if the field is not last delimiters = getDataRecordMetadata().getFieldDelimiters(); } else { delimiters = getDataRecordMetadata().getRecordDelimiters(); if (delimiters == null) { delimiters = getDataRecordMetadata().getFieldDelimiters(); } } } return delimiters; } return null; } /** * @return <code>true</code> if any field delimiter contains a carriage return, <code>false</code> otherwise */ public boolean containsCarriageReturnInDelimiters() { String[] delimiters = getDelimiters(); if (delimiters != null) { for (String delimiter : delimiters) { if (delimiter.indexOf('\r') >= 0) { return true; } } } return false; } /** * Sets the OEF-as-delimiter flag. * * @param eofAsDelimiter the new value of the flag */ public void setEofAsDelimiter(boolean eofAsDelimiter) { this.eofAsDelimiter = eofAsDelimiter; } /** * @return the value of the OEF-as-delimiter flag */ public boolean isEofAsDelimiter() { return eofAsDelimiter; } /** * Sets the format pattern of this data field. * * @param formatStr the new format pattern (acceptable value depends on the type of the data field) */ public void setFormatStr(String formatStr) { this.formatStr = formatStr; } /** * This method should not be called directly, use {@link #getFormat(DataFieldFormatType)} instead. * @return the format pattern which will be used when outputting field's value as a string, or <code>null</code> if * no format pattern is set for this field */ @SuppressWarnings("deprecation") public String getFormatStr() { if (formatStr != null) { return formatStr; } if (dataRecordMetadata != null) { if (getDataType().isNumeric()) { return dataRecordMetadata.getNumberFormatStr(); } if (type == DataFieldType.DATE || type == DataFieldType.DATETIME) { return dataRecordMetadata.getDateFormatStr(); } } return null; } /** * This method checks if type of field is date or datetime and if formatString isn't <code>null</code> or empty. * * @return <code>true</code> if type of field is date or datetime, <code>false</code> otherwise * * @since 24th August 2007 * @see org.jetel.component.DataFieldmetadata.isTimeFormat(CharSequence) */ @SuppressWarnings("deprecation") private boolean isDateOrTimeFieldWithFormatStr() { if (type != DataFieldType.DATE && type != DataFieldType.DATETIME) { return false; } return !StringUtils.isEmpty(formatStr); } /** * This method checks if formatString has a format of date. If formatString is <code>null</code> or empty then * formatString hasn't a format of date. * Note: formatString can has a format of date and format of time at the same time. * * @return <code>true</code> if formatString has a format of date, <code>false</code> otherwise * * @since 24th August 2007 * @see org.jetel.component.DataFieldmetadata.isTimeFormat(CharSequence) */ public boolean isDateFormat() { if (!isDateOrTimeFieldWithFormatStr()) { return false; } return DATE_ONLY_PATTERN.matcher(formatStr).find(); } /** * This method checks if formatString has a format of time. If formatString is <code>null</code> or empty then * formatString hasn't a format of time. * Note: formatString can has a format of date and format of time at the same time. * * @return <code>true</code> if formatString has a format of time, <code>false</code> otherwise * * @since 24th August 2007 * @see org.jetel.component.DataFieldmetadata.isDateFormat(CharSequence) */ public boolean isTimeFormat() { if (!isDateOrTimeFieldWithFormatStr()) { return false; } return TIME_ONLY_PATTERN.matcher(formatStr).find(); } /** * Sets the maximum field size (used only when dealing with a fixed-size type of record). * * @param size the new size of the data field */ public void setSize(int size) { this.size = size; } /** * @return the specified maximum field size (used only when dealing with a fixed-size type of record) */ public int getSize() { return size; } /** * @return <code>true</code> if this data field is delimited, <code>false</code> otherwise */ public boolean isDelimited() { return (size == 0 || (getDataRecordMetadata()!=null && getDataRecordMetadata().getParsingType() == DataRecordParsingType.DELIMITED)); } /** * @return <code>true</code> if this data field is fixed-length, <code>false</code> otherwise */ public boolean isFixed() { return (size > 0 && getDataRecordMetadata()!=null && this.getDataRecordMetadata().getParsingType()!=DataRecordParsingType.DELIMITED); } /** * Determines whether the field is byte-based. * * @return <code>true</code> if this data field is byte-based, <code>false</code> otherwise */ public boolean isByteBased() { if(BinaryFormat.isBinaryFormat(formatStr)) { return true; } return (type == DataFieldType.BYTE || type == DataFieldType.CBYTE); } /** * @return true iff formatStr is not null and is not empty */ public boolean hasFormat() { return !StringUtils.isEmpty(formatStr); } /** * Returns a type of a data field format obtained by analysis of * a prefix of getFormarStr(). No prefix with a format type * results in a default format type (DataFieldFormatType.DEFAULT_FORMAT_TYPE). * * Returns null for getFormatStr() being null or an empty string. * * @return a type of a data field format (or null if the field has no format) */ public DataFieldFormatType getFormatType() { return DataFieldFormatType.getFormatType(getFormatStr()); } /** * Returns a formatting string of a given type. A purpose of this method is to prevent * usage of incompatible formatting string types. * * The type of a formatting string is checked (using its prefix) * - If the formatting string stored in meta-data has a different type, either * an empty string is returned or conversion is performed. * - If the formatting string stored in meta-data matches a type given in argument, * the formatting string with no prefix is returned * * @param dataFieldFormat * @return */ public String getFormat(DataFieldFormatType dataFieldFormat) { return dataFieldFormat.getFormat(getFormatStr()); } /** * Returns a formatting string of the default type ({@link DataFieldFormatType#DEFAULT_FORMAT_TYPE}). * A purpose of this method is to prevent usage of incompatible formatting string types. * <p> * Equivalent call:<br> * {@link #getFormat(DataFieldFormatType.DEFAULT_FORMAT_TYPE)} * * * @param dataFieldFormat * @return * @see #getFormat(DataFieldFormatType) */ public String getFormat() { return getFormat(DataFieldFormatType.DEFAULT_FORMAT_TYPE); } /** * Prepare a DateFormatter instance based on format string and locale. * Available only for date field metadata. * @return DateFormatter instance for this date field metadata */ public DateFormatter createDateFormatter() { if (type != DataFieldType.DATE) { throw new UnsupportedOperationException("DateFormatter is available only for date field metadata."); } return DateFormatterFactory.getFormatter(getFormatStr(), getLocaleStr(), getTimeZoneStr()); } /** * Sets the position of the field in a data record (used only when dealing with fixed-size type of record). * * @param shift the new position of the field in a data record */ public void setShift(short shift) { this.shift = shift; } /** * @return the position of the field in a data record (used only when dealing with fixed-size type of record) */ public short getShift() { return shift; } /** * Sets the trim flag. * * @param trim the new value of the trim flag */ public void setTrim(Boolean trim) { this.trim = trim; } /** * @return the value of the trim flag */ public boolean isTrim() { if (trim == null) { if (getDataType().isTrimType()) { return true; } else { return false; } } else { return trim; } } /** * @return true if leading blank characters should be skipped */ public boolean isSkipLeadingBlanks() { return isTrim(); } /** * @return true if trailing blank characters should be skipped */ public boolean isSkipTrailingBlanks() { if (trim == null) { //trailing characters in fixlen metadata are skipped by default if (getDataRecordMetadata().getParsingType() == DataRecordParsingType.FIXEDLEN) { return true; } } return isTrim(); } /** * Sets the nullable flag. * * @param nullable the new value of the nullable flag */ public void setNullable(boolean nullable) { this.nullable = nullable; } /** * @return the value of the nullable flag */ public boolean isNullable() { return nullable; } /** * Sets a string value that will be considered as <code>null</code> (in addition to <code>null</code> itself). * * @param nullValue the string value to be considered as null, or <code>null</code> if an empty string should be used */ public void setNullValue(String nullValue) { this.nullValue = nullValue; } /** * @return the string value that is considered as <code>null</code>, never returns <code>null</code> */ public String getNullValue() { if (nullValue != null) { return nullValue; } if (dataRecordMetadata != null) { return dataRecordMetadata.getNullValue(); } return DataRecordMetadata.DEFAULT_NULL_VALUE; } /** * Sets the default value. * * @param defaultValue the new default value */ public void setDefaultValue(Object defaultValue) { this.defaultValue = defaultValue; } /** * @return the default value */ public Object getDefaultValue() { return defaultValue; } /** * Sets the default string value. * * @param defaultValueStr the new default string value * * @since 30th October 2002 */ public void setDefaultValueStr(String defaultValueStr) { this.defaultValueStr = defaultValueStr; } /** * @return the default string value * * @since 30th October 2002 */ public String getDefaultValueStr() { if (defaultValueStr != null) { return defaultValueStr; } else if (defaultValue != null) { return defaultValue.toString(); } return null; } /** * @return <code>true</code> if the default value is set, <code>false</code> otherwise */ public boolean isDefaultValueSet() { return (!StringUtils.isEmpty(defaultValueStr) || defaultValue != null); } /** * Sets the auto-filling value. * * @param autoFilling the new auto-filling value */ public void setAutoFilling(String autoFilling) { this.autoFilling = autoFilling; } /** * @return the auto-filling value */ public String getAutoFilling() { return autoFilling; } /** * @return true if the data field is auto filled, <code>false</code> otherwise */ public boolean isAutoFilled() { return !StringUtils.isEmpty(autoFilling); } /** * @return <code>true</code> if this data field is the last non-autofilled field within the data record metadata, * <code>false</code> otherwise. */ private boolean isLastNonAutoFilledField() { if (isAutoFilled()) { return false; } DataRecordMetadata metadata = getDataRecordMetadata(); DataFieldMetadata[] fields = metadata.getFields(); for (int i = getNumber() + 1; i < metadata.getNumFields(); i++) { if (!fields[i].isAutoFilled()) { return false; } } return true; } /** * Sets the fieldProperties attribute of the DataRecordMetadata object. Field properties allows defining additional * parameters for individual fields. These parameters (key-value pairs) are NOT normally handled by CloverETL, but * can be used in user's code or Components - thus allow for greater flexibility. * * @param properties The new recordProperties value */ public void setFieldProperties(Properties properties) { fieldProperties = new TypedProperties(properties); if (type == DataFieldType.DECIMAL) { if (fieldProperties.getProperty(LENGTH_ATTR) == null) { fieldProperties.setProperty(LENGTH_ATTR, Integer.toString(Defaults.DataFieldMetadata.DECIMAL_LENGTH)); } if (fieldProperties.getProperty(SCALE_ATTR) == null) { fieldProperties.setProperty(SCALE_ATTR, Integer.toString(Defaults.DataFieldMetadata.DECIMAL_SCALE)); } } } /** * Gets the fieldProperties attribute of the DataFieldMetadata object.<br> * These properties are automatically filled-in when parsing XML (.fmt) file containing data record metadata. Any * attribute not directly recognized by Clover is stored within properties object.<br> * Example: * * <pre> * &lt;Field name=&quot;Field1&quot; type=&quot;numeric&quot; delimiter=&quot;;&quot; myOwn1=&quot;1&quot; myOwn2=&quot;xyz&quot; /&gt; * </pre> * * @return The fieldProperties value */ public TypedProperties getFieldProperties() { return fieldProperties; } /** * Sets a value of the property with the given key. * * @param key the key of the property * @param value the value to be set */ public void setProperty(String key, String value) { if (fieldProperties == null) { setFieldProperties(new Properties()); } fieldProperties.setProperty(key, value); } /** * Returns a value of the property with the given key. * * @param key the key of the property * * @return the value of the property */ public String getProperty(String key) { return fieldProperties.getProperty(key); } /** * Sets the locale code string.<br> * Formatters/Parsers are generated based on this field's value. * * @param localeStr the locale code (eg. "en", "fr", ...) */ public void setLocaleStr(String localeStr) { this.localeStr = localeStr; } /** * @return the locale code string, or <code>null</code> if no locale string is set */ public String getLocaleStr() { if (localeStr != null) { return localeStr; } if (dataRecordMetadata != null) { return dataRecordMetadata.getLocaleStr(); } return null; } /** * @param timeZoneStr the timeZoneStr to set */ public void setTimeZoneStr(String timeZoneStr) { this.timeZoneStr = timeZoneStr; } /** * @return the timeZoneStr */ public String getTimeZoneStr() { if (timeZoneStr != null) { return timeZoneStr; } if (dataRecordMetadata != null) { return dataRecordMetadata.getTimeZoneStr(); } return null; } /** * Set collator sensitivity string. * @param collatorSensitivity */ public void setCollatorSensitivity(String collatorSensitivity) { this.collatorSensitivity = collatorSensitivity; } /** * Returns collator sensitivity as string according to CollatorSensitivityType class. * @return */ public String getCollatorSensitivity() { if (collatorSensitivity != null) { return collatorSensitivity; } else { return dataRecordMetadata.getCollatorSensitivity(); } } /** * This method checks if value from this field can be put safe in another field. * * @param anotherField the another field to be checked * * @return <code>true</code> if conversion is save, <code>false</code> otherwise */ public boolean isSubtype(DataFieldMetadata anotherField) { switch (type) { case INTEGER: switch (anotherField.getDataType()) { case DECIMAL: int anotherFieldLength = Integer.valueOf(anotherField.getProperty(LENGTH_ATTR)); int anotherFieldScale = Integer.valueOf(anotherField.getProperty(SCALE_ATTR)); return (anotherFieldLength - anotherFieldScale >= INTEGER_LENGTH); } break; case LONG: switch (anotherField.getDataType()) { case DECIMAL: int anotherFieldLength = Integer.valueOf(anotherField.getProperty(LENGTH_ATTR)); int anotherFieldScale = Integer.valueOf(anotherField.getProperty(SCALE_ATTR)); return (anotherFieldLength - anotherFieldScale >= LONG_LENGTH); } break; case NUMBER: switch (anotherField.getDataType()) { case DECIMAL: int anotherFieldLength = Integer.valueOf(anotherField.getProperty(LENGTH_ATTR)); int anotherFieldScale = Integer.valueOf(anotherField.getProperty(SCALE_ATTR)); return (anotherFieldLength >= DOUBLE_LENGTH && anotherFieldScale >= DOUBLE_SCALE); } break; case DECIMAL: switch (anotherField.getDataType()) { case DECIMAL: int anotherFieldLength = Integer.valueOf(anotherField.getProperty(LENGTH_ATTR)); int anotherFieldScale = Integer.valueOf(anotherField.getProperty(SCALE_ATTR)); return (anotherFieldLength >= Integer.valueOf(fieldProperties.getProperty(LENGTH_ATTR)) && anotherFieldScale >= Integer.valueOf(fieldProperties.getProperty(SCALE_ATTR))); case NUMBER: return (Integer.valueOf(fieldProperties.getProperty(LENGTH_ATTR)) <= DOUBLE_LENGTH && Integer.valueOf(fieldProperties.getProperty(SCALE_ATTR)) <= DOUBLE_SCALE); case INTEGER: return (Integer.valueOf(fieldProperties.getProperty(LENGTH_ATTR)) - Integer.valueOf(fieldProperties.getProperty(SCALE_ATTR)) <= INTEGER_LENGTH); case LONG: return (Integer.valueOf(fieldProperties.getProperty(LENGTH_ATTR)) - Integer.valueOf(fieldProperties.getProperty(SCALE_ATTR)) <= LONG_LENGTH); } break; } return type.isSubtype(anotherField.getDataType()); } /** * Creates a deep copy of this data field metadata object. * * @return an exact copy of current data field metadata object */ public DataFieldMetadata duplicate() { DataFieldMetadata dataFieldMetadata = new DataFieldMetadata(); dataFieldMetadata.setNumber(number); dataFieldMetadata.setName(name); dataFieldMetadata.setLabel(label); dataFieldMetadata.setDescription(description); dataFieldMetadata.setDataType(type); dataFieldMetadata.setContainerType(containerType); dataFieldMetadata.setDelimiter(delimiter); dataFieldMetadata.setEofAsDelimiter(eofAsDelimiter); dataFieldMetadata.setFormatStr(formatStr); dataFieldMetadata.setSize(size); dataFieldMetadata.setShift(shift); dataFieldMetadata.setTrim(trim); dataFieldMetadata.setNullable(nullable); dataFieldMetadata.setDefaultValueStr(defaultValueStr); dataFieldMetadata.setAutoFilling(autoFilling); dataFieldMetadata.setFieldProperties(fieldProperties); dataFieldMetadata.setLocaleStr(localeStr); dataFieldMetadata.setTimeZoneStr(timeZoneStr); dataFieldMetadata.setCollatorSensitivity(collatorSensitivity); return dataFieldMetadata; } @Override public boolean equals(Object object) { return equals(object, true); } public boolean equals(Object object, boolean checkFixDelType) { if (object == this) { return true; } if (!(object instanceof DataFieldMetadata)) { return false; } DataFieldMetadata dataFieldMetadata = (DataFieldMetadata) object; if (this.type == dataFieldMetadata.getDataType()) { //decimal data type has to have identical length and scale if (this.type == DataFieldType.DECIMAL) { if (!getProperty(LENGTH_ATTR).equals(dataFieldMetadata.getProperty(LENGTH_ATTR)) || !getProperty(SCALE_ATTR).equals(dataFieldMetadata.getProperty(SCALE_ATTR))) { return false; } } if (isFixed() && dataFieldMetadata.isFixed()) { // both fixed return (getSize() == dataFieldMetadata.getSize()); } else if (!isFixed() && !dataFieldMetadata.isFixed()) { // both delimited return true; } else { // one fixed and the second delimited return !checkFixDelType; } } return false; } @Override public int hashCode() { //FIXME this is not correct implementation, at least decimal type with different scale and length can be considered as different return this.type.hashCode(); } /** * Checks if the meta is valid. * * @param status * @return */ public void checkConfig(ConfigurationStatus status) { //check data type if (type == null) { status.add(new ConfigurationProblem("Data type is not specified.", Severity.ERROR, null, Priority.NORMAL)); } // verify default value - approved by kokon if (defaultValue != null || defaultValueStr != null) { DataField dataField = DataFieldFactory.createDataField(this, false); try { dataField.setToDefaultValue(); } catch (RuntimeException e) { status.add(new ConfigurationProblem("Wrong default value '" + getDefaultValueStr() + "' for field '" + name + "' in the record metadata element '" + dataRecordMetadata.getName() + "'.", Severity.ERROR, null, Priority.NORMAL)); } } if (DataFieldType.BOOLEAN == type && !StringUtils.isEmpty(formatStr)) { final BooleanFormatter bf = BooleanFormatterFactory.createFormatter(formatStr); final String trueO = bf.formatBoolean(true); try { if (true != bf.parseBoolean(trueO)) { status.add(new ConfigurationProblem("Wrong boolean format '" + formatStr + "' for field '" + name + "' in the record metadata element '" + dataRecordMetadata.getName() + "' - reverse check for true output string defined by the format '" + trueO + "' will return incorrect value.", Severity.WARNING, null, Priority.NORMAL)); } } catch (ParseBooleanException e) { status.add(new ConfigurationProblem( ExceptionUtils.getMessage("Wrong boolean format '" + formatStr + "' for field '" + name + "' in the record metadata element '" + dataRecordMetadata.getName() + "' - reverse check for true output string defined by the format '" + trueO + "' will not be parsable.", e), Severity.WARNING, null, Priority.NORMAL)); } final String falseO = bf.formatBoolean(false); try { if (false != bf.parseBoolean(falseO)) { status.add(new ConfigurationProblem("Wrong boolean format '" + formatStr + "' for field '" + name + "' in the record metadata element '" + dataRecordMetadata.getName() + "' - reverse check for true output string defined by the format '" + falseO + "' will return incorrect value.", Severity.WARNING, null, Priority.NORMAL)); } } catch (ParseBooleanException e) { status.add(new ConfigurationProblem( ExceptionUtils.getMessage("Wrong boolean format '" + formatStr + "' for field '" + name + "' in the record metadata element '" + dataRecordMetadata.getName() + "' - reverse check for true output string defined by the format '" + falseO + "' will not be parsable.", e), Severity.WARNING, null, Priority.NORMAL)); } } } /** * This method serialise only data type and length and scale for decimal type. * @param buffer */ public void serialize(CloverBuffer buffer) { buffer.put(type.getByteIdentifier()); buffer.put(containerType.getByteIdentifier()); if (type == DataFieldType.DECIMAL) { buffer.putInt(getFieldProperties().getIntProperty(DataFieldMetadata.LENGTH_ATTR)); buffer.putInt(getFieldProperties().getIntProperty(DataFieldMetadata.SCALE_ATTR)); } } @Override public String toString(){ return "Field [name:" + this.name + ", type:" + this.type.toString(getContainerType()) + (containerType != DataFieldContainerType.SINGLE ? ", containerType:" + containerType.getDisplayName() : "") + ", position:" + this.number + "]"; } /** * @return string representation of this field metadata, only data type is presented */ public String toStringDataType() { StringBuilder result = new StringBuilder(); result.append(getDataType().toString(getContainerType())); if (getDataType() == DataFieldType.DECIMAL) { result.append('('); result.append(getProperty(DataFieldMetadata.LENGTH_ATTR)); result.append(','); result.append(getProperty(DataFieldMetadata.SCALE_ATTR)); result.append(")"); } return result.toString(); } /** * @deprecated use {@link DataFieldType#STRING} instead */ @Deprecated public static final char STRING_FIELD = 'S'; /** * @deprecated use {@link DataFieldType#STRING} instead */ @Deprecated public static final String STRING_TYPE = "string"; /** * @deprecated use {@link DataFieldType#DATE} instead */ @Deprecated public static final char DATE_FIELD = 'D'; /** * @deprecated use {@link DataFieldType#DATE} instead */ @Deprecated public static final String DATE_TYPE = "date"; /** * @deprecated use {@link DataFieldType#DATE} instead */ @Deprecated public static final char DATETIME_FIELD = 'T'; /** * @deprecated use {@link DataFieldType#DATE} instead */ @Deprecated public static final String DATETIME_TYPE = "datetime"; /** * @deprecated use {@link DataFieldType#NUMBER} instead */ @Deprecated public static final char NUMERIC_FIELD = 'N'; /** * @deprecated use {@link DataFieldType#NUMBER} instead */ @Deprecated public static final String NUMERIC_TYPE = "number"; /** * @deprecated use {@link DataFieldType#NUMBER} instead */ @Deprecated public static final String NUMERIC_TYPE_DEPRECATED = "numeric"; /** * @deprecated use {@link DataFieldType#INTEGER} instead */ @Deprecated public static final char INTEGER_FIELD = 'i'; /** * @deprecated use {@link DataFieldType#INTEGER} instead */ @Deprecated public static final String INTEGER_TYPE = "integer"; /** * @deprecated use {@link DataFieldType#LONG} instead */ @Deprecated public static final char LONG_FIELD = 'l'; /** * @deprecated use {@link DataFieldType#LONG} instead */ @Deprecated public static final String LONG_TYPE = "long"; /** * @deprecated use {@link DataFieldType#DECIMAL} instead */ @Deprecated public static final char DECIMAL_FIELD = 'd'; /** * @deprecated use {@link DataFieldType#DECIMAL} instead */ @Deprecated public static final String DECIMAL_TYPE = "decimal"; /** * @deprecated use {@link DataFieldType#BYTE} instead */ @Deprecated public static final char BYTE_FIELD = 'B'; /** * @deprecated use {@link DataFieldType#BYTE} instead */ @Deprecated public static final String BYTE_TYPE = "byte"; /** * @deprecated use {@link DataFieldType#BOOLEAN} instead */ @Deprecated public static final char BOOLEAN_FIELD = 'b'; /** * @deprecated use {@link DataFieldType#BOOLEAN} instead */ @Deprecated public static final String BOOLEAN_TYPE = "boolean"; /** * @deprecated use {@link DataFieldType#CBYTE} instead */ @Deprecated public static final char BYTE_FIELD_COMPRESSED = 'Z'; /** * @deprecated use {@link DataFieldType#CBYTE} instead */ @Deprecated public static final String BYTE_COMPRESSED_TYPE = "cbyte"; /** * @deprecated should not be used at all */ @Deprecated public static final char SEQUENCE_FIELD = 'q'; /** * @deprecated should not be used at all */ @Deprecated public static final String SEQUENCE_TYPE = "sequence"; /** * @deprecated use {@link DataFieldType#NULL} instead */ @Deprecated public static final char NULL_FIELD = 'n'; /** * @deprecated use {@link DataFieldType#NULL} instead */ @Deprecated public static final String NULL_TYPE = "null"; /** * @deprecated use {@link DataFieldType#UNKNOWN} instead */ @Deprecated public static final char UNKNOWN_FIELD = ' '; /** * @deprecated use {@link DataFieldType#UNKNOWN} instead */ @Deprecated public static final String UNKNOWN_TYPE = "unknown"; /** * Converts a type of a data field into its full string form. * * @param type the type of a data field * * @return the type of the data field as a string * @deprecated use {@link DataFieldType#getName()} instead */ @Deprecated public static String type2Str(char type) { try { return DataFieldType.fromChar(type).getName(); } catch (IllegalArgumentException e) { return DataFieldType.UNKNOWN.getName(); } } /** * Converts a type of a data field in a full string form into its character form. * * @param type the type of the data field as a string * * @return the type of a data field * @deprecated use {@link DataFieldType#fromName(String)} instead */ @Deprecated public static char str2Type(String dataTypeName) { try { return DataFieldType.fromName(dataTypeName).getObsoleteIdentifier(); } catch (IllegalArgumentException e) { return DataFieldType.UNKNOWN.getObsoleteIdentifier(); } } }
package com.cloveretl.tableau; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Date; import java.util.HashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jetel.component.fileoperation.CloverURI; import org.jetel.component.fileoperation.FileManager; import org.jetel.data.BooleanDataField; import org.jetel.data.DataRecord; import org.jetel.data.DataRecordFactory; import org.jetel.data.DateDataField; import org.jetel.data.IntegerDataField; import org.jetel.data.NumericDataField; import org.jetel.data.StringDataField; import org.jetel.exception.AttributeNotFoundException; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ConfigurationProblem; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.ConfigurationStatus.Priority; import org.jetel.exception.ConfigurationStatus.Severity; import org.jetel.exception.XMLConfigurationException; import org.jetel.graph.InputPort; import org.jetel.graph.Node; import org.jetel.graph.Result; import org.jetel.graph.TransformationGraph; import org.jetel.metadata.DataFieldContainerType; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataFieldType; import org.jetel.metadata.DataRecordMetadata; import org.jetel.util.date.DateFieldExtractor; import org.jetel.util.date.DateFieldExtractorFactory; import org.jetel.util.file.FileUtils; import org.jetel.util.property.ComponentXMLAttributes; import org.jetel.util.property.RefResFlag; import org.jetel.util.string.StringUtils; import org.w3c.dom.Element; import com.cloveretl.tableau.TableauTableStructureParser.TableauTableColumnDefinition; import com.tableausoftware.TableauException; import com.tableausoftware.DataExtract.Collation; import com.tableausoftware.DataExtract.Extract; import com.tableausoftware.DataExtract.Row; import com.tableausoftware.DataExtract.Table; import com.tableausoftware.DataExtract.TableDefinition; import com.tableausoftware.DataExtract.Type; public class TableauWriter extends Node { private static final ReentrantLock lock = new ReentrantLock(); public final static String TABLEAU_WRITER = "TABLEAU_WRITER"; public static final String XML_ACTION_ON_EXISTING_FILE = "actionOnExistingFile"; /* * Note mtomcanyi: * * Tableau API seems to accept table name but throws exception when table name is anything else than "Extract". * Component code is ready accept table name from user, so when Tableau API start accepting it we can just uncomment our code * in fromXML() and customcomponents.xml and make table name configurable. */ public static final String XML_TABLE_NAME = "tableName"; public static final String XML_OUTPUT_FILE = "outputFile"; public static final String XML_DEFAULT_TABLE_COLLATION = "defaultTableCollation"; public static final String XML_TABLE_STRUCTURE = "tableStructure"; public static final String XML_TIMEOUT = "timeout"; // output file suffix required by Tableau private static final String REQUIRED_FILE_SUFFIX = ".tde"; // Attributes initialized from XML configuration private String outputFileName; private String tableName; private TableauActionOnExistingFile actionOnExistingFile; private String actionOnExistingFileRaw; private String rawTableCollation; private Collation defaultTableCollation; private String tableStructure; // How long should component wait for write lock, after this timeout the component run fails private long synchroLockTimeoutSeconds; // field name and its table column definition private HashMap<String, TableauTableColumnDefinition> mappings; // Component inputs private InputPort inputPort; private DataRecordMetadata inputMetadata; private DataRecord inputRecord; // Output structures private Extract targetExtract; private Table targetTable; private TableDefinition tableDefinition; // Calendar instance to convert from input dates to Tableau date fields private DateFieldExtractor[] extractors; static Log logger = LogFactory.getLog(TableauWriter.class); public TableauWriter(String id, TransformationGraph graph, String outputFileName, String tableName, String rawTableCollation, String actionOnExistingFileRaw, String tableStructure, long timeout) { super(id, graph); this.outputFileName = outputFileName; this.tableName = tableName; this.rawTableCollation= rawTableCollation; this.actionOnExistingFileRaw = actionOnExistingFileRaw; this.tableStructure = tableStructure; this.synchroLockTimeoutSeconds = timeout; } @Override public void init() throws ComponentNotReadyException { super.init(); prepareInputRecord(); if (defaultTableCollation == null) { checkDefaultCollation(null); } try { actionOnExistingFile = TableauActionOnExistingFile.valueOf(actionOnExistingFileRaw); } catch (IllegalArgumentException e) { throw new ComponentNotReadyException("Invalid value of Action on existing file. Value was: " + actionOnExistingFileRaw); } mappings = new TableauTableStructureParser(tableStructure, true, inputMetadata).getTableauMapping(); } @Override protected Result execute() throws Exception { // Tableau API is not thread-safe. We use a lock to deal with it. // We wait for first record to come in. This prevents locking the tableau API too early. if (readRecord() && runIt) { logger.info(getName() + " is trying to acquire lock for Tableau API."); boolean lockSuccess = lock.tryLock(synchroLockTimeoutSeconds, TimeUnit.SECONDS); // thread is waiting if (!lockSuccess) { logger.error(getName() + " didn't acquire Tableau API lock. This happened because there were multiple TableauWriter" + " components running at the same time, which is not allowed."); throw new Exception("TableauWriter: component " + getName() + " couldn't acquire write lock because there was already different TableauWriter component running."); //+ " Component waited for " + synchroLockTimeoutSeconds + " seconds."); } // we have the lock at this point logger.info(getName() + " acquired lock for Tableau API."); try { // check and prepare target file prepareTargetFile(); prepareTargetTable(); prepareValueConvertors(); // first record was already read writeRecord(); while (readRecord() && runIt) { writeRecord(); } } finally { if (lockSuccess) { if (targetExtract != null) { targetExtract.close(); } lock.unlock(); logger.info(getName() + " released lock for Tableau API."); } } } return Result.FINISHED_OK; } private boolean readRecord() throws InterruptedException, IOException{ return (inputPort.readRecord(inputRecord) != null); } private void writeRecord() throws ComponentNotReadyException { try { Row outputRow = new Row(this.tableDefinition); for (int i=0; i<inputRecord.getNumFields();i++) { DataFieldMetadata fieldMetadata=inputMetadata.getField(i); if (inputRecord.getField(i).isNull()) { outputRow.setNull(i); continue; } Type type = tableDefinition.getColumnType(i); switch (type) { case UNICODE_STRING: // null values are handled above so CloverString -> String conversion will always succeed outputRow.setString(i, ((StringDataField)inputRecord.getField(i)).getValue().toString()); break; case BOOLEAN: outputRow.setBoolean(i, ((BooleanDataField)inputRecord.getField(i)).getBoolean()); break; case DATETIME: case DATE: case DURATION: final Date inputDate = ((DateDataField)inputRecord.getField(i)).getDate(); DateFieldExtractor extractor = extractors[i]; extractor.setDate(inputDate); int year = extractor.getYear(); int month = extractor.getMonth(); int day = extractor.getDay(); int hour = extractor.getHour(); int minute = extractor.getMinute(); int second = extractor.getSecond(); int millisecond = extractor.getMilliSecond(); switch (type) { case DURATION: outputRow.setDuration(i, day, hour, minute, second, millisecond); break; case DATE: outputRow.setDate(i, year, month, day); break; default: // DATETIME outputRow.setDateTime(i, year, month, day, hour, minute, second, millisecond); } break; case DOUBLE: outputRow.setDouble(i, ((NumericDataField)inputRecord.getField(i)).getDouble()); break; case INTEGER: outputRow.setInteger(i, ((IntegerDataField)inputRecord.getField(i)).getInt()); break; default: throw new ComponentNotReadyException( "Unable to convert value of type \"" + fieldMetadata.getDataType() + "\" into any types supported by Tableau. Offending field: " + fieldMetadata.getName()); } } targetTable.insert(outputRow); } catch (TableauException e) { throw new ComponentNotReadyException( "Unable to write input record to the output file. Offending record: \n" + this.inputRecord, e); } } private void prepareInputRecord() throws ComponentNotReadyException { this.inputPort = getInputPort(0); this.inputMetadata = inputPort.getMetadata(); if (inputMetadata == null) { throw new ComponentNotReadyException("Input edge is missing metadata information"); } this.inputRecord = DataRecordFactory.newRecord(inputMetadata); this.inputRecord.init(); } private Extract prepareTargetFile() throws ComponentNotReadyException { if (outputFileName == null || outputFileName.isEmpty()) { throw new ComponentNotReadyException( "Output file path is not set. Enter valid path pointing to a local file with \".tde\" suffix"); } logger.debug("Input files is configured to: \"" + outputFileName + "\""); URI contextURI; try { contextURI = getContextURL().toURI(); } catch (URISyntaxException e1) { ComponentNotReadyException ex = new ComponentNotReadyException("Error while resolving project context."); ex.addSuppressed(e1); throw ex; } File targetFile = FileManager.getInstance().getFile(CloverURI.createSingleURI(contextURI, outputFileName)); logger.debug("Resolved target file to: \"" + targetFile + "\""); // Create any missing directories FileUtils.createParentDirs(getContextURL(), outputFileName); if (targetFile.exists()) { if (actionOnExistingFile.isOverwrite()) { // Tableau API throws exception if target file exists. We must delete it, there is no "replace" option // See docs of constructor for Extract class if (!targetFile.delete()) { throw new ComponentNotReadyException("Unable to delete output file, the file is probably locked. Output file: " + targetFile); } } } try { this.targetExtract = new Extract(targetFile.getCanonicalPath()); return this.targetExtract; } catch (IOException | TableauException e) { logger.debug("Extract exception thrown: "+e.getMessage()); throw new ComponentNotReadyException("Unable to open output file. Output file: " + targetFile, e); } } private void prepareTargetTable() throws ComponentNotReadyException { if (tableName == null) { // we validate that input edge is connected in init() method before this code gets called. this.tableName = "Extract"; logger.info("Target table name is not set. Using \"Extract\" as table name."); } try { if (targetExtract.hasTable(tableName)) { // table exists; open it if append mode is on if (actionOnExistingFile.isTerminate()) { throw new ComponentNotReadyException("Target table exists and terminate processing option was specified. Terminating processing. Table: " + tableName); } this.targetTable = targetExtract.openTable(tableName); this.tableDefinition = targetTable.getTableDefinition(); } else { // table does not exist; create new definition logger.info("Target table does not exist. Creating new table definition."); this.tableDefinition = createTableDefinition(); this.targetExtract.addTable(tableName, tableDefinition); this.targetTable = targetExtract.openTable(tableName); printTableDefinition(this.tableName, tableDefinition); } } catch (TableauException e) { throw new ComponentNotReadyException("Unable to create/open target table: " + tableName,e); } } private TableDefinition createTableDefinition() throws ComponentNotReadyException { try { TableDefinition tableDefinition = new TableDefinition(); tableDefinition.setDefaultCollation(this.defaultTableCollation); for (int i=0; i<inputRecord.getNumFields();i++) { DataFieldMetadata fieldMetadata=inputMetadata.getField(i); TableauTableColumnDefinition column = mappings.get(fieldMetadata.getName()); Type tableauType; if (column.getTableauType().equals(TableauTableStructureParser.DEFAULT_TABLEAU_TYPE_STRING)) { tableauType = convertToDefaultType(fieldMetadata); } else { tableauType = Type.valueOf(column.getTableauType()); } if (column.getCollation().equals(TableauTableStructureParser.DEFAULT_COLLATION_STRING)) { tableDefinition.addColumn(fieldMetadata.getName(), tableauType); } else { tableDefinition.addColumnWithCollation( fieldMetadata.getName(), tableauType, Collation.valueOf(column.getCollation())); } } return tableDefinition; } catch (TableauException e) { throw new ComponentNotReadyException("Unable to create target table definition from input metadata.",e); } } private static Type convertToDefaultType(DataFieldMetadata fieldMeta) throws ComponentNotReadyException { switch (fieldMeta.getDataType()) { case BOOLEAN: return Type.BOOLEAN; case DATE: return Type.DATETIME; case NUMBER: return Type.DOUBLE; case INTEGER: return Type.INTEGER; case STRING: return Type.UNICODE_STRING; default: throw new ComponentNotReadyException("Field type " + fieldMeta.getDataType() + " cannot be converted to any Tableau type!"); } } public static Type[] getCompatibleTypes(DataFieldMetadata fieldMeta) { switch (fieldMeta.getDataType()) { case BOOLEAN: return new Type[] {Type.BOOLEAN}; case DATE: return new Type[] {Type.DATETIME, Type.DATE, Type.DURATION}; case NUMBER: return new Type[] {Type.DOUBLE}; case INTEGER: return new Type[] {Type.INTEGER}; case STRING: return new Type[] {Type.UNICODE_STRING}; default: return null; } } private void prepareValueConvertors() { DataRecordMetadata recordMeta = getInputPort(0).getMetadata(); this.extractors = new DateFieldExtractor[recordMeta.getNumFields()]; for (int i=0; i<recordMeta.getNumFields(); i++) { DataFieldMetadata fieldMeta = recordMeta.getField(i); if (DataFieldType.DATE == fieldMeta.getDataType() ) { extractors[i]= DateFieldExtractorFactory.getExtractor(fieldMeta.getTimeZoneStr()); } } } // Log table metadata definition private void printTableDefinition(String tableName, TableDefinition tableDef) throws TableauException { int numColumns = tableDef.getColumnCount(); StringBuffer strBuf = new StringBuffer(); strBuf.append("\n for ( int i = 0; i < numColumns; ++i ) { Type type = tableDef.getColumnType(i); String name = tableDef.getColumnName(i); strBuf.append(String.format("Column %3d: %-25s %-14s\n", i+1, name, Type.enumForValue(type.getValue()))); } strBuf.append(" logger.info(strBuf); } public static Node fromXML(TransformationGraph graph, Element xmlElement) throws XMLConfigurationException, AttributeNotFoundException { ComponentXMLAttributes xattribs = new ComponentXMLAttributes(xmlElement, graph); String componentID = xattribs.getString(XML_ID_ATTRIBUTE); String targetFileName = xattribs.getStringEx(XML_OUTPUT_FILE, null, RefResFlag.URL); String targetTableName = xattribs.getStringEx(XML_TABLE_NAME, "Extract", null); String actionOnExistingFile = xattribs.getStringEx(XML_ACTION_ON_EXISTING_FILE, TableauActionOnExistingFile.OVERWRITE_TABLE.name(), null); String rawTableCollation = xattribs.getStringEx(XML_DEFAULT_TABLE_COLLATION, null, null); String tableStructure = xattribs.getStringEx(XML_TABLE_STRUCTURE, "", null); // Currently, multiple TableauWriters are not allowed to run at the same time. Thus the timeout is set to 0. long timeout = xattribs.getLong(XML_TIMEOUT, 0); return new TableauWriter(componentID, graph,targetFileName,targetTableName,rawTableCollation,actionOnExistingFile,tableStructure,timeout); } /** * Sets default collation. If status is null, prints errors to System.err * @param status */ private void checkDefaultCollation(ConfigurationStatus status) { String errMessage = null; /* * Ugly hack by mtomcanyi: Tableau Java libraries require native libraries to be on PATH. * Tableau does not currently (June 2014) provide libraries for Mac OS X so the code below will always fail on Mac. * Additionally if user does not configure libraries on Win or Linux the call to Collation.valueOf() fails due to unsatisfied linking error. * The try/catch below is therefore our best effort to avoid crashing and return helpful error. */ try { if (rawTableCollation == null) { // The calls to Collation.valueOf() need to be hard-coded here. Do not put it in a class constant (the class wouldn't initialize) this.defaultTableCollation = Collation.valueOf(TableauTableStructureParser.DEFAULT_COLLATION); } else { try { defaultTableCollation = Collation.valueOf(rawTableCollation); } catch (IllegalArgumentException e) { errMessage = "Illegal value for default table collation: " + rawTableCollation; } } } catch (UnsatisfiedLinkError | NoClassDefFoundError e) { if (System.getProperty("os.name").startsWith("Mac")) { errMessage = "The " + getClass().getSimpleName() + " does not work on Mac OS X as Tableau does not provide libraries for Mac."; } else { errMessage = "Unable to initialize Tableau native libraries. Make sure they are installed and configured in PATH environment variable (see component docs). Underlying error: \n" + e.getMessage(); } } if (errMessage != null) { if (status != null) { status.add(new ConfigurationProblem(errMessage, Severity.ERROR, this, Priority.NORMAL)); } else { System.err.println(errMessage); } } } @Override public ConfigurationStatus checkConfig(ConfigurationStatus status) { status = super.checkConfig(status); checkDefaultCollation(status); if (StringUtils.isEmpty(outputFileName)) { status.add(new ConfigurationProblem("Missing File URL attribute.", Severity.ERROR, this, Priority.NORMAL)); } // Tableau API requires that the target file ends with ".tde". See Extract constructor doc if (outputFileName != null && !outputFileName.endsWith(REQUIRED_FILE_SUFFIX)) { status.add(new ConfigurationProblem("Output file path must point to a file with \".tde\" suffix", Severity.ERROR, this, Priority.NORMAL)); } for (Node n : getGraph().getPhase(getPhaseNum()).getNodes().values()) { if (n != this && getType().equals(n.getType())) { //multiple writers in the same phase //status.add("\"" + n.getName() + "\" writes in the same phase. Having multiple TableauWriters in the same phase is not recommended.", ConfigurationStatus.Severity.WARNING, this, ConfigurationStatus.Priority.NORMAL); status.add("\"" + n.getName() + "\" writes in the same phase. Having multiple TableauWriters in the same phase is not allowed.", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL); //multiple writers in the same phase AND a same file - that will never work, reports config error /* try { URL contextURL = getContextURL(); URL url1 = FileUtils.getFileURL(contextURL, ((TableauWriter) n).outputFileName); URL url2 = FileUtils.getFileURL(contextURL, outputFileName); if (url1.equals(url2)) { status.add("\"" + n.getName() + "\" (ID: " + n.getId() + ") writes to the same file in the same phase!", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL); } } catch (MalformedURLException e) { } */ } } try { TableauActionOnExistingFile.valueOf(actionOnExistingFileRaw); } catch (Exception e) { status.add(new ConfigurationProblem( "Action on existing output file is not set properly!", Severity.ERROR, this, Priority.NORMAL)); } checkInputPorts(status, 1, 1); DataRecordMetadata recordMeta; if (getInputPort(0) != null && (recordMeta = getInputPort(0).getMetadata()) != null) { for (int i=0; i<recordMeta.getNumFields(); i++) { DataFieldMetadata fieldMeta = recordMeta.getField(i); DataFieldType fieldType= fieldMeta.getDataType(); if (fieldType == DataFieldType.LONG || fieldType == DataFieldType.DECIMAL || fieldType == DataFieldType.BYTE || fieldType == DataFieldType.CBYTE) { status.add("Input metadata of \"" + getName() + "\" contain data type unsupported by Tableau! Metadata field " + recordMeta.getField(i).getName() + " of metadata " + recordMeta.getName() + " has type " + fieldType.getName() + "! Unsupported types are: " + DataFieldType.LONG.getName() + ", " + DataFieldType.DECIMAL.getName() + ", " + DataFieldType.BYTE.getName() + ", " + DataFieldType.CBYTE.getName(), ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL); } if (fieldMeta.getContainerType() != DataFieldContainerType.SINGLE) { status.add("Input metadata of \"" + getName() + "\" have container unsupported by Tableau! Metadata field " + recordMeta.getField(i).getName() + " of metadata " + recordMeta.getName() + " has container " + fieldMeta.getContainerType().getDisplayName() +"! Container types " + DataFieldContainerType.MAP.getDisplayName() + " and " + DataFieldContainerType.LIST.getDisplayName() + " are not supported.", ConfigurationStatus.Severity.ERROR, this, ConfigurationStatus.Priority.NORMAL); } } } return status; } public static enum TableauActionOnExistingFile { OVERWRITE_TABLE, APPEND_TO_TABLE, TERMINATE_PROCESSING; public boolean isOverwrite() { return (this == OVERWRITE_TABLE); } public boolean isAppend() { return (this == APPEND_TO_TABLE); } public boolean isTerminate() { return (this == TERMINATE_PROCESSING); } } }
package org.helioviewer.plugins.eveplugin.events.model; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import org.helioviewer.jhv.data.datatype.event.JHVEvent; /** * * * @author Bram Bourgoignie (Bram.Bourgoignie@oma.be) * */ public class EventPlotConfiguration { /** The event */ private final JHVEvent event; /** The scaled x position */ private final double scaledX0; private final double scaledX1; /** the Y position */ private final int yPosition; /** The position of the angle the event area */ private Rectangle drawPosition; /** * Creates a EventPlotConfiguration for the given event with scaledX0 start * position and scaledX1 end position. * * @param event * the event for this plot configuration * @param scaledX0 * the scaled start position * @param scaledX1 * the scaled end position * @param yPosition * the y-position of this event in the band provided for this * event type. */ public EventPlotConfiguration(JHVEvent event, double scaledX0, double scaledX1, int yPosition) { this.event = event; this.scaledX0 = scaledX0; this.scaledX1 = scaledX1; this.yPosition = yPosition; } /** * Draws the event plot configuration on the given graph area. * * @param g * the graphics on which to draw * @param graphArea * the area available to draw * @param nrOfEventTypes * the number of event types to be drawn * @param eventTypeNR * the number of this event type * @param linesForEventType * maximum of lines needed for this event type * @param totalLines * the total number of lines for all events * @param nrPreviousLines * the number of lines used already */ public void draw(Graphics g, Rectangle graphArea, int nrOfEventTypes, int eventTypeNR, int linesForEventType, int totalLines, int nrPreviousLines) { int spacePerLine = Math.min(4, (new Double(Math.floor(1.0 * graphArea.height / totalLines / 2))).intValue()); int startPosition = spacePerLine * 2 * (nrPreviousLines + yPosition); // g.setColor(event.getColor()); drawPosition = new Rectangle((new Double(Math.floor(graphArea.width * scaledX0))).intValue(), startPosition, (new Double(Math.floor(graphArea.width * (scaledX1 - scaledX0)))).intValue(), spacePerLine); int endpointsMarkWidth = 2; if (drawPosition.width > 10) { g.setColor(Color.black); g.fillRect(drawPosition.x, startPosition, endpointsMarkWidth, spacePerLine); g.setColor(event.getEventRelationShip().getRelationshipColor()); g.fillRect(drawPosition.x + endpointsMarkWidth, startPosition, drawPosition.width - 2 * endpointsMarkWidth, spacePerLine); g.setColor(Color.black); g.fillRect(drawPosition.x + drawPosition.width - endpointsMarkWidth, startPosition, endpointsMarkWidth, spacePerLine); } else { g.setColor(event.getEventRelationShip().getRelationshipColor()); g.fillRect(drawPosition.x, startPosition, drawPosition.width, spacePerLine); } } /** * Gets the event at the given point. * * @param p * the location to check for an event. * @return null if no event is located there, the event if found */ public JHVEvent getEventAtPoint(Point p) { if (containsPoint(p)) { return event; } return null; } public JHVEvent getEvent() { return event; } /** * Checks if the given point is located where the event was drawn. * * @param p * the point to check * @return true if the point is located in the event area, false if the * point is not located in the event area. */ private boolean containsPoint(Point p) { if (drawPosition != null) { return drawPosition.contains(p); } return false; } public int getEventPosition() { return this.yPosition; } }
package org.helioviewer.plugins.eveplugin.events.model; import java.awt.Color; import java.awt.Graphics; import java.awt.Rectangle; import org.helioviewer.jhv.data.datatype.JHVEvent; /** * * * @author Bram Bourgoignie (Bram.Bourgoignie@oma.be) * */ public class EventPlotConfiguration { /** The event */ private final JHVEvent event; /** The scaled x position */ private final double scaledX0; private final double scaledX1; /** * Creates a EventPlotConfiguration for the given event with scaledX0 start * position and scaledX1 end position. * * @param event * the event for this plot configuration * @param scaledX0 * the scaled start position * @param scaledX1 * the scaled end position */ public EventPlotConfiguration(JHVEvent event, double scaledX0, double scaledX1) { this.event = event; this.scaledX0 = scaledX0; this.scaledX1 = scaledX1; } /** * Draws the event plot configuration on the given graph area. * * @param g * the graphics on which to draw * @param graphArea * the area available to draw */ public void draw(Graphics g, Rectangle graphArea) { g.setColor(Color.CYAN); g.fillRect((new Double(Math.floor(graphArea.width * scaledX0))).intValue(), 10, (new Double(Math.floor(graphArea.width * (scaledX1 - scaledX0)))).intValue(), 2); // g.drawString(event.getDisplayName(), (new // Double(Math.floor(graphArea.width * scaledX0))).intValue(), 60); g.drawImage(event.getIcon().getImage(), (new Double(Math.floor(graphArea.width * scaledX0))).intValue(), 60, null); } }
package com.digitalpetri.opcua.stack.client.channel; import java.nio.ByteOrder; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import com.digitalpetri.opcua.stack.client.UaTcpClient; import com.digitalpetri.opcua.stack.core.StatusCodes; import com.digitalpetri.opcua.stack.core.UaException; import com.digitalpetri.opcua.stack.core.UaRuntimeException; import com.digitalpetri.opcua.stack.core.channel.ChannelSecrets; import com.digitalpetri.opcua.stack.core.channel.SerializationQueue; import com.digitalpetri.opcua.stack.core.channel.headers.AsymmetricSecurityHeader; import com.digitalpetri.opcua.stack.core.channel.headers.HeaderDecoder; import com.digitalpetri.opcua.stack.core.channel.messages.ErrorMessage; import com.digitalpetri.opcua.stack.core.channel.messages.MessageType; import com.digitalpetri.opcua.stack.core.channel.messages.TcpMessageDecoder; import com.digitalpetri.opcua.stack.core.types.builtin.DateTime; import com.digitalpetri.opcua.stack.core.types.enumerated.SecurityTokenRequestType; import com.digitalpetri.opcua.stack.core.types.structured.CloseSecureChannelRequest; import com.digitalpetri.opcua.stack.core.types.structured.OpenSecureChannelRequest; import com.digitalpetri.opcua.stack.core.types.structured.OpenSecureChannelResponse; import com.digitalpetri.opcua.stack.core.types.structured.RequestHeader; import com.digitalpetri.opcua.stack.core.util.BufferUtil; import com.google.common.collect.Lists; import io.netty.buffer.ByteBuf; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class UaTcpClientAsymmetricHandler extends SimpleChannelInboundHandler<ByteBuf> implements HeaderDecoder { private final Logger logger = LoggerFactory.getLogger(getClass()); private List<ByteBuf> chunkBuffers = Lists.newArrayList(); private ScheduledFuture renewFuture; private final AtomicReference<AsymmetricSecurityHeader> headerRef = new AtomicReference<>(); private final int maxChunkCount; private final ClientSecureChannel secureChannel; private final UaTcpClient client; private final SerializationQueue serializationQueue; private final CompletableFuture<Channel> handshakeFuture; public UaTcpClientAsymmetricHandler(UaTcpClient client, SerializationQueue serializationQueue, CompletableFuture<Channel> handshakeFuture) { this.client = client; this.serializationQueue = serializationQueue; this.handshakeFuture = handshakeFuture; maxChunkCount = serializationQueue.getParameters().getLocalMaxChunkCount(); secureChannel = client.getSecureChannel(); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { if (renewFuture != null) renewFuture.cancel(false); super.channelInactive(ctx); } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { SecurityTokenRequestType requestType = secureChannel.getChannelId() == 0 ? SecurityTokenRequestType.Issue : SecurityTokenRequestType.Renew; OpenSecureChannelRequest request = new OpenSecureChannelRequest( new RequestHeader(null, DateTime.now(), 0L, 0L, null, 0L, null), PROTOCOL_VERSION, requestType, secureChannel.getMessageSecurityMode(), secureChannel.getLocalNonce(), 60 * 1000L ); sendSecureChannelRequest(ctx, request); } @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof CloseSecureChannelRequest) { sendCloseSecureChannelRequest(ctx, (CloseSecureChannelRequest) evt); } } @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception { buffer = buffer.order(ByteOrder.LITTLE_ENDIAN); while (buffer.readableBytes() >= HeaderLength && buffer.readableBytes() >= getMessageLength(buffer)) { int messageLength = getMessageLength(buffer); MessageType messageType = MessageType.fromMediumInt(buffer.getMedium(buffer.readerIndex())); switch (messageType) { case OpenSecureChannel: onOpenSecureChannel(ctx, buffer.readSlice(messageLength)); break; case Error: onError(ctx, buffer.readSlice(messageLength)); break; default: throw new UaException(StatusCodes.Bad_TcpMessageTypeInvalid, "unexpected MessageType: " + messageType); } } } private void onOpenSecureChannel(ChannelHandlerContext ctx, ByteBuf buffer) throws UaException { buffer.skipBytes(3); // Skip messageType char chunkType = (char) buffer.readByte(); if (chunkType == 'A') { chunkBuffers.forEach(ByteBuf::release); chunkBuffers.clear(); } else { buffer.skipBytes(4); // Skip messageSize long secureChannelId = buffer.readUnsignedInt(); secureChannel.setChannelId(secureChannelId); AsymmetricSecurityHeader securityHeader = AsymmetricSecurityHeader.decode(buffer); if (!headerRef.compareAndSet(null, securityHeader)) { if (!securityHeader.equals(headerRef.get())) { throw new UaRuntimeException(StatusCodes.Bad_SecurityChecksFailed, "subsequent AsymmetricSecurityHeader did not match"); } } chunkBuffers.add(buffer.readerIndex(0).retain()); if (chunkBuffers.size() > maxChunkCount) { throw new UaException(StatusCodes.Bad_TcpMessageTooLarge, String.format("max chunk count exceeded (%s)", maxChunkCount)); } if (chunkType == 'F') { final List<ByteBuf> buffersToDecode = chunkBuffers; chunkBuffers = Lists.newArrayListWithCapacity(maxChunkCount); serializationQueue.decode((binaryDecoder, chunkDecoder) -> { ByteBuf messageBuffer = chunkDecoder.decodeAsymmetric( secureChannel, MessageType.OpenSecureChannel, buffersToDecode ); binaryDecoder.setBuffer(messageBuffer); OpenSecureChannelResponse response = binaryDecoder.decodeMessage(null); logger.debug("Received OpenSecureChannelResponse."); secureChannel.setPreviousTokenId(secureChannel.getCurrentTokenId()); secureChannel.setCurrentTokenId(response.getSecurityToken().getTokenId()); secureChannel.setChannelId(response.getSecurityToken().getChannelId()); logger.debug("SecureChannel id={}", secureChannel.getChannelId()); if (secureChannel.isSymmetricSigningEnabled()) { secureChannel.setRemoteNonce(response.getServerNonce()); ChannelSecrets channelSecrets = ChannelSecrets.forChannel( secureChannel, secureChannel.getLocalNonce(), secureChannel.getRemoteNonce() ); secureChannel.setChannelSecrets(channelSecrets); } if (response.getServerProtocolVersion() < PROTOCOL_VERSION) { throw new UaRuntimeException(StatusCodes.Bad_ProtocolVersionUnsupported, "server protocol version unsupported: " + response.getServerProtocolVersion()); } DateTime createdAt = response.getSecurityToken().getCreatedAt(); long revisedLifetime = response.getSecurityToken().getRevisedLifetime(); long renewAt = (long) (revisedLifetime * 0.75); renewFuture = ctx.executor().schedule(() -> renewSecureChannel(ctx), renewAt, TimeUnit.MILLISECONDS); // messageBuffer is a composite; releasing it releases components as well. messageBuffer.release(); buffersToDecode.clear(); ctx.executor().execute(() -> { // SecureChannel is ready; remove the acknowledge handler and add the symmetric handler. if (ctx.pipeline().get(UaTcpClientAcknowledgeHandler.class) != null) { ctx.pipeline().remove(UaTcpClientAcknowledgeHandler.class); } ctx.pipeline().addFirst(new UaTcpClientSymmetricHandler(client, serializationQueue, handshakeFuture)); }); }); } } } private void sendSecureChannelRequest(ChannelHandlerContext ctx, OpenSecureChannelRequest request) { serializationQueue.encode((binaryEncoder, chunkEncoder) -> { ByteBuf messageBuffer = BufferUtil.buffer(); binaryEncoder.setBuffer(messageBuffer); binaryEncoder.encodeMessage(null, request); List<ByteBuf> chunks = chunkEncoder.encodeAsymmetric( secureChannel, MessageType.OpenSecureChannel, messageBuffer, chunkEncoder.nextRequestId() ); ctx.executor().execute(() -> { chunks.forEach(c -> ctx.write(c, ctx.voidPromise())); ctx.flush(); }); messageBuffer.release(); logger.debug("Sent OpenSecureChannelRequest ({}, id={}).", request.getRequestType(), secureChannel.getChannelId()); }); } private void sendCloseSecureChannelRequest(ChannelHandlerContext ctx, CloseSecureChannelRequest request) { serializationQueue.encode((binaryEncoder, chunkEncoder) -> { ByteBuf messageBuffer = BufferUtil.buffer(); binaryEncoder.setBuffer(messageBuffer); binaryEncoder.encodeMessage(null, request); List<ByteBuf> chunks = chunkEncoder.encodeAsymmetric( secureChannel, MessageType.CloseSecureChannel, messageBuffer, chunkEncoder.nextRequestId() ); ctx.executor().execute(() -> { chunks.forEach(c -> ctx.write(c, ctx.voidPromise())); ctx.flush(); }); messageBuffer.release(); logger.debug("Sent CloseSecureChannelRequest."); }); } private void renewSecureChannel(ChannelHandlerContext ctx) { OpenSecureChannelRequest request = new OpenSecureChannelRequest( new RequestHeader(null, DateTime.now(), 0L, 0L, null, 0L, null), PROTOCOL_VERSION, SecurityTokenRequestType.Renew, secureChannel.getMessageSecurityMode(), secureChannel.getLocalNonce(), 60 * 1000L ); sendSecureChannelRequest(ctx, request); } private void onError(ChannelHandlerContext ctx, ByteBuf buffer) { ErrorMessage error = TcpMessageDecoder.decodeError(buffer); if (error.getError() == StatusCodes.Bad_TcpSecureChannelUnknown) { secureChannel.setChannelId(0); secureChannel.setCurrentTokenId(0); secureChannel.setPreviousTokenId(-1); } logger.error("Received error message: " + error); ctx.close(); } }
package org.fi.muni.diploma.thesis.frontend.views.humantaskform; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Logger; import org.fi.muni.diploma.thesis.frontend.filterutils.CustomFilterDecorator; import org.fi.muni.diploma.thesis.frontend.filterutils.CustomFilterGenerator; import org.fi.muni.diploma.thesis.frontend.views.TaskDetailView; import org.fi.muni.diploma.thesis.frontend.views.TaskListView; import org.fi.muni.diploma.thesis.service_lifecycle_model.Service; import org.fi.muni.diploma.thesis.utils.TaskServiceWrapper; import org.fi.muni.diploma.thesis.utils.humantask.HumanTaskName; import org.fi.muni.diploma.thesis.utils.humantask.HumanTaskOutput; import org.fi.muni.diploma.thesis.utils.humantask.HumanTaskOutputType; import org.fi.muni.diploma.thesis.utils.humantask.InternalHumanTask; import org.kie.api.task.TaskService; import org.tepi.filtertable.paged.PagedFilterControlConfig; import org.tepi.filtertable.paged.PagedFilterTable; import com.vaadin.data.Container; import com.vaadin.data.Property; import com.vaadin.data.fieldgroup.FieldGroup; import com.vaadin.data.fieldgroup.FieldGroup.CommitException; import com.vaadin.data.util.BeanItem; import com.vaadin.data.util.IndexedContainer; import com.vaadin.data.util.ObjectProperty; import com.vaadin.data.util.PropertysetItem; import com.vaadin.data.validator.IntegerRangeValidator; import com.vaadin.event.FieldEvents.BlurEvent; import com.vaadin.event.FieldEvents.BlurListener; import com.vaadin.event.FieldEvents.FocusEvent; import com.vaadin.event.FieldEvents.FocusListener; import com.vaadin.navigator.Navigator; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.CheckBox; import com.vaadin.ui.Field; import com.vaadin.ui.FormLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.NativeSelect; import com.vaadin.ui.PasswordField; import com.vaadin.ui.TextArea; import com.vaadin.ui.TextField; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.BaseTheme; public class HumanTaskForm extends VerticalLayout { private static final long serialVersionUID = 1L; private InternalHumanTask humanTask; private PropertysetItem itemset; private FieldGroup binder; private Long taskid; private static final Logger logger = Logger.getLogger(HumanTaskForm.class.getName()); private TaskService taskService; public Navigator navigator; private TextField uuid; private TextField serviceName; // for storing integer final MyBean myBean = new MyBean(); BeanItem<MyBean> beanItem = new BeanItem<MyBean>(myBean); @SuppressWarnings("unchecked") final Property<Integer> integerProperty = (Property<Integer>) beanItem.getItemProperty("value"); // for presenting found services in S-RAMP repository private PagedFilterTable<?> filterTable; public class SelectListener implements ClickListener { private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { // TODO Auto-generated method stub Service service = (Service) event.getButton().getData(); HumanTaskForm.this.getUuid().setValue(service.getUUID()); HumanTaskForm.this.getServiceName().setValue(service.getName()); } } public class ButtonListener implements ClickListener { private static final long serialVersionUID = 1L; String menuitem; Boolean copy; public ButtonListener(String menuitem) { this.menuitem = menuitem; } @Override public void buttonClick(ClickEvent event) { taskService = new TaskServiceWrapper(); logger.info("button clicked"); FieldGroup data = (FieldGroup) event.getButton().getData(); try { data.commit(); } catch (CommitException e) { // TODO Auto-generated catch block e.printStackTrace(); } Long id = HumanTaskForm.this.getTaskid(); Map<String, Object> result = new HashMap<String, Object>(); Collection<Field<?>> col = data.getFields(); for (Iterator<Field<?>> iterator = col.iterator(); iterator.hasNext();) { Field<?> field = iterator.next(); logger.info("output name:" + binder.getPropertyId(field)); logger.info("output value:" + field.getValue()); logger.info("output type:" + field.getType() + "property:" + field.getPropertyDataSource().getType()); // look out for Integer if (field.getPropertyDataSource().getType().equals(Integer.class)) { logger.info("we have found integer output"); result.put((String) binder.getPropertyId(field), integerProperty.getValue()); } else { result.put((String) binder.getPropertyId(field), field.getValue()); } } taskService.start(id, "anton"); taskService.complete(id, "anton", result); HumanTaskForm.this.navigator.navigateTo("main" + "/" + TaskListView.NAME); } } public HumanTaskForm() { } @SuppressWarnings({ "unchecked" }) public HumanTaskForm(Long taskId, InternalHumanTask newInternalHumanTask, Navigator navigator) { this.humanTask = newInternalHumanTask; this.taskid = taskId; this.navigator = navigator; this.taskService = new TaskServiceWrapper(); // data binding of form this.setItemset(new PropertysetItem()); this.setBinder(new FieldGroup(this.getItemset())); Label greeting = new Label("Work on \'" + this.humanTask.getName() + "\' task"); greeting.setSizeUndefined(); greeting.setStyleName("h2"); addComponent(greeting); setComponentAlignment(greeting, Alignment.TOP_LEFT); // special processing when this task is active - we need to display INPUTS to user if (this.humanTask.getName().equals(HumanTaskName.SELECT_SERVICE_FROM_SRAMP.toString())) { logger.info("Select service from s-ramp human task requires special processing as it has also inputs"); Map<String, Object> inputs = this.taskService.getTaskContent(taskId); List<Service> services = (List<Service>) inputs.get("inServiceList"); if (services == null) { logger.info("services are null"); } else { logger.info(String.valueOf(services.size())); logger.info(services.toString()); logger.info("processing inputs"); for (Service service : services) { logger.info("service uuid:" + service.getUUID()); logger.info("service name:" + service.getName()); } // load the table with data filterTable = buildFilterTable(services); filterTable.setPageLength(filterTable.getContainerDataSource().size()); Label tableGreet = new Label("Services found in S-RAMP Repository"); tableGreet.setSizeUndefined(); tableGreet.setStyleName("h3"); addComponent(tableGreet); addComponent(filterTable); setComponentAlignment(greeting, Alignment.TOP_LEFT); setComponentAlignment(filterTable, Alignment.TOP_LEFT); // add table pagination PagedFilterControlConfig config = new PagedFilterControlConfig(); config.setItemsPerPage("Services per page:"); List<Integer> lengths = new ArrayList<Integer>(); lengths.add(10); lengths.add(20); lengths.add(50); lengths.add(100); lengths.add(250); lengths.add(500); config.setPageLengthsAndCaptions(lengths); HorizontalLayout cfg = filterTable.createControls(config); addComponent(cfg); setComponentAlignment(cfg, Alignment.TOP_LEFT); } } FormLayout fl = new FormLayout(); List<HumanTaskOutput> outputs = new ArrayList<HumanTaskOutput>(); outputs = this.humanTask.getOutputs(); // go through all outputs for this particular human task, and generate corresponding data output for (HumanTaskOutput output : outputs) { HumanTaskOutputType type = output.getDataType(); switch (type) { case BOOLEAN: { CheckBox checkbox = new CheckBox(); checkbox.setCaption(output.getLabel()); checkbox.setRequired(true); // checkbox.setValue(true); this.getItemset().addItemProperty(output.getOutputIdentifier(), new ObjectProperty<Boolean>(false)); this.getBinder().bind(checkbox, output.getOutputIdentifier()); fl.addComponent(checkbox); break; } case ENUM_STATE: { NativeSelect enumSelect = new NativeSelect(output.getLabel()); enumSelect.setRequired(true); enumSelect.setRequiredError("This field is required"); if (this.getHumanTask().getName().equals(HumanTaskName.REGISTER_EXISTING_SERVICE.toString())) { enumSelect.addItems("InTest", "Available", "Deprecated"); } this.getItemset().addItemProperty(output.getOutputIdentifier(), new ObjectProperty<String>("")); this.getBinder().bind(enumSelect, output.getOutputIdentifier()); fl.addComponent(enumSelect); break; } case INTEGER: { logger.info("adding integer output:" + output.getDataType() + "label:" + output.getLabel()); TextField integerField = new TextField(output.getLabel()); integerField.setConverter(Integer.class); // integerField.setConverter(new StringToIntegerConverter()); integerField.addValidator(new IntegerRangeValidator("Value has to be from range 0-65535", 0, 65535)); integerField.setRequired(true); integerField.setRequiredError("This field is required"); // this.getItemset().addItemProperty(output.getOutputIdentifier(), new // ObjectProperty<Integer>(((Integer)8480))); this.getItemset().addItemProperty(output.getOutputIdentifier(), integerProperty); this.getBinder().bind(integerField, output.getOutputIdentifier()); fl.addComponent(integerField); break; } case PASSWORD: { PasswordField passwordField = new PasswordField(output.getLabel()); passwordField.setRequired(true); passwordField.setRequiredError("This field is required"); this.getItemset().addItemProperty(output.getOutputIdentifier(), new ObjectProperty<String>("")); this.getBinder().bind(passwordField, output.getOutputIdentifier()); fl.addComponent(passwordField); } break; case STRING: { TextField stringField = new TextField(output.getLabel()); stringField.setRequired(true); stringField.setRequiredError("This field is required"); this.getItemset().addItemProperty(output.getOutputIdentifier(), new ObjectProperty<String>("")); this.getBinder().bind(stringField, output.getOutputIdentifier()); fl.addComponent(stringField); // we need to save the outputs of select service task explicitly due to "SELECT" functionality if (this.humanTask.getName().equals(HumanTaskName.SELECT_SERVICE_FROM_SRAMP.toString())) { if (output.getOutputIdentifier().toLowerCase().contains("uuid")) { this.setUuid(stringField); } else if (output.getOutputIdentifier().toLowerCase().contains("name")) { this.setServiceName(stringField); } } break; } case TEXT_AREA: { TextArea textArea = new TextArea(output.getLabel()); textArea.setRequired(true); textArea.setRequiredError("This field is required"); textArea.addFocusListener(new FocusListener() { private static final long serialVersionUID = 1L; @Override public void focus(FocusEvent event) { if (((TextArea) event.getComponent()).getValue().equals("Enter some description or URL pointing to the resource")) { ((TextArea) event.getComponent()).setValue(""); } } }); //this is stupid - it won't be possible to let an empty value, and it should be possible // textArea.addBlurListener(new BlurListener() { // private static final long serialVersionUID = 1L; // @Override // public void blur(BlurEvent event) { // ((TextArea) event.getComponent()).setValue("Enter some description or URL pointing to the resource"); this.getItemset().addItemProperty(output.getOutputIdentifier(), new ObjectProperty<String>("Enter some description or URL pointing to the resource")); this.getBinder().bind(textArea, output.getOutputIdentifier()); fl.addComponent(textArea); break; } default: break; } } Button submitButton = new Button("Complete Task"); submitButton.setData(this.getBinder()); submitButton.addClickListener(new ButtonListener(TaskDetailView.NAME)); fl.addComponent(submitButton); addComponent(fl); } private PagedFilterTable<?> buildFilterTable(List<Service> services) { PagedFilterTable<IndexedContainer> filterTable = new PagedFilterTable<IndexedContainer>(""); // filterTable.setSizeFull(); filterTable.setFilterDecorator(new CustomFilterDecorator()); filterTable.setFilterGenerator(new CustomFilterGenerator()); filterTable.setContainerDataSource(buildContainer(services)); filterTable.setFilterBarVisible(true); filterTable.setFilterFieldVisible("Action", false); return filterTable; } @SuppressWarnings("unchecked") private Container buildContainer(List<Service> services) { IndexedContainer cont = new IndexedContainer(); cont.addContainerProperty("Service Name", String.class, null); cont.addContainerProperty("Service UUID", String.class, null); cont.addContainerProperty("Action", Button.class, null); int i = 1; for (Service service : services) { cont.addItem(i); cont.getContainerProperty(i, "Service Name").setValue(service.getName()); cont.getContainerProperty(i, "Service UUID").setValue(service.getUUID()); Button detailsField = new Button("select"); detailsField.setData(service); detailsField.addClickListener(new SelectListener()); detailsField.addStyleName(BaseTheme.BUTTON_LINK); cont.getContainerProperty(i, "Action").setValue(detailsField); i++; } return cont; } public InternalHumanTask getHumanTask() { return humanTask; } public void setHumanTask(InternalHumanTask humanTask) { this.humanTask = humanTask; } public PropertysetItem getItemset() { return itemset; } public void setItemset(PropertysetItem itemset) { this.itemset = itemset; } public FieldGroup getBinder() { return binder; } public void setBinder(FieldGroup binder) { this.binder = binder; } public Long getTaskid() { return taskid; } public void setTaskid(Long taskid) { this.taskid = taskid; } public Navigator getNavigator() { return navigator; } public void setNavigator(Navigator navigator) { this.navigator = navigator; } public class MyBean { private int value; public int getValue() { return value; } public void setValue(int integer) { value = integer; } } public PagedFilterTable<?> getFilterTable() { return filterTable; } public void setFilterTable(PagedFilterTable<?> filterTable) { this.filterTable = filterTable; } public TextField getUuid() { return uuid; } public void setUuid(TextField uuid) { this.uuid = uuid; } public TextField getServiceName() { return serviceName; } public void setServiceName(TextField serviceName) { this.serviceName = serviceName; } }
package org.xwiki.test; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.junit.Before; import org.slf4j.Logger; import org.xwiki.component.annotation.ComponentAnnotationLoader; import org.xwiki.component.annotation.ComponentDeclaration; import org.xwiki.component.annotation.ComponentDescriptorFactory; import org.xwiki.component.descriptor.ComponentDependency; import org.xwiki.component.descriptor.ComponentDescriptor; import org.xwiki.component.descriptor.DefaultComponentDescriptor; import org.xwiki.component.internal.RoleHint; import org.xwiki.component.manager.ComponentLookupException; import org.xwiki.component.util.ReflectionUtils; import org.xwiki.test.annotation.AllComponents; import org.xwiki.test.annotation.ComponentList; import org.xwiki.test.annotation.MockingRequirement; import org.xwiki.test.annotation.MockingRequirements; /** * Unit tests for Components should extend this class instead of the older * {@link org.xwiki.test.AbstractComponentTestCase} test class. To use this class, annotate your test class with * with {@link org.xwiki.test.annotation.MockingRequirement}, passing the implementation class you're testing. * Then in your test code, do a lookup of your component under test and you'll get a component instance which has all * its injected dependencies mocked automatically. * * For example: <code><pre> * &#64;MockingRequirement(MyComponentImplementation.class) * public class MyComponentTest extends AbstractMockingComponentTestCase&lt;MyComponent&gt; * { * &#64;Test * public void someTest() throws Exception * { * MyComponent myComponent = getMockedComponent(); * ... * } * </code></pre> * * Note that by default there are no component registered against the component manager except those mocked * automatically by the {@code @MockingRequirement} annotation. This has 2 advantages: * <ul> * <li>This is the spirit of AbstractMockingComponentTestCase since they're supposed to mock all dependencies and * define their behaviors</li> * <li>It makes the tests up to 10 times faster</li> * </ul> * If you really need to register some components, use the {@link ComponentList} annotation and if you really really * need to register all components (it takes time) then use {@link AllComponents}. * * @version $Id$ * @since 2.2M1 */ public abstract class AbstractMockingComponentTestCase<T> extends AbstractMockingTestCase { private MockingComponentManager componentManager; private ComponentAnnotationLoader loader = new ComponentAnnotationLoader(); private ComponentDescriptorFactory factory = new ComponentDescriptorFactory(); private Map<Class, Logger> mockLoggers = new HashMap<Class, Logger>(); private Map<Class, RoleHint<T>> mockedComponents = new HashMap<Class, RoleHint<T>>(); /** * Extend EmbeddableComponentManager in order to mock Loggers since they're handled specially and are not * components. */ private class LogSpecificMockingComponentManager extends MockingComponentManager { private List<Class< ? >> mockedComponentClasses = new ArrayList<Class< ? >>(); public void addMockedComponentClass(Class< ? > mockedComponentClass) { this.mockedComponentClasses.add(mockedComponentClass); } @Override protected Object createLogger(Class< ? > instanceClass) { Object logger; if (this.mockedComponentClasses.contains(instanceClass)) { logger = getMockery().mock(Logger.class, instanceClass.getName()); mockLoggers.put(instanceClass, (Logger) logger); } else { logger = super.createLogger(instanceClass); } return logger; } } /** * @return the first component mocked by a {@link MockingRequirement} annotation * @since 4.2M3 */ public T getMockedComponent() throws ComponentLookupException { if (this.mockedComponents.size() == 0) { throw new RuntimeException("You need to have at least one @MockingRequirement annotation!"); } if (this.mockedComponents.size() > 1) { throw new RuntimeException("When there are several @MockingRequirement annotations you muse use the " + "getMockedComponent(mockedComponentClass) signature!"); } else { return getMockedComponent(this.mockedComponents.keySet().iterator().next()); } } /** * @param mockedComponentClass the class of the mocked component to return * @return the component mocked by a {@link MockingRequirement} annotation that is of the passed class type * @since 4.2M3 */ public T getMockedComponent(Class mockedComponentClass) throws ComponentLookupException { RoleHint<T> roleHint = this.mockedComponents.get(mockedComponentClass); return this.componentManager.getInstance(roleHint.getRoleType(), roleHint.getHint()); } /** * @return the Mock Logger if the Component under Test has requested an Injection of a Logger or null otherwise */ public Logger getMockLogger(Class< ? > mockedComponentClass) throws Exception { // Make sure that the mocked component has been loaded at least once as otherwise the Component Manager will // not have injected any mock logger at this point! getMockedComponent(mockedComponentClass); return this.mockLoggers.get(mockedComponentClass); } /** * @return the Mock Logger if the Component under Test has requested an Injection of a Logger or null otherwise */ public Logger getMockLogger() throws Exception { // Make sure that the mocked component has been loaded at least once as otherwise the Component Manager will // not have injected any mock logger at this point! getMockedComponent(); if (this.mockLoggers.size() == 1) { return this.mockLoggers.values().iterator().next(); } else if (this.mockLoggers.size() == 0) { throw new RuntimeException("You have excluded the Logger from being mocked in your @MockingRequirement!"); } else { throw new RuntimeException("When there are several @MockingRequirement annotations you muse use the " + "getMockLogger(mockRequirementInstanceClass) signature!"); } } @Before public void setUp() throws Exception { this.componentManager = new LogSpecificMockingComponentManager(); // Step 1: Register the components that are needed by the tests. registerComponents(); // Step 2: Create MockRequirement instances and register them as components for (MockingRequirement mockingRequirement : getMockingRequirements()) { List<Class< ? >> exclusions = Arrays.asList(mockingRequirement.exceptions()); // Mark the component class having its deps mocked so that our MockingEmbeddableComponentManager will // serve a mock Logger (but only if the Logger class is not in the exclusion list) if (!exclusions.contains(Logger.class)) { ((LogSpecificMockingComponentManager) this.componentManager) .addMockedComponentClass(mockingRequirement.value()); } // Handle component fields Type componentRoleType = findComponentRoleType(mockingRequirement); for (ComponentDescriptor descriptor : this.factory.createComponentDescriptors(mockingRequirement.value(), componentRoleType)) { // Only use the descriptor for the specified hint if ((mockingRequirement.hint().length() > 0 && mockingRequirement.hint().equals( descriptor.getRoleHint())) || mockingRequirement.hint().length() == 0) { registerMockDependencies(descriptor, exclusions); getComponentManager().registerComponent(descriptor); // Save the mocked component information so that the test can get an instance of this component // easily by calling getMockedComponent(...) this.mockedComponents.put(mockingRequirement.value(), new RoleHint<T>(descriptor.getRoleType(), descriptor.getRoleHint())); break; } } } } private List<MockingRequirement> getMockingRequirements() { MockingRequirements mockingRequirementsAnnotation = getClass().getAnnotation(MockingRequirements.class); List<MockingRequirement> mockingRequirements; if (mockingRequirementsAnnotation != null) { mockingRequirements = Arrays.asList(mockingRequirementsAnnotation.value()); } else { MockingRequirement mockingRequirementAnnotation = getClass().getAnnotation(MockingRequirement.class); if (mockingRequirementAnnotation != null) { mockingRequirements = Collections.singletonList(mockingRequirementAnnotation); } else { throw new RuntimeException("When extending " + AbstractMockingComponentTestCase.class.getSimpleName() + " you must have at least one @" + MockingRequirement.class.getSimpleName() + "."); } } return mockingRequirements; } /** * If the user has specified the {@link org.xwiki.test.annotation.AllComponents} annotation then all components * are lodaded; however this is not recommended since it slows down the execution time and makes the test less * controlled; we recommend instead to use the {@link ComponentList} annotation which only registers the component * implementation you pass to it; or even better don't use any annotation which means no component is registered * explicitly which should be the default since you're mocking all component dependencies with the * {@link MockingRequirement} annotation. */ private void registerComponents() { AllComponents allComponentsAnnotation = this.getClass().getAnnotation(AllComponents.class); if (allComponentsAnnotation != null) { this.loader.initialize(this.componentManager, getClass().getClassLoader()); } else { ComponentList componentListAnnotation = this.getClass().getAnnotation(ComponentList.class); if (componentListAnnotation != null) { List<ComponentDeclaration> componentDeclarations = new ArrayList<ComponentDeclaration>(); for (Class<?> componentClass : componentListAnnotation.value()) { componentDeclarations.add(new ComponentDeclaration(componentClass.getName())); } this.loader.initialize(this.componentManager, getClass().getClassLoader(), componentDeclarations); } } } private <T> void registerMockDependencies(ComponentDescriptor<T> descriptor, List<Class< ? >> exceptions) throws Exception { Collection<ComponentDependency< ? >> dependencyDescriptors = descriptor.getComponentDependencies(); for (ComponentDependency< ? > dependencyDescriptor : dependencyDescriptors) { Class<?> roleTypeClass = ReflectionUtils.getTypeClass(dependencyDescriptor.getRoleType()); // Only register a mock if it isn't: // - An explicit exception specified by the user // - A logger // - A collection of components, we want to keep them as Java collections. Those collections are later // filled by the component manager with available components. Developers can register mocked components // in an override of #setupDependencies(). // TODO: Handle multiple roles/hints. if (!exceptions.contains(roleTypeClass) && Logger.class != roleTypeClass && !roleTypeClass.isAssignableFrom(List.class) && !roleTypeClass.isAssignableFrom(Map.class)) { DefaultComponentDescriptor cd = new DefaultComponentDescriptor(); cd.setRoleType(dependencyDescriptor.getRoleType()); cd.setRoleHint(dependencyDescriptor.getRoleHint()); this.componentManager.registerComponent( cd, getMockery().mock(ReflectionUtils.getTypeClass(dependencyDescriptor.getRoleType()), dependencyDescriptor.getName())); } } } private Type findComponentRoleType(MockingRequirement mockingRequirement) { Type componentRoleType; Set<Type> componentRoleTypes = this.loader.findComponentRoleTypes(mockingRequirement.value()); Class< ? > role = mockingRequirement.role(); if (!Object.class.getName().equals(role.getName())) { if (!componentRoleTypes.contains(role)) { throw new RuntimeException("Specified Component Role not found in component"); } else { componentRoleType = role; } } else { if (componentRoleTypes.isEmpty()) { throw new RuntimeException( String.format("Couldn't find roles for component [%s]", mockingRequirement.value())); } else if (componentRoleTypes.size() > 1) { throw new RuntimeException("Components with several roles must explicitly specify which role to use."); } else { componentRoleType = componentRoleTypes.iterator().next(); } } return componentRoleType; } /** * @return a configured Component Manager */ @Override public MockingComponentManager getComponentManager() throws Exception { return this.componentManager; } }
package org.opendaylight.yangtools.yang.parser.spi.meta; import static com.google.common.base.Verify.verifyNotNull; import com.google.common.annotations.Beta; import com.google.common.base.VerifyException; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import org.opendaylight.yangtools.concepts.Immutable; import org.opendaylight.yangtools.yang.common.QName; import org.opendaylight.yangtools.yang.common.QNameModule; import org.opendaylight.yangtools.yang.model.api.DataSchemaNode; import org.opendaylight.yangtools.yang.model.api.SchemaNode; import org.opendaylight.yangtools.yang.model.api.SchemaNodeDefaults; import org.opendaylight.yangtools.yang.model.api.SchemaPath; import org.opendaylight.yangtools.yang.model.api.meta.DeclaredStatement; import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement; /** * Effective view of a {@link StmtContext} for the purposes of creating an {@link EffectiveStatement}. */ @Beta public interface EffectiveStmtCtx extends CommonStmtCtx, StmtContextCompat, Immutable { /** * Return parent of this context, if there is one. All statements except for top-level source statements, such as * {@code module} and {@code submodule}. * * @return Parent context, or null if this statement is the root */ @Nullable Parent effectiveParent(); /** * Return parent of this context. * * @return Parent context * @throws VerifyException if this context is already the root */ default @NonNull Parent getEffectiveParent() { return verifyNotNull(effectiveParent(), "Attempted to access beyond root context"); } /** * Minimum amount of parent state required to build an accurate effective view of a particular child. Child state * is expressed as {@link Current}. */ @Beta interface Parent extends EffectiveStmtCtx { /** * Effective {@code config} statement value. */ @Beta enum EffectiveConfig { /** * We have an effective {@code config true} statement. */ TRUE(Boolean.TRUE), /** * We have an effective {@code config false} statement. */ FALSE(Boolean.FALSE), /** * We are in a context where {@code config} statements are ignored. */ IGNORED(null), /** * We are in a context where {@code config} is not determined, such as within a {@code grouping}. */ UNDETERMINED(null); private final Boolean config; EffectiveConfig(final @Nullable Boolean config) { this.config = config; } /** * Return this value as a {@link Boolean} for use with {@link DataSchemaNode#effectiveConfig()}. * * @return A boolean or null */ public @Nullable Boolean asNullable() { return config; } } /** * Return the effective {@code config} statement value. * * @return This statement's effective config */ @NonNull EffectiveConfig effectiveConfig(); // FIXME: 7.0.0: this is currently only used by AbstractTypeStatement @NonNull QNameModule effectiveNamespace(); /** * Return the effective path of this statement. This method is intended for use with statements which naturally * have a {@link QName} identifier and this identifier forms the ultimate step in their * {@link SchemaNode#getPath()}. * * <p> * Returned object conforms to {@link SchemaPathSupport}'s view of how these are to be handled. Users of this * method are expected to consult {@link SchemaPathSupport#extractQName(Object)} and * {@link SchemaPathSupport#extractPath(Object, Object)} to ensure correct implementation behaviour with respect * to {@link SchemaNode#getQName()} and {@link SchemaNode#getPath()} respectively. * * @return An effective path object */ // FIXME: Remove this when SchemaNode.getPath() is removed. QName users will store getArgument() instead. default @NonNull Object effectivePath() { return SchemaPathSupport.toEffectivePath(getSchemaPath()); } /** * Return an optional-to-provide path for {@link SchemaNode#getPath()}. The result of this method is expected * to be consulted with {@link SchemaNodeDefaults#throwUnsupportedIfNull(Object, SchemaPath)} to get consistent * API behaviour. * * @return Potentially-null {@link SchemaPath}. */ // FIXME: Remove this when SchemaNode.getPath() is removed default @Nullable SchemaPath optionalPath() { return SchemaPathSupport.toOptionalPath(getSchemaPath()); } /** * Return the {@link SchemaNode#getPath()} of this statement. Not all statements have a SchemaPath, in which * case null is returned. * * @return SchemaPath or null */ // FIXME: Remove this when SchemaNode.getPath() is removed @Nullable SchemaPath schemaPath(); /** * Return the {@link SchemaNode#getPath()} of this statement, failing if it is not present. * * @return A SchemaPath. * @throws VerifyException if {@link #schemaPath()} returns null */ // FIXME: Remove this when SchemaNode.getPath() is removed default @NonNull SchemaPath getSchemaPath() { return verifyNotNull(schemaPath(), "Missing path for %s", this); } } /** * Minimum amount of state required to build an accurate effective view of a statement. This is a strict superset * of information available in {@link Parent}. * * @param <A> Argument type * @param <D> Class representing declared version of this statement */ @Beta interface Current<A, D extends DeclaredStatement<A>> extends Parent, NamespaceStmtCtx, BoundStmtCtxCompat<A, D> { @NonNull QName moduleName(); @Nullable EffectiveStatement<?, ?> original(); // FIXME: 7.0.0: this method should be moved to stmt.type in some shape or form @NonNull QName argumentAsTypeQName(); // FIXME: YANGTOOLS-1186: lob the Holy Hand Grenade of Antioch @Deprecated <E extends EffectiveStatement<A, D>> @NonNull StmtContext<A, D, E> caerbannog(); /** * Compare another context for equality of {@code getEffectiveParent().getSchemaPath()}, just in a safer manner. * * @param other Other {@link Current} * @return True if {@code other} has parent path equal to this context's parent path. */ // FIXME: Remove this when SchemaNode.getPath() is removed default boolean equalParentPath(final Current<A, D> other) { final Parent ours = effectiveParent(); final Parent theirs = other.effectiveParent(); return ours == theirs || ours != null && theirs != null && SchemaPathSupport.effectivelyEqual( ours.schemaPath(), theirs.schemaPath()); } } }
package crazypants.enderio.conduit.item; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.ISidedInventory; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.world.World; import net.minecraftforge.common.ForgeDirection; import cpw.mods.fml.common.TickType; import crazypants.enderio.Config; import crazypants.enderio.conduit.AbstractConduitNetwork; import crazypants.enderio.conduit.ConduitNetworkTickHandler; import crazypants.enderio.conduit.ConduitNetworkTickHandler.TickListener; import crazypants.enderio.conduit.ConnectionMode; import crazypants.enderio.conduit.IConduit; import crazypants.enderio.conduit.item.ItemConduitNetwork.NetworkedInventory.Target; import crazypants.util.BlockCoord; import crazypants.util.InventoryWrapper; import crazypants.util.ItemUtil; import crazypants.util.Lang; public class ItemConduitNetwork extends AbstractConduitNetwork<IItemConduit, IItemConduit> { private long timeAtLastApply; private final List<NetworkedInventory> inventories = new ArrayList<ItemConduitNetwork.NetworkedInventory>(); private final Map<BlockCoord, List<NetworkedInventory>> invMap = new HashMap<BlockCoord, List<ItemConduitNetwork.NetworkedInventory>>(); private final Map<BlockCoord, IItemConduit> conMap = new HashMap<BlockCoord, IItemConduit>(); private boolean requiresSort = true; private final InnerTickHandler tickHandler = new InnerTickHandler(); public ItemConduitNetwork() { super(IItemConduit.class); } @Override public Class<IItemConduit> getBaseConduitType() { return IItemConduit.class; } @Override public void addConduit(IItemConduit con) { super.addConduit(con); conMap.put(con.getLocation(), con); TileEntity te = con.getBundle().getEntity(); if(te != null) { for (ForgeDirection direction : con.getExternalConnections()) { IInventory extCon = con.getExternalInventory(direction); if(extCon != null) { inventoryAdded(con, direction, te.xCoord + direction.offsetX, te.yCoord + direction.offsetY, te.zCoord + direction.offsetZ, extCon); } } } } public void inventoryAdded(IItemConduit itemConduit, ForgeDirection direction, int x, int y, int z, IInventory externalInventory) { BlockCoord bc = new BlockCoord(x, y, z); NetworkedInventory inv = new NetworkedInventory(externalInventory, itemConduit, direction, bc); inventories.add(inv); getOrCreate(bc).add(inv); requiresSort = true; } private List<NetworkedInventory> getOrCreate(BlockCoord bc) { List<NetworkedInventory> res = invMap.get(bc); if(res == null) { res = new ArrayList<ItemConduitNetwork.NetworkedInventory>(); invMap.put(bc, res); } return res; } public void inventoryRemoved(ItemConduit itemConduit, int x, int y, int z) { BlockCoord bc = new BlockCoord(x, y, z); List<NetworkedInventory> invs = getOrCreate(bc); NetworkedInventory remove = null; for (NetworkedInventory ni : invs) { if(ni.con.getLocation().equals(itemConduit.getLocation())) { remove = ni; break; } } if(remove != null) { invs.remove(remove); inventories.remove(remove); requiresSort = true; } } public void routesChanged() { requiresSort = true; } public ItemStack sendItems(ItemConduit itemConduit, ItemStack item, ForgeDirection side) { if(item == null) { return item; } BlockCoord loc = itemConduit.getLocation().getLocation(side); ItemStack result = item.copy(); List<NetworkedInventory> invs = getOrCreate(loc); for (NetworkedInventory inv : invs) { if(inv.con.getLocation().equals(itemConduit.getLocation())) { int numInserted = inv.insertIntoTargets(item.copy()); if(numInserted >= item.stackSize) { //TODO: I was returning null here as per the API but quarries plus //was interpreting this as nothing being taken result = item.copy(); result.stackSize = 0; return result; } result.stackSize -= numInserted; } } return result; } public List<String> getTargetsForExtraction(BlockCoord extractFrom, IItemConduit con, ItemStack input) { List<String> result = new ArrayList<String>(); List<NetworkedInventory> invs = getOrCreate(extractFrom); for (NetworkedInventory source : invs) { if(source.con.getLocation().equals(con.getLocation())) { if(source != null && source.sendPriority != null) { for (Target t : source.sendPriority) { ItemFilter f = t.inv.con.getOutputFilter(t.inv.conDir); if(input == null || f == null || f.doesItemPassFilter(input)) { String s = Lang.localize(t.inv.inv.getInvName(), false) + " " + t.inv.location + " Distance [" + t.distance + "] "; result.add(s); } } } } } return result; } public List<String> getInputSourcesFor(IItemConduit con, ForgeDirection dir, ItemStack input) { List<String> result = new ArrayList<String>(); for (NetworkedInventory inv : inventories) { if(inv.hasTarget(con, dir)) { ItemFilter f = inv.con.getInputFilter(inv.conDir); if(input == null || f == null || f.doesItemPassFilter(input)) { result.add(Lang.localize(inv.inv.getInvName(), false)); } } } return result; } private boolean isRemote(ItemConduit itemConduit) { World world = itemConduit.getBundle().getEntity().worldObj; if(world != null && world.isRemote) { return true; } return false; } @Override public void onUpdateEntity(IConduit conduit) { World world = conduit.getBundle().getEntity().worldObj; if(world == null) { return; } if(world.isRemote) { return; } long curTime = world.getTotalWorldTime(); if(curTime != timeAtLastApply) { timeAtLastApply = curTime; tickHandler.tick = world.getTotalWorldTime(); ConduitNetworkTickHandler.instance.addListener(tickHandler); } } private void doTick(long tick) { // long start = System.nanoTime(); for (NetworkedInventory ni : inventories) { if(requiresSort) { ni.updateInsertOrder(); } ni.onTick(tick); } // if(requiresSort) { // long took = System.nanoTime() - start; // double secs = took / 1000000000.0; // System.out.println("Sortinging item network: took " + took + " nano " + secs + " secs, " + (secs * 1000) + " millis"); requiresSort = false; } static int compare(int x, int y) { return (x < y) ? -1 : ((x == y) ? 0 : 1); } private static int MAX_SLOT_CHECK_PER_TICK = 64; class NetworkedInventory { ISidedInventory inv; IItemConduit con; ForgeDirection conDir; BlockCoord location; int inventorySide; List<Target> sendPriority = new ArrayList<Target>(); private int extractFromSlot = -1; int tickDeficit; //work around for a vanilla chest changing into a double chest without doing unnedded checks all the time boolean recheckInv = false; private int delay = 0; IInventory origInv; NetworkedInventory(IInventory inv, IItemConduit con, ForgeDirection conDir, BlockCoord location) { inventorySide = conDir.getOpposite().ordinal(); this.con = con; this.conDir = conDir; this.location = location; if(inv instanceof ISidedInventory) { this.inv = (ISidedInventory) inv; } else { if(inv instanceof TileEntityChest) { recheckInv = true; } this.inv = new InventoryWrapper(inv); } } public boolean hasTarget(IItemConduit conduit, ForgeDirection dir) { for (Target t : sendPriority) { if(t.inv.con == conduit && t.inv.conDir == dir) { return true; } } return false; } boolean canExtract() { ConnectionMode mode = con.getConectionMode(conDir); return mode == ConnectionMode.INPUT || mode == ConnectionMode.IN_OUT; } boolean canInsert() { ConnectionMode mode = con.getConectionMode(conDir); return mode == ConnectionMode.OUTPUT || mode == ConnectionMode.IN_OUT; } boolean isSticky() { return con.getOutputFilter(conDir).isValid() && con.getOutputFilter(conDir).isSticky(); } public void onTick(long tick) { int transfered; if(tickDeficit > 0 || !canExtract() || !con.isExtractionRedstoneConditionMet(conDir)) { //do nothing } else { transferItems(); } tickDeficit if(tickDeficit < -1) { //Sleep for a second before checking again. tickDeficit = 20; } } private boolean canExtractThisTick(long tick) { if(!con.isExtractionRedstoneConditionMet(conDir)) { return false; } return true; } private int nextSlot(int numSlots) { ++extractFromSlot; if(extractFromSlot >= numSlots || extractFromSlot < 0) { extractFromSlot = 0; } return extractFromSlot; } private void setNextStartingSlot(int slot) { extractFromSlot = slot; extractFromSlot } private boolean transferItems() { if(recheckInv) { //Re-check vanilla chests twice a second to make sure they haven't become double chests delay++; if(delay % 10 == 0) { inv = new InventoryWrapper(((InventoryWrapper) inv).getWrappedInv()); delay = 0; } } int[] slotIndices = inv.getAccessibleSlotsFromSide(inventorySide); if(slotIndices == null) { return false; } int numSlots = slotIndices.length; ItemStack extractItem = null; int maxExtracted = con.getMaximumExtracted(); int slot = -1; int slotChecksPerTick = Math.min(numSlots, MAX_SLOT_CHECK_PER_TICK); for (int i = 0; i < slotChecksPerTick; i++) { int index = nextSlot(numSlots); slot = slotIndices[index]; ItemStack item = inv.getStackInSlot(slot); if(canExtractItem(item)) { extractItem = item.copy(); if(inv.canExtractItem(slot, extractItem, inventorySide)) { if(doTransfer(extractItem, slot, maxExtracted)) { setNextStartingSlot(slot); return true; } } } } return false; } private boolean canExtractItem(ItemStack itemStack) { if(itemStack == null) { return false; } ItemFilter filter = con.getInputFilter(conDir); if(filter == null) { return true; } return filter.doesItemPassFilter(itemStack); } private boolean doTransfer(ItemStack extractedItem, int slot, int maxExtract) { if(extractedItem == null) { return false; } ItemStack toExtract = extractedItem.copy(); toExtract.stackSize = Math.min(maxExtract, toExtract.stackSize); int numInserted = insertIntoTargets(toExtract); if(numInserted <= 0) { return false; } ItemStack curStack = inv.getStackInSlot(slot); if(curStack != null) { curStack = curStack.copy(); curStack.stackSize -= numInserted; if(curStack.stackSize > 0) { inv.setInventorySlotContents(slot, curStack); inv.onInventoryChanged(); } else { inv.setInventorySlotContents(slot, null); inv.onInventoryChanged(); } } con.itemsExtracted(numInserted, slot); tickDeficit = Math.round(numInserted * con.getTickTimePerItem()); return true; } private int insertIntoTargets(ItemStack toExtract) { if(toExtract == null) { return 0; } int totalToInsert = toExtract.stackSize; int leftToInsert = totalToInsert; boolean matchedStickyInput = false; for (Target target : sendPriority) { if(target.stickyInput && !matchedStickyInput) { ItemFilter of = target.inv.con.getOutputFilter(target.inv.conDir); matchedStickyInput = of.isValid() && of.doesItemPassFilter(toExtract); } if(target.stickyInput || !matchedStickyInput) { int inserted = target.inv.insertItem(toExtract); if(inserted > 0) { toExtract.stackSize -= inserted; leftToInsert -= inserted; } if(leftToInsert <= 0) { return totalToInsert; } } } return totalToInsert - leftToInsert; } private int insertItem(ItemStack item) { if(!canInsert() || item == null) { return 0; } ItemFilter filter = con.getOutputFilter(conDir); if(filter != null) { if(!filter.doesItemPassFilter(item)) { return 0; } } return ItemUtil.doInsertItem(inv, item, ForgeDirection.values()[inventorySide]); } void updateInsertOrder() { sendPriority.clear(); if(!canExtract()) { return; } //Map<BlockCoord, Target> result = new HashMap<BlockCoord, Target>(); List<Target> result = new ArrayList<ItemConduitNetwork.NetworkedInventory.Target>(); for (NetworkedInventory other : inventories) { if((con.isSelfFeedEnabled(conDir) || (other != this)) && other.canInsert() && con.getInputColor(conDir) == other.con.getOutputColor(other.conDir)) { if(Config.itemConduitUsePhyscialDistance) { sendPriority.add(new Target(other, distanceTo(other), other.isSticky())); } else { //result.put(other.location, new Target(other, 9999999, other.isSticky())); result.add(new Target(other, 9999999, other.isSticky())); } } } if(Config.itemConduitUsePhyscialDistance) { Collections.sort(sendPriority); } else { if(!result.isEmpty()) { Map<BlockCoord, Integer> visited = new HashMap<BlockCoord, Integer>(); List<BlockCoord> steps = new ArrayList<BlockCoord>(); steps.add(con.getLocation()); calculateDistances(result, visited, steps, 0); sendPriority.addAll(result); Collections.sort(sendPriority); } } } private void calculateDistances(List<Target> targets, Map<BlockCoord, Integer> visited, List<BlockCoord> steps, int distance) { if(steps == null || steps.isEmpty()) { return; } ArrayList<BlockCoord> nextSteps = new ArrayList<BlockCoord>(); for (BlockCoord bc : steps) { IItemConduit con = conMap.get(bc); if(con != null) { for (ForgeDirection dir : con.getExternalConnections()) { Target target = getTarget(targets, con, dir); if(target != null && target.distance > distance) { target.distance = distance; } } if(!visited.containsKey(bc)) { visited.put(bc, distance); } else { int prevDist = visited.get(bc); if(prevDist <= distance) { continue; } visited.put(bc, distance); } for (ForgeDirection dir : con.getConduitConnections()) { nextSteps.add(bc.getLocation(dir)); } } } calculateDistances(targets, visited, nextSteps, distance + 1); } private Target getTarget(List<Target> targets, IItemConduit con, ForgeDirection dir) { for (Target target : targets) { if(target.inv.conDir == dir && target.inv.con.getLocation().equals(con.getLocation())) { return target; } } return null; } private int distanceTo(NetworkedInventory other) { return con.getLocation().distanceSquared(other.con.getLocation()); } class Target implements Comparable<Target> { NetworkedInventory inv; int distance; boolean stickyInput; Target(NetworkedInventory inv, int distance, boolean stickyInput) { this.inv = inv; this.distance = distance; this.stickyInput = stickyInput; } @Override public int compareTo(Target o) { if(stickyInput && !o.stickyInput) { return -1; } if(!stickyInput && o.stickyInput) { return 1; } return compare(distance, o.distance); } } } private class InnerTickHandler implements TickListener { long tick; @Override public void tickStart(EnumSet<TickType> type, Object... tickData) { } @Override public void tickEnd(EnumSet<TickType> type, Object... tickData) { doTick(tick); } } }
package nu.validator.servlet; import java.io.IOException; import java.io.Writer; import java.util.Map; import java.util.TreeMap; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.ext.LexicalHandler; public class TreeDumpContentHandler implements ContentHandler, LexicalHandler { private final Writer writer; private int level = 0; private boolean inCharacters = false; private boolean close; /** * @param writer */ public TreeDumpContentHandler(final Writer writer, boolean close) { this.writer = writer; this.close = close; } public TreeDumpContentHandler(final Writer writer) { this(writer, true); } private void printLead() throws IOException { if (inCharacters) { writer.write("\"\n"); inCharacters = false; } writer.write("| "); for (int i = 0; i < level; i++) { writer.write(" "); } } public void characters(char[] ch, int start, int length) throws SAXException { try { if (!inCharacters) { printLead(); writer.write('"'); inCharacters = true; } writer.write(ch, start, length); } catch (IOException e) { throw new SAXException(e); } } public void endElement(String uri, String localName, String qName) throws SAXException { try { if (inCharacters) { writer.write("\"\n"); inCharacters = false; } level } catch (IOException e) { throw new SAXException(e); } } public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { try { printLead(); writer.write('<'); if ("http: writer.write("math "); } else if ("http: writer.write("svg "); } writer.write(localName); writer.write(">\n"); level++; TreeMap<String, String> map = new TreeMap<String, String>(); for (int i = 0; i < atts.getLength(); i++) { String ns = atts.getURI(i); String name; if ("http: name = "xlink " + atts.getLocalName(i); } else if ("http: name = "xml " + atts.getLocalName(i); } else if ("http: name = "xmlns " + atts.getLocalName(i); } else { name = atts.getLocalName(i); } map.put(name, atts.getValue(i)); } for (Map.Entry<String, String> entry : map.entrySet()) { printLead(); writer.write(entry.getKey()); writer.write("=\""); writer.write(entry.getValue()); writer.write("\"\n"); } } catch (IOException e) { throw new SAXException(e); } } public void comment(char[] ch, int offset, int len) throws SAXException { try { printLead(); writer.write("<! writer.write(ch, offset, len); writer.write(" } catch (IOException e) { throw new SAXException(e); } } public void startDTD(String name, String publicIdentifier, String systemIdentifier) throws SAXException { try { printLead(); writer.write("<!DOCTYPE "); writer.write(name); if (publicIdentifier.length() > 0 || systemIdentifier.length() > 0) { writer.write(' '); writer.write('\"'); writer.write(publicIdentifier); writer.write('\"'); writer.write(' '); writer.write('\"'); writer.write(systemIdentifier); writer.write('\"'); } writer.write(">\n"); } catch (IOException e) { throw new SAXException(e); } } public void endDocument() throws SAXException { try { if (inCharacters) { writer.write("\"\n"); inCharacters = false; } if (close) { writer.flush(); writer.close(); } } catch (IOException e) { throw new SAXException(e); } } public void startPrefixMapping(String prefix, String uri) throws SAXException { } public void startEntity(String arg0) throws SAXException { } public void endCDATA() throws SAXException { } public void endDTD() throws SAXException { } public void endEntity(String arg0) throws SAXException { } public void startCDATA() throws SAXException { } public void endPrefixMapping(String prefix) throws SAXException { } public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { } public void processingInstruction(String target, String data) throws SAXException { } public void setDocumentLocator(Locator locator) { } public void skippedEntity(String name) throws SAXException { } public void startDocument() throws SAXException { } }
package org.openecard.common.apdu; import iso.std.iso_iec._24727.tech.schema.Transmit; import java.util.ArrayList; import org.openecard.common.apdu.common.CardCommandAPDU; import org.openecard.common.util.ByteUtils; import org.openecard.common.util.ShortUtils; /** * * @author Moritz Horsch <horsch@cdc.informatik.tu-darmstadt.de> * @author Johannes Schmoelz <johannes.schmoelz@ecsec.de> * @author Tobias Wich <tobias.wich@ecsec.de> */ public class ReadBinary extends CardCommandAPDU { /** * READ BINARY command instruction byte. INS = 0xB0 */ private static final byte READ_BINARY_INS_1 = (byte) 0xB0; /** * READ BINARY command instruction byte. INS = 0xB1 */ private static final byte READ_BINARY_INS_2 = (byte) 0xB1; /** * Creates an new READ BINARY APDU. */ public ReadBinary() { super(x00, READ_BINARY_INS_1, x00, xFF); } /** * Creates an new READ BINARY APDU. * * @param offset Offset */ public ReadBinary(byte offset) { super(x00, READ_BINARY_INS_1, offset, xFF); } /** * Creates an new READ BINARY APDU. * * @param offset Offset * @param length Expected length */ public ReadBinary(byte offset, byte length) { super(x00, READ_BINARY_INS_1, offset, length); } /** * Creates an new READ BINARY APDU. * Bit 8 of P1 is set to 1, bits 7 and 6 of P1 are set to 00 (RFU), * bits 5 to 1 of P1 encode a short EF identifier and P2 (eight bits) * encodes an offset from zero to 255. * * @param shortFileID Short file identifier * @param offset Offset * @param length Expected length */ public ReadBinary(byte shortFileID, byte offset, short length) { super(x00, READ_BINARY_INS_1, (byte) ((0x1F & shortFileID) | 0x80), offset); setLE(length); } /** * Creates an new READ BINARY APDU. * Bit 8 of P1 is set to 0, and P1-P2 (fifteen bits) encodes an * offset from zero to 32 767. * * @param offset Offset * @param length Expected length */ public ReadBinary(short offset, byte length) { setINS(READ_BINARY_INS_1); setP1((byte) (((byte) (offset >> 8)) & 0x7F)); setP2((byte) (offset & xFF)); setLE(length); } /** * Creates an new READ BINARY APDU. * Bit 8 of P1 is set to 0, and P1-P2 (fifteen bits) encodes an * offset from zero to 32 767. * * @param offset Offset * @param length Expected length */ public ReadBinary(short offset, short length) { setINS(READ_BINARY_INS_1); setP1((byte) (((byte) (offset >> 8)) & 0x7F)); setP2((byte) (offset & xFF)); setLE(length); } /** * Creates an new READ BINARY APDU. * P1-P2 set to '0000' identifies the current EF. * The offset data object with tag '54' is encoded in the command data field. * * @param fileID File identifier * @param offset Offset * @param length Expected length */ public ReadBinary(short fileID, short offset, short length) { super(x00, READ_BINARY_INS_2, x00, x00); byte[] content = ShortUtils.toByteArray(offset); content = ByteUtils.concatenate((byte) 0x54, content); setP1P2(ShortUtils.toByteArray(fileID)); setData(content); setLE(length); } /** * Creates a new Transmit message. * * @param slotHandle Slot handle * @return Transmit */ @Override public Transmit makeTransmit(byte[] slotHandle) { ArrayList<byte[]> defaultResponses = new ArrayList<byte[]>() { { add(new byte[]{(byte) 0x90, (byte) 0x00}); add(new byte[]{(byte) 0x62, (byte) 0x82}); } }; return makeTransmit(slotHandle, defaultResponses); } }
package com.saucelabs.common; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.*; public class SauceHelperTest { private SauceHelper sauceHelper; @Before public void runBeforeEveryTest() { sauceHelper = new SauceHelper(); } @Test public void shouldReturnPassedForTrueResult() { assertStringsEqual("sauce:job-result=", true); } @Test public void shouldReturnFailedForFalseResult() { assertStringsEqual("sauce:job-result=", false); } @Test public void shouldReturnCorrectStringForTestName() { String testName = "MyTestName"; assertEquals("sauce:job-name=" + testName, sauceHelper.getTestNameString(testName)); } @Test public void shouldReturnSauceContextString() { String comment = "This is a comment"; assertEquals("sauce:context=" + comment, sauceHelper.getCommentString(comment)); } @Test public void shouldRunExecuteStringMethodWithoutDefaultManagerSet() { JavaScriptInvokerManager javascriptExecutor = mock(JavaScriptInvokerManager.class); JavaScriptInvokerFactory.setJavaScriptInvoker(javascriptExecutor); sauceHelper.setTestStatus("pass"); verify(javascriptExecutor, times(1)).executeScript("sauce:job-result=pass"); } private void assertStringsEqual(String s, boolean b) { assertEquals(s + b, sauceHelper.getTestResultString(b)); } }
package hu.qgears.images; import hu.qgears.commons.AbstractReferenceCountedDisposeable; import hu.qgears.commons.mem.INativeMemory; import hu.qgears.commons.mem.INativeMemoryAllocator; import hu.qgears.images.text.RGBAColor; import java.nio.ByteBuffer; /** * Image in native memory that can be accessed as: * * OpenGL texture * * source for native filters * * target as native webcam implementation. * @author rizsi * */ public class NativeImage extends AbstractReferenceCountedDisposeable { /** * The transparent marker bit mask in the returned value of getTransparentOrOpaqueMask() method. * The returned value means transparent when getTransparentOrOpaqueMask()&transparentBit!=0 */ public static final int transparentBit=1; /** * The opaque marker bit mask in the returned value of getTransparentOrOpaqueMask() method. * The returned value means opaque when getTransparentOrOpaqueMask()&opaqueBit!=0 */ public static final int opaqueBit=2; private INativeMemory buffer; private ByteBuffer nbuffer; private SizeInt size; private ENativeImageComponentOrder componentOrder; private int nChannels; private int width; private ENativeImageAlphaStorageFormat alphaStorageFormat=ENativeImageAlphaStorageFormat.normal; /** The alignment of rows to memory */ private int alignment; /** The length of one row and padding (required by alignment) in memory */ private int step; /** * Stores cached transparency and opacity information. BIG FAT WARNING: the * value of this variable may be considered correct only if the image has been * loaded using {@link UtilNativeImageIo#loadImageFromFile(java.io.File)} or * {@link UtilNativeImageIo#loadImageFromFile(INativeMemory)}, or, if the * image has been created another way, {@link #getTransparentOrOpaqueMask()} * is called previously. * In case the image is modified since calculation of this flag this flag will be incorrect! */ private int transparentOrOpaqueMask = -1; /** * The default alignment of native image rows to memory. * this means that all row start an an address that: ptrRow%defaultAlignment=0 */ public static int defaultAlignment=1; /** * The alignment that allows compatibility with openCV. */ public static int compatibleAlignment=4; /** * Create a native image from existing data. * @param buffer see getBuffer() * @param size see getSize() * @param componentOrder see getComponentOrder() * @param alignemnt see getAlignment() */ public NativeImage(INativeMemory buffer, SizeInt size, ENativeImageComponentOrder componentOrder, int alignment) { super(); init(buffer, size, componentOrder, alignment); } private void init(INativeMemory buffer, SizeInt size, ENativeImageComponentOrder componentOrder, int alignment) { this.buffer = buffer; this.size=size; this.componentOrder=componentOrder; this.nChannels=componentOrder.getNCHannels(); this.width=size.getWidth(); this.alignment=alignment; this.step=getStep(this.width, componentOrder, alignment); this.nbuffer=buffer.getJavaAccessor(); } /** * Get the memory buffer that contains image pixel data. * @return */ public INativeMemory getBuffer() { return buffer; } /** * Get the width of the image in pixels. * @return */ public int getWidth() { return size.getWidth(); } /** * Get the height of the image in pixels. * @return */ public int getHeight() { return size.getHeight(); } /** * Get the pixel data storage format of the image. * @return */ public ENativeImageComponentOrder getComponentOrder() { return componentOrder; } /** * Get the size of the image in pixels. * @return */ public SizeInt getSize() { return size; } /** * Get the image pixel data of the given pixel and channel. * @param x * @param y * @param channel * @return pixel data value of the channel */ public byte getChannel(int x, int y, int channel) { return nbuffer.get(y*step+x*nChannels+channel); } /** * Set the image pixel data of the given channel. * @param x * @param y * @param channel * @param value * @return */ public NativeImage setChannel(int x, int y, int channel, byte value) { nbuffer.put(y*step+x*nChannels+channel, value); return this; } /** * Create a native image that has the specified size, component order * and alignment. * @param size * @param componentOrder * @param alignment * @param allocator memory allocator to be used to allocate space for image. * @return */ public static NativeImage create( SizeInt size, ENativeImageComponentOrder componentOrder, int alignment, INativeMemoryAllocator allocator) { int step=getStep(size.getWidth(), componentOrder, alignment); INativeMemory buffer=allocator.allocateNativeMemory(step*size.getHeight(), alignment); return new NativeImage(buffer, size, componentOrder, alignment); } /** * Create a native image that has the specified size, component order * and alignment. * @param size * @param componentOrder * @param allocator memory allocator to be used to allocate space for image. * @return */ public static NativeImage create( SizeInt size, ENativeImageComponentOrder componentOrder, INativeMemoryAllocator allocator) { int alignment=allocator.getDefaultAlignment(); int step=getStep(size.getWidth(), componentOrder, alignment); INativeMemory buffer=allocator.allocateNativeMemory(step*size.getHeight()); return new NativeImage(buffer, size, componentOrder, alignment); } /** * Get the length of a line of the image data in bytes. * @param width width of the image in pixels * @param co pixel data format * @param alignment storage alignment of the image. * @return */ public static int getStep(int width, ENativeImageComponentOrder co, int alignment) { int step=width*co.getNCHannels(); int mod=step% alignment; if(mod>0) { step+=alignment-mod; } return step; } /** * Copy the rectangular area from the source image into this image. * * Target is this image at 0,0 * @param src * @param x the left corner of source * @param y the top corner of source */ public void copyFromSource(NativeImage src, int x, int y) { copyFromSource(src, x, y, 0, 0); } /** * Copy the rectangular area from the source image into this image. * Target is this image at tgX, tgY * @param src * @param x the left corner of source * @param y the top corner of source * @param tgX * @param tgY */ public void copyFromSource(NativeImage src, int x, int y, int tgX, int tgY) { copyFromSource(src, x, y, tgX, tgY, false); } /** * Do pixel copying from a source image using pixel data conversion. * @param src * @param x * @param y * @param tgX * @param tgY */ private void convertFromSource(NativeImage src, int x, int y, int tgX, int tgY) { int w=Math.min(src.getSize().getWidth()-x, getSize().getWidth()-tgX); int h=Math.min(src.getSize().getHeight()-y, getSize().getHeight()-tgY); for(int j=0;j<h;++j) { for(int i=0;i<w;++i) { int pixel=src.getPixel(i+x, j+y); setPixel(tgX+i, tgY+j, pixel); } } } /** * Copy the rectangular area beginning from the (x,y) coordinate from source * image into this image beginning with (tgX,tgY) in this image. * * Width and height of the resulting image is the minimum of the two images. * * @param src source {@link NativeImage} * @param x the left corner of source * @param y the top corner of source * @param tgX the left corner of target * @param tgY the top corner of target * @param processFromPosition * if true, processing of data from the current position of the * source image's buffer will be performed instead of position 0 */ private void copyFromSource(NativeImage src, int x, int y, int tgX, int tgY, boolean processFromPosition) { if (!src.getComponentOrder().equals(getComponentOrder())) { convertFromSource(src, x, y, tgX, tgY); return; } int nc = src.getnChannels(); ByteBuffer srcb = src.getBuffer().getJavaAccessor(); ByteBuffer bb = getBuffer().getJavaAccessor(); int w = Math.min(src.getSize().getWidth() - x, getSize().getWidth() - tgX); int h = Math.min(src.getSize().getHeight() - y, getSize().getHeight() - tgY); int stepSrc = src.getStep(); int stepTrg = getStep(); int pos = srcb.position(); for (int j = 0; j < h; ++j) { int ptrsrc = (j + y) * stepSrc + x * nc; if (processFromPosition) { srcb.limit(pos + ptrsrc + w * nc); srcb.position(pos + ptrsrc); } else { srcb.limit(ptrsrc + w * nc); srcb.position(ptrsrc); } bb.position((j + tgY) * stepTrg + tgX * nc); bb.put(srcb); } srcb.position(0); srcb.limit(srcb.capacity()); bb.position(0); } /** * Set pixel color in rgba encoding * @param i x index of the image pixel * @param j y index of the image pixel * @param rgba color in rgba integer (8 bit each alpha is on LSB) */ public void setPixel(int i, int j, int rgba) { int nc=getnChannels(); int pos=j*step+i*nc; int r=(rgba>>24)&0xFF; int g=(rgba>>16)&0xFF; int b=(rgba>>8)&0xFF; int a=rgba&0xFF; switch (componentOrder) { case BGR: nbuffer.put(pos , (byte)b); nbuffer.put(pos+1, (byte)g); nbuffer.put(pos+2, (byte)r); break; case BGRA: nbuffer.put(pos , (byte)b); nbuffer.put(pos+1, (byte)g); nbuffer.put(pos+2, (byte)r); nbuffer.put(pos+3, (byte)a); break; case RGB: nbuffer.put(pos , (byte)r); nbuffer.put(pos+1, (byte)g); nbuffer.put(pos+2, (byte)b); break; case RGBA: nbuffer.put(pos , (byte)r); nbuffer.put(pos+1,(byte)g); nbuffer.put(pos+2, (byte)b); nbuffer.put(pos+3, (byte)a); break; case MONO: nbuffer.put(pos, (byte)((b+g+r)/3)); break; default: throw new RuntimeException("Unknown component order: "+componentOrder); } } /** * Get pixel color in RGBA encoding. * @param i * @param j * @return */ private int getPixel(int i, int j) { int nc=getnChannels(); int pos=j*step+i*nc; int b; int g; int r; int a; switch (componentOrder) { case BGR: b=nbuffer.get(pos); g=nbuffer.get(pos+1); r=nbuffer.get(pos+2); a=255; break; case BGRA: b=nbuffer.get(pos); g=nbuffer.get(pos+1); r=nbuffer.get(pos+2); a=nbuffer.get(pos+3); break; case RGB: r=nbuffer.get(pos); g=nbuffer.get(pos+1); b=nbuffer.get(pos+2); a=255; break; case RGBA: r=nbuffer.get(pos); g=nbuffer.get(pos+1); b=nbuffer.get(pos+2); a=nbuffer.get(pos+3); break; case ARGB: b=nbuffer.get(pos); g=nbuffer.get(pos+1); r=nbuffer.get(pos+2); a=nbuffer.get(pos+3); break; case MONO: g = nbuffer.get(pos); r = g; b = g; a=255; break; default: throw new RuntimeException("Unknown component order: "+componentOrder); } switch (alphaStorageFormat) { case normal: //nothing to do break; case premultiplied: { float f; if (a == 0) { f = 0; } else { a = a & 0xFF; f = 255f / a; r = clampMul(f, r); g = clampMul(f, g); b = clampMul(f, b); } break; } default: //nothing to do break; } return ((r<<24)&0xFF000000)+((g<<16)&0x00FF0000)+((b<<8)&0x0000FF00)+(a&0xFF); } private static final int clampMul(float f, int r) { float ret=f*(0xFF&r); if (ret > 255) { ret = 255; } if (ret < 0) { ret = 0; } return (int)ret; } /** * Get the number of channels of the image format. * @return */ public int getnChannels() { return nChannels; } /** * Get the storage alignment of image data. * Data of all lines are aligned to addresses with this alignment. * Some image manipulation libraries require that lines of data is aligned in memory. * @return 1, 2 and 4 are common values */ public int getAlignment() { return alignment; } /** * Get the length of a stored row in bytes. * @return width*bytesperpixel+alignmentIfRequired */ public int getStep() { return step; } /** * The size of memory buffer area holding the image. * It is: step*height * (step is nChannel*width+alignmentPadding * where aligmentPadding depends on alignment and width values. * See implementation of getStep()) * @return */ public int getBufferSize() { return step*size.getHeight(); } /** * Create a copy of this image that is: * * allocated using the given allocator * * aligned to be compatible with openCV * @param allocator used to allocate imagebuffer memory * @return */ public NativeImage createCopy(INativeMemoryAllocator allocator) { NativeImage ret=create(getSize(), getComponentOrder(), compatibleAlignment, allocator); ret.copyFromSource(this, 0, 0); return ret; } @Override protected void singleDispose() { if(buffer!=null) { buffer.decrementReferenceCounter(); buffer=null; } nbuffer=null; } /** * Get the alpha storage format of the image. See {@link ENativeImageAlphaStorageFormat} * @return */ public ENativeImageAlphaStorageFormat getAlphaStorageFormat() { return alphaStorageFormat; } public void setAlphaStorageFormat( ENativeImageAlphaStorageFormat alphaStorageFormat) { this.alphaStorageFormat = alphaStorageFormat; } /** * Set the alpha value of all pixels to this value. * @param b */ public void clearAlpha(byte b) { int channel=componentOrder.getAlphaChannel(); if(channel>=0) { int height=size.getHeight(); for(int y=0;y<height;++y) { for(int x=0;x<width;++x) { setChannel(x, y, channel, b); } } } } /** * Flip the image data in the y coordinate. */ public void flipY() { int height=size.getHeight(); int n=height/2; for(int y=0;y<n;++y) { for(int x=0;x<width;++x) { int y2=height-y-1; int rgba=getPixel(x, y); int rgba2=getPixel(x, y2); setPixel(x, y, rgba2); setPixel(x, y2, rgba); } } } /** * Lazy init and return the transparent or opaque mask of the image. * This method finds transparency only in 4 byte image formats. In other cases the returned value will be 0. * In case of non alpha channel formats the returned value will be {@link opaqueBit} * The first time when this test is executed it will run slow because it reads the whole image data. * @return transparency and opacity mask see opaqueBit and transparentBit constants. */ public int getTransparentOrOpaqueMask() { if (this.transparentOrOpaqueMask == -1) { final int alphaChannelIdx = getComponentOrder().getAlphaChannel(); if(alphaChannelIdx!=-1) { if(getComponentOrder().getNCHannels()==4 && getAlignment()<=4) { int oMask=0xff<<(3-alphaChannelIdx)*8; ByteBuffer bb=getBuffer().getJavaAccessor(); int c=bb.capacity()/4; bb.clear(); boolean t=true; boolean o=true; for(int i=0;i<c;++i) { int v=bb.getInt(); t&=v==0; o&=((v&oMask)==oMask); } bb.clear(); transparentOrOpaqueMask = (t?transparentBit:0)+(o?opaqueBit:0); }else { transparentOrOpaqueMask=0; } } else { transparentOrOpaqueMask = opaqueBit; } } return transparentOrOpaqueMask; } /** * Returns the color of specified pixel. * * @param x X coordinate of pixel * @param y Y coordinate of pixel * @return The pixel color as a {@link RGBAColor} * * @since 3.0 */ public RGBAColor getRGBA(int x, int y){ int pixel = getPixel(x, y); return new RGBAColor( (pixel >> 24) & 0xFF, (pixel >> 16) & 0xFF, (pixel >> 8) & 0xFF, pixel & 0xFF ); } /** * This method is only to be used by UtilNativeImageIo class! * @param transparentOrOpaqueMask */ public void setTransparentOrOpaqueMask(int transparentOrOpaqueMask) { this.transparentOrOpaqueMask=transparentOrOpaqueMask; } /** * Set the given pixel to the given color. * @param x * @param y * @param c * * @since 5.0 */ public void setPixel(int x, int y, RGBAColor c) { setPixel(x, y, c.r<<24|c.g<<16|c.b<<8|c.a); } }
package loci.formats.in; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Hashtable; import java.util.Vector; import loci.common.DataTools; import loci.common.DateTools; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.common.Region; import loci.common.services.DependencyException; import loci.common.services.ServiceFactory; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.ImageTools; import loci.formats.MetadataTools; import loci.formats.meta.MetadataStore; import loci.formats.services.MDBService; import loci.formats.tiff.IFD; import loci.formats.tiff.IFDList; import loci.formats.tiff.PhotoInterp; import loci.formats.tiff.TiffCompression; import loci.formats.tiff.TiffConstants; import loci.formats.tiff.TiffParser; import ome.xml.model.primitives.Color; import ome.xml.model.primitives.NonNegativeInteger; import ome.xml.model.primitives.PositiveFloat; import ome.xml.model.primitives.PositiveInteger; import ome.xml.model.primitives.Timestamp; public class ZeissLSMReader extends FormatReader { // -- Constants -- public static final String[] MDB_SUFFIX = {"mdb"}; /** Tag identifying a Zeiss LSM file. */ private static final int ZEISS_ID = 34412; /** Data types. */ private static final int TYPE_SUBBLOCK = 0; private static final int TYPE_ASCII = 2; private static final int TYPE_LONG = 4; private static final int TYPE_RATIONAL = 5; private static final int TYPE_DATE = 6; private static final int TYPE_BOOLEAN = 7; /** Subblock types. */ private static final int SUBBLOCK_RECORDING = 0x10000000; private static final int SUBBLOCK_LASER = 0x50000000; private static final int SUBBLOCK_TRACK = 0x40000000; private static final int SUBBLOCK_DETECTION_CHANNEL = 0x70000000; private static final int SUBBLOCK_ILLUMINATION_CHANNEL = 0x90000000; private static final int SUBBLOCK_BEAM_SPLITTER = 0xb0000000; private static final int SUBBLOCK_DATA_CHANNEL = 0xd0000000; private static final int SUBBLOCK_TIMER = 0x12000000; private static final int SUBBLOCK_MARKER = 0x14000000; private static final int SUBBLOCK_END = (int) 0xffffffff; /** Data types. */ private static final int RECORDING_NAME = 0x10000001; private static final int RECORDING_DESCRIPTION = 0x10000002; private static final int RECORDING_OBJECTIVE = 0x10000004; private static final int RECORDING_ZOOM = 0x10000016; private static final int RECORDING_SAMPLE_0TIME = 0x10000036; private static final int RECORDING_CAMERA_BINNING = 0x10000052; private static final int TRACK_ACQUIRE = 0x40000006; private static final int TRACK_TIME_BETWEEN_STACKS = 0x4000000b; private static final int LASER_NAME = 0x50000001; private static final int LASER_ACQUIRE = 0x50000002; private static final int LASER_POWER = 0x50000003; private static final int CHANNEL_DETECTOR_GAIN = 0x70000003; private static final int CHANNEL_PINHOLE_DIAMETER = 0x70000009; private static final int CHANNEL_AMPLIFIER_GAIN = 0x70000005; private static final int CHANNEL_FILTER_SET = 0x7000000f; private static final int CHANNEL_FILTER = 0x70000010; private static final int CHANNEL_ACQUIRE = 0x7000000b; private static final int CHANNEL_NAME = 0x70000014; private static final int ILLUM_CHANNEL_NAME = 0x90000001; private static final int ILLUM_CHANNEL_ATTENUATION = 0x90000002; private static final int ILLUM_CHANNEL_WAVELENGTH = 0x90000003; private static final int ILLUM_CHANNEL_ACQUIRE = 0x90000004; private static final int START_TIME = 0x10000036; private static final int DATA_CHANNEL_NAME = 0xd0000001; private static final int DATA_CHANNEL_ACQUIRE = 0xd0000017; private static final int BEAM_SPLITTER_FILTER = 0xb0000002; private static final int BEAM_SPLITTER_FILTER_SET = 0xb0000003; /** Drawing element types. */ private static final int TEXT = 13; private static final int LINE = 14; private static final int SCALE_BAR = 15; private static final int OPEN_ARROW = 16; private static final int CLOSED_ARROW = 17; private static final int RECTANGLE = 18; private static final int ELLIPSE = 19; private static final int CLOSED_POLYLINE = 20; private static final int OPEN_POLYLINE = 21; private static final int CLOSED_BEZIER = 22; private static final int OPEN_BEZIER = 23; private static final int CIRCLE = 24; private static final int PALETTE = 25; private static final int POLYLINE_ARROW = 26; private static final int BEZIER_WITH_ARROW = 27; private static final int ANGLE = 28; private static final int CIRCLE_3POINT = 29; // -- Static fields -- private static final Hashtable<Integer, String> METADATA_KEYS = createKeys(); // -- Fields -- private double pixelSizeX, pixelSizeY, pixelSizeZ; private byte[][][] lut = null; private Vector<Double> timestamps; private int validChannels; private String[] lsmFilenames; private Vector<IFDList> ifdsList; private TiffParser tiffParser; private int nextLaser = 0, nextDetector = 0; private int nextFilter = 0, nextDichroicChannel = 0, nextDichroic = 0; private int nextDataChannel = 0, nextIllumChannel = 0, nextDetectChannel = 0; private boolean splitPlanes = false; private double zoom; private Vector<String> imageNames; private String binning; private Vector<Double> xCoordinates, yCoordinates, zCoordinates; private int dimensionM, dimensionP; private Hashtable<String, Integer> seriesCounts; private String userName; private double originX, originY, originZ; private int totalROIs = 0; private int prevPlane = -1; private int prevChannel = 0; private byte[] prevBuf = null; private Region prevRegion = null; private Hashtable<Integer, String> acquiredDate = new Hashtable<Integer, String>(); // -- Constructor -- /** Constructs a new Zeiss LSM reader. */ public ZeissLSMReader() { super("Zeiss Laser-Scanning Microscopy", new String[] {"lsm", "mdb"}); domains = new String[] {FormatTools.LM_DOMAIN}; hasCompanionFiles = true; datasetDescription = "One or more .lsm files; if multiple .lsm files " + "are present, an .mdb file should also be present"; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#getOptimalTileWidth() */ public int getOptimalWidth() { FormatTools.assertId(currentId, true, 1); try { return (int) ifdsList.get(getSeries()).get(0).getTileWidth(); } catch (FormatException e) { LOGGER.debug("Could not retrieve tile width", e); } return super.getOptimalTileWidth(); } /* @see loci.formats.IFormatReader#getOptimalTileHeight() */ public int getOptimalTileHeight() { FormatTools.assertId(currentId, true, 1); try { return (int) ifdsList.get(getSeries()).get(0).getTileLength(); } catch (FormatException e) { LOGGER.debug("Could not retrieve tile height", e); } return super.getOptimalTileHeight(); } /* @see loci.formats.IFormatReader#isSingleFile(String) */ public boolean isSingleFile(String id) throws FormatException, IOException { if (checkSuffix(id, MDB_SUFFIX)) return false; return isGroupFiles() ? getMDBFile(id) != null : true; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { pixelSizeX = pixelSizeY = pixelSizeZ = 0; lut = null; timestamps = null; validChannels = 0; lsmFilenames = null; ifdsList = null; tiffParser = null; nextLaser = nextDetector = 0; nextFilter = nextDichroicChannel = nextDichroic = 0; nextDataChannel = nextIllumChannel = nextDetectChannel = 0; splitPlanes = false; zoom = 0; imageNames = null; binning = null; totalROIs = 0; prevPlane = -1; prevChannel = 0; prevBuf = null; prevRegion = null; xCoordinates = null; yCoordinates = null; zCoordinates = null; dimensionM = 0; dimensionP = 0; seriesCounts = null; originX = originY = originZ = 0d; userName = null; acquiredDate.clear(); } } /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { final int blockLen = 4; if (!FormatTools.validStream(stream, blockLen, false)) return false; TiffParser parser = new TiffParser(stream); return parser.isValidHeader() || stream.readShort() == 0x5374; } /* @see loci.formats.IFormatReader#fileGroupOption(String) */ public int fileGroupOption(String id) throws FormatException, IOException { return checkSuffix(id, MDB_SUFFIX) ? FormatTools.MUST_GROUP : FormatTools.CAN_GROUP; } /* @see loci.formats.IFormatReader#getSeriesUsedFiles(boolean) */ public String[] getSeriesUsedFiles(boolean noPixels) { FormatTools.assertId(currentId, true, 1); if (noPixels) { if (checkSuffix(currentId, MDB_SUFFIX)) return new String[] {currentId}; return null; } if (lsmFilenames == null) return new String[] {currentId}; if (lsmFilenames.length == 1 && currentId.equals(lsmFilenames[0])) { return lsmFilenames; } return new String[] {currentId, getLSMFileFromSeries(getSeries())}; } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); if (lut == null || lut[getSeries()] == null || getPixelType() != FormatTools.UINT8) { return null; } byte[][] b = new byte[3][]; b[0] = lut[getSeries()][prevChannel * 3]; b[1] = lut[getSeries()][prevChannel * 3 + 1]; b[2] = lut[getSeries()][prevChannel * 3 + 2]; return b; } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); if (lut == null || lut[getSeries()] == null || getPixelType() != FormatTools.UINT16 || validChannels == 0) { return null; } short[][] s = new short[3][65536]; for (int i=2; i>=3-validChannels; i for (int j=0; j<s[i].length; j++) { s[i][j] = (short) j; } } return s; } /* @see loci.formats.IFormatReader#setSeries(int) */ public void setSeries(int series) { if (series != getSeries()) { prevBuf = null; } super.setSeries(series); } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); if (getSeriesCount() > 1) { in.close(); in = new RandomAccessInputStream(getLSMFileFromSeries(getSeries())); in.order(!isLittleEndian()); tiffParser = new TiffParser(in); } IFDList ifds = ifdsList.get(getSeries()); if (splitPlanes && getSizeC() > 1 && ifds.size() == getSizeZ() * getSizeT()) { int bpp = FormatTools.getBytesPerPixel(getPixelType()); int plane = no / getSizeC(); int c = no % getSizeC(); Region region = new Region(x, y, w, h); if (prevPlane != plane || prevBuf == null || prevBuf.length < w * h * bpp * getSizeC() || !region.equals(prevRegion)) { prevBuf = new byte[w * h * bpp * getSizeC()]; tiffParser.getSamples(ifds.get(plane), prevBuf, x, y, w, h); prevPlane = plane; prevRegion = region; } ImageTools.splitChannels( prevBuf, buf, c, getSizeC(), bpp, false, false, w * h * bpp); prevChannel = c; } else { tiffParser.getSamples(ifds.get(no), buf, x, y, w, h); prevChannel = getZCTCoords(no)[1]; } if (getSeriesCount() > 1) in.close(); return buf; } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); if (checkSuffix(id, MDB_SUFFIX)) { lsmFilenames = parseMDB(id); } else lsmFilenames = new String[] {id}; if (lsmFilenames == null || lsmFilenames.length == 0) { throw new FormatException("LSM files were not found."); } timestamps = new Vector<Double>(); imageNames = new Vector<String>(); xCoordinates = new Vector<Double>(); yCoordinates = new Vector<Double>(); zCoordinates = new Vector<Double>(); seriesCounts = new Hashtable<String, Integer>(); int seriesCount = 0; Vector<String> validFiles = new Vector<String>(); for (String filename : lsmFilenames) { try { int extraSeries = getExtraSeries(filename); seriesCounts.put(filename, extraSeries); seriesCount += extraSeries; validFiles.add(filename); } catch (IOException e) { LOGGER.debug("Failed to parse " + filename, e); } } lsmFilenames = validFiles.toArray(new String[validFiles.size()]); core = new CoreMetadata[seriesCount]; ifdsList = new Vector<IFDList>(); ifdsList.setSize(core.length); int realSeries = 0; for (int i=0; i<lsmFilenames.length; i++) { RandomAccessInputStream stream = new RandomAccessInputStream(lsmFilenames[i]); int count = seriesCounts.get(lsmFilenames[i]); TiffParser tp = new TiffParser(stream); Boolean littleEndian = tp.checkHeader(); long[] ifdOffsets = tp.getIFDOffsets(); int ifdsPerSeries = (ifdOffsets.length / 2) / count; int offset = 0; Object zeissTag = null; for (int s=0; s<count; s++, realSeries++) { core[realSeries] = new CoreMetadata(); core[realSeries].littleEndian = littleEndian; IFDList ifds = new IFDList(); while (ifds.size() < ifdsPerSeries) { tp.setDoCaching(offset == 0); IFD ifd = tp.getIFD(ifdOffsets[offset]); if (offset == 0) zeissTag = ifd.get(ZEISS_ID); if (offset > 0 && ifds.size() == 0) { ifd.putIFDValue(ZEISS_ID, zeissTag); } ifds.add(ifd); if (zeissTag != null) offset += 2; else offset++; } for (IFD ifd : ifds) { tp.fillInIFD(ifd); } ifdsList.set(realSeries, ifds); } stream.close(); } MetadataStore store = makeFilterMetadata(); lut = new byte[ifdsList.size()][][]; long[] previousStripOffsets = null; for (int series=0; series<ifdsList.size(); series++) { if (series > 0 && lsmFilenames.length > 1) { previousStripOffsets = null; } IFDList ifds = ifdsList.get(series); for (IFD ifd : ifds) { // check that predictor is set to 1 if anything other // than LZW compression is used if (ifd.getCompression() != TiffCompression.LZW) { ifd.putIFDValue(IFD.PREDICTOR, 1); } } // fix the offsets for > 4 GB files RandomAccessInputStream s = new RandomAccessInputStream(getLSMFileFromSeries(series)); for (int i=0; i<ifds.size(); i++) { long[] stripOffsets = ifds.get(i).getStripOffsets(); if (stripOffsets == null || (i != 0 && previousStripOffsets == null)) { throw new FormatException( "Strip offsets are missing; this is an invalid file."); } else if (i == 0 && previousStripOffsets == null) { previousStripOffsets = stripOffsets; continue; } boolean neededAdjustment = false; for (int j=0; j<stripOffsets.length; j++) { if (j >= previousStripOffsets.length) break; if (stripOffsets[j] < previousStripOffsets[j]) { stripOffsets[j] = (previousStripOffsets[j] & ~0xffffffffL) | (stripOffsets[j] & 0xffffffffL); if (stripOffsets[j] < previousStripOffsets[j]) { long newOffset = stripOffsets[j] + 0x100000000L; if (newOffset < s.length()) { stripOffsets[j] = newOffset; } } neededAdjustment = true; } if (neededAdjustment) { ifds.get(i).putIFDValue(IFD.STRIP_OFFSETS, stripOffsets); } } previousStripOffsets = stripOffsets; } s.close(); initMetadata(series); } for (int i=0; i<getSeriesCount(); i++) { core[i].imageCount = core[i].sizeZ * core[i].sizeC * core[i].sizeT; } MetadataTools.populatePixels(store, this, true); for (int series=0; series<ifdsList.size(); series++) { setSeries(series); if (series < imageNames.size()) { store.setImageName(imageNames.get(series), series); } if (acquiredDate.containsKey(series)) { store.setImageAcquisitionDate(new Timestamp( acquiredDate.get(series)), series); } store.setPixelsBinDataBigEndian(!isLittleEndian(), series, 0); } setSeries(0); } // -- Helper methods -- private String getMDBFile(String id) throws FormatException, IOException { Location parentFile = new Location(id).getAbsoluteFile().getParentFile(); String[] fileList = parentFile.list(); for (int i=0; i<fileList.length; i++) { if (fileList[i].startsWith(".")) continue; if (checkSuffix(fileList[i], MDB_SUFFIX)) { Location file = new Location(parentFile, fileList[i]).getAbsoluteFile(); if (file.isDirectory()) continue; // make sure that the .mdb references this .lsm String[] lsms = parseMDB(file.getAbsolutePath()); if (lsms == null) return null; for (String lsm : lsms) { if (id.endsWith(lsm) || lsm.endsWith(id)) { return file.getAbsolutePath(); } } } } return null; } private int getEffectiveSeries(int currentSeries) { int seriesCount = 0; for (int i=0; i<lsmFilenames.length; i++) { Integer count = seriesCounts.get(lsmFilenames[i]); if (count == null) count = 1; seriesCount += count; if (seriesCount > currentSeries) return i; } return -1; } private String getLSMFileFromSeries(int currentSeries) { int effectiveSeries = getEffectiveSeries(currentSeries); return effectiveSeries < 0 ? null : lsmFilenames[effectiveSeries]; } private int getExtraSeries(String file) throws FormatException, IOException { if (in != null) in.close(); in = new RandomAccessInputStream(file); boolean littleEndian = in.read() == TiffConstants.LITTLE; in.order(littleEndian); tiffParser = new TiffParser(in); IFD ifd = tiffParser.getFirstIFD(); RandomAccessInputStream ras = getCZTag(ifd); if (ras == null) return 1; ras.order(littleEndian); ras.seek(264); dimensionP = ras.readInt(); dimensionM = ras.readInt(); ras.close(); int nSeries = dimensionM * dimensionP; return nSeries <= 0 ? 1 : nSeries; } private int getPosition(int currentSeries) { int effectiveSeries = getEffectiveSeries(currentSeries); int firstPosition = 0; for (int i=0; i<effectiveSeries; i++) { firstPosition += seriesCounts.get(lsmFilenames[i]); } return currentSeries - firstPosition; } private RandomAccessInputStream getCZTag(IFD ifd) throws FormatException, IOException { // get TIF_CZ_LSMINFO structure short[] s = ifd.getIFDShortArray(ZEISS_ID); if (s == null) { LOGGER.warn("Invalid Zeiss LSM file. Tag {} not found.", ZEISS_ID); TiffReader reader = new TiffReader(); reader.setId(getLSMFileFromSeries(series)); core[getSeries()] = reader.getCoreMetadata()[0]; reader.close(); return null; } byte[] cz = new byte[s.length]; for (int i=0; i<s.length; i++) { cz[i] = (byte) s[i]; } RandomAccessInputStream ras = new RandomAccessInputStream(cz); ras.order(isLittleEndian()); return ras; } protected void initMetadata(int series) throws FormatException, IOException { setSeries(series); IFDList ifds = ifdsList.get(series); IFD ifd = ifds.get(0); in.close(); in = new RandomAccessInputStream(getLSMFileFromSeries(series)); in.order(isLittleEndian()); tiffParser = new TiffParser(in); PhotoInterp photo = ifd.getPhotometricInterpretation(); int samples = ifd.getSamplesPerPixel(); core[series].sizeX = (int) ifd.getImageWidth(); core[series].sizeY = (int) ifd.getImageLength(); core[series].rgb = samples > 1 || photo == PhotoInterp.RGB; core[series].interleaved = false; core[series].sizeC = isRGB() ? samples : 1; core[series].pixelType = ifd.getPixelType(); core[series].imageCount = ifds.size(); core[series].sizeZ = getImageCount(); core[series].sizeT = 1; LOGGER.info("Reading LSM metadata for series #{}", series); MetadataStore store = makeFilterMetadata(); int instrument = getEffectiveSeries(series); String imageName = getLSMFileFromSeries(series); if (imageName.indexOf(".") != -1) { imageName = imageName.substring(0, imageName.lastIndexOf(".")); } if (imageName.indexOf(File.separator) != -1) { imageName = imageName.substring(imageName.lastIndexOf(File.separator) + 1); } if (lsmFilenames.length != getSeriesCount()) { imageName += " #" + (getPosition(series) + 1); } // link Instrument and Image store.setImageID(MetadataTools.createLSID("Image", series), series); String instrumentID = MetadataTools.createLSID("Instrument", instrument); store.setInstrumentID(instrumentID, instrument); store.setImageInstrumentRef(instrumentID, series); RandomAccessInputStream ras = getCZTag(ifd); if (ras == null) { imageNames.add(imageName); return; } ras.seek(16); core[series].sizeZ = ras.readInt(); ras.skipBytes(4); core[series].sizeT = ras.readInt(); int dataType = ras.readInt(); switch (dataType) { case 2: addSeriesMeta("DataType", "12 bit unsigned integer"); break; case 5: addSeriesMeta("DataType", "32 bit float"); break; case 0: addSeriesMeta("DataType", "varying data types"); break; default: addSeriesMeta("DataType", "8 bit unsigned integer"); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { ras.seek(0); addSeriesMeta("MagicNumber ", ras.readInt()); addSeriesMeta("StructureSize", ras.readInt()); addSeriesMeta("DimensionX", ras.readInt()); addSeriesMeta("DimensionY", ras.readInt()); ras.seek(32); addSeriesMeta("ThumbnailX", ras.readInt()); addSeriesMeta("ThumbnailY", ras.readInt()); // pixel sizes are stored in meters, we need them in microns pixelSizeX = ras.readDouble() * 1000000; pixelSizeY = ras.readDouble() * 1000000; pixelSizeZ = ras.readDouble() * 1000000; addSeriesMeta("VoxelSizeX", new Double(pixelSizeX)); addSeriesMeta("VoxelSizeY", new Double(pixelSizeY)); addSeriesMeta("VoxelSizeZ", new Double(pixelSizeZ)); originX = ras.readDouble() * 1000000; originY = ras.readDouble() * 1000000; originZ = ras.readDouble() * 1000000; addSeriesMeta("OriginX", originX); addSeriesMeta("OriginY", originY); addSeriesMeta("OriginZ", originZ); } else ras.seek(88); int scanType = ras.readShort(); switch (scanType) { case 0: addSeriesMeta("ScanType", "x-y-z scan"); core[series].dimensionOrder = "XYZCT"; break; case 1: addSeriesMeta("ScanType", "z scan (x-z plane)"); core[series].dimensionOrder = "XYZCT"; break; case 2: addSeriesMeta("ScanType", "line scan"); core[series].dimensionOrder = "XYZCT"; break; case 3: addSeriesMeta("ScanType", "time series x-y"); core[series].dimensionOrder = "XYTCZ"; break; case 4: addSeriesMeta("ScanType", "time series x-z"); core[series].dimensionOrder = "XYZTC"; break; case 5: addSeriesMeta("ScanType", "time series 'Mean of ROIs'"); core[series].dimensionOrder = "XYTCZ"; break; case 6: addSeriesMeta("ScanType", "time series x-y-z"); core[series].dimensionOrder = "XYZTC"; break; case 7: addSeriesMeta("ScanType", "spline scan"); core[series].dimensionOrder = "XYCTZ"; break; case 8: addSeriesMeta("ScanType", "spline scan x-z"); core[series].dimensionOrder = "XYCZT"; break; case 9: addSeriesMeta("ScanType", "time series spline plane x-z"); core[series].dimensionOrder = "XYTCZ"; break; case 10: addSeriesMeta("ScanType", "point mode"); core[series].dimensionOrder = "XYZCT"; break; default: addSeriesMeta("ScanType", "x-y-z scan"); core[series].dimensionOrder = "XYZCT"; } core[series].indexed = lut != null && lut[series] != null; if (isIndexed()) { core[series].rgb = false; } if (getSizeC() == 0) core[series].sizeC = 1; if (isRGB()) { // shuffle C to front of order string core[series].dimensionOrder = getDimensionOrder().replaceAll("C", ""); core[series].dimensionOrder = getDimensionOrder().replaceAll("XY", "XYC"); } if (getEffectiveSizeC() == 0) { core[series].imageCount = getSizeZ() * getSizeT(); } else { core[series].imageCount = getSizeZ() * getSizeT() * getEffectiveSizeC(); } if (getImageCount() != ifds.size()) { int diff = getImageCount() - ifds.size(); core[series].imageCount = ifds.size(); if (diff % getSizeZ() == 0) { core[series].sizeT -= (diff / getSizeZ()); } else if (diff % getSizeT() == 0) { core[series].sizeZ -= (diff / getSizeT()); } else if (getSizeZ() > 1) { core[series].sizeZ = ifds.size(); core[series].sizeT = 1; } else if (getSizeT() > 1) { core[series].sizeT = ifds.size(); core[series].sizeZ = 1; } } if (getSizeZ() == 0) core[series].sizeZ = getImageCount(); if (getSizeT() == 0) core[series].sizeT = getImageCount() / getSizeZ(); long channelColorsOffset = 0; long timeStampOffset = 0; long eventListOffset = 0; long scanInformationOffset = 0; long channelWavelengthOffset = 0; long applicationTagOffset = 0; Color[] channelColor = new Color[getSizeC()]; if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { int spectralScan = ras.readShort(); if (spectralScan != 1) { addSeriesMeta("SpectralScan", "no spectral scan"); } else addSeriesMeta("SpectralScan", "acquired with spectral scan"); int type = ras.readInt(); switch (type) { case 1: addSeriesMeta("DataType2", "calculated data"); break; case 2: addSeriesMeta("DataType2", "animation"); break; default: addSeriesMeta("DataType2", "original scan data"); } long[] overlayOffsets = new long[9]; String[] overlayKeys = new String[] {"VectorOverlay", "InputLut", "OutputLut", "ROI", "BleachROI", "MeanOfRoisOverlay", "TopoIsolineOverlay", "TopoProfileOverlay", "LinescanOverlay"}; overlayOffsets[0] = ras.readInt(); overlayOffsets[1] = ras.readInt(); overlayOffsets[2] = ras.readInt(); channelColorsOffset = ras.readInt(); addSeriesMeta("TimeInterval", ras.readDouble()); ras.skipBytes(4); scanInformationOffset = ras.readInt(); applicationTagOffset = ras.readInt(); timeStampOffset = ras.readInt(); eventListOffset = ras.readInt(); overlayOffsets[3] = ras.readInt(); overlayOffsets[4] = ras.readInt(); ras.skipBytes(4); addSeriesMeta("DisplayAspectX", ras.readDouble()); addSeriesMeta("DisplayAspectY", ras.readDouble()); addSeriesMeta("DisplayAspectZ", ras.readDouble()); addSeriesMeta("DisplayAspectTime", ras.readDouble()); overlayOffsets[5] = ras.readInt(); overlayOffsets[6] = ras.readInt(); overlayOffsets[7] = ras.readInt(); overlayOffsets[8] = ras.readInt(); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.NO_OVERLAYS) { for (int i=0; i<overlayOffsets.length; i++) { parseOverlays(series, overlayOffsets[i], overlayKeys[i], store); } } totalROIs = 0; addSeriesMeta("ToolbarFlags", ras.readInt()); channelWavelengthOffset = ras.readInt(); ras.skipBytes(64); } else ras.skipBytes(182); if (getSizeC() > 1) { if (!splitPlanes) splitPlanes = isRGB(); core[series].rgb = false; if (splitPlanes) core[series].imageCount *= getSizeC(); } for (int c=0; c<getEffectiveSizeC(); c++) { String lsid = MetadataTools.createLSID("Channel", series, c); store.setChannelID(lsid, series, c); } if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { // NB: the Zeiss LSM 5.5 specification indicates that there should be // 15 32-bit integers here; however, there are actually 16 32-bit // integers before the tile position offset. // We have confirmed with Zeiss that this is correct, and the 6.0 // specification was updated to contain the correct information. ras.skipBytes(64); int tilePositionOffset = ras.readInt(); ras.skipBytes(36); int positionOffset = ras.readInt(); // read referenced structures addSeriesMeta("DimensionZ", getSizeZ()); addSeriesMeta("DimensionChannels", getSizeC()); addSeriesMeta("DimensionM", dimensionM); addSeriesMeta("DimensionP", dimensionP); if (lsmFilenames.length == 1) { xCoordinates.clear(); yCoordinates.clear(); zCoordinates.clear(); } if (positionOffset != 0) { in.seek(positionOffset); int nPositions = in.readInt(); for (int i=0; i<nPositions; i++) { double xPos = originX + in.readDouble() * 1000000; double yPos = originY + in.readDouble() * 1000000; double zPos = originZ + in.readDouble() * 1000000; xCoordinates.add(xPos); yCoordinates.add(yPos); zCoordinates.add(zPos); addGlobalMeta("X position for position #" + (i + 1), xPos); addGlobalMeta("Y position for position #" + (i + 1), yPos); addGlobalMeta("Z position for position #" + (i + 1), zPos); } } if (tilePositionOffset != 0) { in.seek(tilePositionOffset); int nTiles = in.readInt(); for (int i=0; i<nTiles; i++) { double xPos = originX + in.readDouble() * 1000000; double yPos = originY + in.readDouble() * 1000000; double zPos = originZ + in.readDouble() * 1000000; if (xCoordinates.size() > i) { xPos += xCoordinates.get(i); xCoordinates.setElementAt(xPos, i); } else if (xCoordinates.size() == i) { xCoordinates.add(xPos); } if (yCoordinates.size() > i) { yPos += yCoordinates.get(i); yCoordinates.setElementAt(yPos, i); } else if (yCoordinates.size() == i) { yCoordinates.add(yPos); } if (zCoordinates.size() > i) { zPos += zCoordinates.get(i); zCoordinates.setElementAt(zPos, i); } else if (zCoordinates.size() == i) { zCoordinates.add(zPos); } addGlobalMeta("X position for position #" + (i + 1), xPos); addGlobalMeta("Y position for position #" + (i + 1), yPos); addGlobalMeta("Z position for position #" + (i + 1), zPos); } } if (channelColorsOffset != 0) { in.seek(channelColorsOffset + 12); int colorsOffset = in.readInt(); int namesOffset = in.readInt(); // read the color of each channel if (colorsOffset > 0) { in.seek(channelColorsOffset + colorsOffset); lut[getSeries()] = new byte[getSizeC() * 3][256]; core[getSeries()].indexed = true; for (int i=0; i<getSizeC(); i++) { int color = in.readInt(); int red = color & 0xff; int green = (color & 0xff00) >> 8; int blue = (color & 0xff0000) >> 16; channelColor[i] = new Color(red, green, blue, 255); for (int j=0; j<256; j++) { lut[getSeries()][i * 3][j] = (byte) ((red / 255.0) * j); lut[getSeries()][i * 3 + 1][j] = (byte) ((green / 255.0) * j); lut[getSeries()][i * 3 + 2][j] = (byte) ((blue / 255.0) * j); } } } // read the name of each channel if (namesOffset > 0) { in.seek(channelColorsOffset + namesOffset + 4); for (int i=0; i<getSizeC(); i++) { if (in.getFilePointer() >= in.length() - 1) break; // we want to read until we find a null char String name = in.readCString(); if (name.length() <= 128) { addSeriesMeta("ChannelName" + i, name); } } } } if (timeStampOffset != 0) { in.seek(timeStampOffset + 4); int nStamps = in.readInt(); for (int i=0; i<nStamps; i++) { double stamp = in.readDouble(); addSeriesMeta("TimeStamp" + i, stamp); timestamps.add(new Double(stamp)); } } if (eventListOffset != 0) { in.seek(eventListOffset + 4); int numEvents = in.readInt(); in.seek(in.getFilePointer() - 4); in.order(!in.isLittleEndian()); int tmpEvents = in.readInt(); if (numEvents < 0) numEvents = tmpEvents; else numEvents = (int) Math.min(numEvents, tmpEvents); in.order(!in.isLittleEndian()); if (numEvents > 65535) numEvents = 0; for (int i=0; i<numEvents; i++) { if (in.getFilePointer() + 16 <= in.length()) { int size = in.readInt(); double eventTime = in.readDouble(); int eventType = in.readInt(); addSeriesMeta("Event" + i + " Time", eventTime); addSeriesMeta("Event" + i + " Type", eventType); long fp = in.getFilePointer(); int len = size - 16; if (len > 65536) len = 65536; if (len < 0) len = 0; addSeriesMeta("Event" + i + " Description", in.readString(len)); in.seek(fp + size - 16); if (in.getFilePointer() < 0) break; } } } if (scanInformationOffset != 0) { in.seek(scanInformationOffset); nextLaser = nextDetector = 0; nextFilter = nextDichroicChannel = nextDichroic = 0; nextDataChannel = nextDetectChannel = nextIllumChannel = 0; Vector<SubBlock> blocks = new Vector<SubBlock>(); while (in.getFilePointer() < in.length() - 12) { if (in.getFilePointer() < 0) break; int entry = in.readInt(); int blockType = in.readInt(); int dataSize = in.readInt(); if (blockType == TYPE_SUBBLOCK) { SubBlock block = null; switch (entry) { case SUBBLOCK_RECORDING: block = new Recording(); break; case SUBBLOCK_LASER: block = new Laser(); break; case SUBBLOCK_TRACK: block = new Track(); break; case SUBBLOCK_DETECTION_CHANNEL: block = new DetectionChannel(); break; case SUBBLOCK_ILLUMINATION_CHANNEL: block = new IlluminationChannel(); break; case SUBBLOCK_BEAM_SPLITTER: block = new BeamSplitter(); break; case SUBBLOCK_DATA_CHANNEL: block = new DataChannel(); break; case SUBBLOCK_TIMER: block = new Timer(); break; case SUBBLOCK_MARKER: block = new Marker(); break; } if (block != null) { blocks.add(block); } } else if (dataSize + in.getFilePointer() <= in.length() && dataSize > 0) { in.skipBytes(dataSize); } else break; } Vector<SubBlock> nonAcquiredBlocks = new Vector<SubBlock>(); SubBlock[] metadataBlocks = blocks.toArray(new SubBlock[0]); for (SubBlock block : metadataBlocks) { block.addToHashtable(); if (!block.acquire) { nonAcquiredBlocks.add(block); blocks.remove(block); } } for (int i=0; i<blocks.size(); i++) { SubBlock block = blocks.get(i); // every valid IlluminationChannel must be immediately followed by // a valid DataChannel or IlluminationChannel if ((block instanceof IlluminationChannel) && i < blocks.size() - 1) { SubBlock nextBlock = blocks.get(i + 1); if (!(nextBlock instanceof DataChannel) && !(nextBlock instanceof IlluminationChannel)) { ((IlluminationChannel) block).wavelength = null; } } // every valid DetectionChannel must be immediately preceded by // a valid Track or DetectionChannel else if ((block instanceof DetectionChannel) && i > 0) { SubBlock prevBlock = blocks.get(i - 1); if (!(prevBlock instanceof Track) && !(prevBlock instanceof DetectionChannel)) { block.acquire = false; nonAcquiredBlocks.add(block); } } if (block.acquire) populateMetadataStore(block, store, series); } for (SubBlock block : nonAcquiredBlocks) { populateMetadataStore(block, store, series); } } if (applicationTagOffset != 0) { in.seek(applicationTagOffset); parseApplicationTags(); } } imageNames.add(imageName); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { if (userName != null) { String experimenterID = MetadataTools.createLSID("Experimenter", 0); store.setExperimenterID(experimenterID, 0); store.setExperimenterUserName(userName, 0); } Double pixX = new Double(pixelSizeX); Double pixY = new Double(pixelSizeY); Double pixZ = new Double(pixelSizeZ); if (pixX > 0) { store.setPixelsPhysicalSizeX(new PositiveFloat(pixX), series); } else { LOGGER.warn("Expected positive value for PhysicalSizeX; got {}", pixX); } if (pixY >= 0) { store.setPixelsPhysicalSizeY(new PositiveFloat(pixY), series); } else { LOGGER.warn("Expected positive value for PhysicalSizeY; got {}", pixY); } if (pixZ >= 0) { store.setPixelsPhysicalSizeZ(new PositiveFloat(pixZ), series); } else { LOGGER.warn("Expected positive value for PhysicalSizeZ; got {}", pixZ); } for (int i=0; i<getSizeC(); i++) { store.setChannelColor(channelColor[i], series, i); } int stampIndex = 0; for (int i=0; i<series; i++) { stampIndex += core[i].sizeT; } double firstStamp = 0; if (timestamps.size() > 0 && stampIndex < timestamps.size()) { firstStamp = timestamps.get(stampIndex).doubleValue(); } for (int i=0; i<getImageCount(); i++) { int[] zct = FormatTools.getZCTCoords(this, i); if (getSizeT() > 1 && zct[2] < timestamps.size() - stampIndex) { double thisStamp = timestamps.get(stampIndex + zct[2]).doubleValue(); store.setPlaneDeltaT(thisStamp - firstStamp, series, i); } if (xCoordinates.size() > series) { store.setPlanePositionX(xCoordinates.get(series), series, i); store.setPlanePositionY(yCoordinates.get(series), series, i); store.setPlanePositionZ(zCoordinates.get(series), series, i); } } } ras.close(); } protected void populateMetadataStore(SubBlock block, MetadataStore store, int series) throws FormatException { if (getMetadataOptions().getMetadataLevel() == MetadataLevel.MINIMUM) { return; } int instrument = getEffectiveSeries(series); // NB: block.acquire can be false. If that is the case, Instrument data // is the only thing that should be populated. if (block instanceof Recording) { Recording recording = (Recording) block; String objectiveID = MetadataTools.createLSID("Objective", instrument, 0); if (recording.acquire) { store.setImageDescription(recording.description, series); if (recording.startTime != null) { acquiredDate.put(series, recording.startTime); } store.setObjectiveSettingsID(objectiveID, series); binning = recording.binning; } store.setObjectiveCorrection( getCorrection(recording.correction), instrument, 0); store.setObjectiveImmersion( getImmersion(recording.immersion), instrument, 0); if (recording.magnification != null && recording.magnification > 0) { store.setObjectiveNominalMagnification( new PositiveInteger(recording.magnification), instrument, 0); } else { LOGGER.warn("Expected positive value for NominalMagnification; got {}", recording.magnification); } store.setObjectiveLensNA(recording.lensNA, instrument, 0); store.setObjectiveIris(recording.iris, instrument, 0); store.setObjectiveID(objectiveID, instrument, 0); } else if (block instanceof Laser) { Laser laser = (Laser) block; if (laser.medium != null) { store.setLaserLaserMedium(getLaserMedium(laser.medium), instrument, nextLaser); } if (laser.type != null) { store.setLaserType(getLaserType(laser.type), instrument, nextLaser); } if (laser.model != null) { store.setLaserModel(laser.model, instrument, nextLaser); } String lightSourceID = MetadataTools.createLSID("LightSource", instrument, nextLaser); store.setLaserID(lightSourceID, instrument, nextLaser); nextLaser++; } else if (block instanceof Track) { Track track = (Track) block; if (track.acquire) { store.setPixelsTimeIncrement(track.timeIncrement, series); } } else if (block instanceof DataChannel) { DataChannel channel = (DataChannel) block; if (channel.name != null && nextDataChannel < getSizeC() && channel.acquire) { store.setChannelName(channel.name, series, nextDataChannel++); } } else if (block instanceof DetectionChannel) { DetectionChannel channel = (DetectionChannel) block; if (channel.pinhole != null && channel.pinhole.doubleValue() != 0f && nextDetectChannel < getSizeC() && channel.acquire) { store.setChannelPinholeSize(channel.pinhole, series, nextDetectChannel); } if (channel.filter != null) { String id = MetadataTools.createLSID("Filter", instrument, nextFilter); if (channel.acquire && nextDetectChannel < getSizeC()) { store.setLightPathEmissionFilterRef( id, instrument, nextDetectChannel, 0); } store.setFilterID(id, instrument, nextFilter); store.setFilterModel(channel.filter, instrument, nextFilter); int space = channel.filter.indexOf(" "); if (space != -1) { String type = channel.filter.substring(0, space).trim(); if (type.equals("BP")) type = "BandPass"; else if (type.equals("LP")) type = "LongPass"; store.setFilterType(getFilterType(type), instrument, nextFilter); String transmittance = channel.filter.substring(space + 1).trim(); String[] v = transmittance.split("-"); try { Integer cutIn = new Integer(v[0].trim()); if (cutIn > 0) { store.setTransmittanceRangeCutIn( new PositiveInteger(cutIn), instrument, nextFilter); } else { LOGGER.warn("Expected positive value for CutIn; got {}", cutIn); } } catch (NumberFormatException e) { } if (v.length > 1) { try { Integer cutOut = new Integer(v[1].trim()); if (cutOut > 0) { store.setTransmittanceRangeCutOut( new PositiveInteger(cutOut), instrument, nextFilter); } else { LOGGER.warn("Expected positive value for CutOut; got {}", cutOut); } } catch (NumberFormatException e) { } } } nextFilter++; } if (channel.channelName != null) { String detectorID = MetadataTools.createLSID("Detector", instrument, nextDetector); store.setDetectorID(detectorID, instrument, nextDetector); if (channel.acquire && nextDetector < getSizeC()) { store.setDetectorSettingsID(detectorID, series, nextDetector); //store.setDetectorSettingsBinning( // getBinning(binning), series, nextDetector); } } if (channel.amplificationGain != null) { store.setDetectorAmplificationGain( channel.amplificationGain, instrument, nextDetector); } if (channel.gain != null) { store.setDetectorGain(channel.gain, instrument, nextDetector); } store.setDetectorType(getDetectorType("PMT"), instrument, nextDetector); store.setDetectorZoom(zoom, instrument, nextDetector); nextDetectChannel++; nextDetector++; } else if (block instanceof BeamSplitter) { BeamSplitter beamSplitter = (BeamSplitter) block; if (beamSplitter.filterSet != null) { if (beamSplitter.filter != null) { String id = MetadataTools.createLSID( "Dichroic", instrument, nextDichroic); store.setDichroicID(id, instrument, nextDichroic); store.setDichroicModel(beamSplitter.filter, instrument, nextDichroic); if (nextDichroicChannel < getEffectiveSizeC()) { //store.setLightPathDichroicRef(id, series, nextDichroicChannel); } nextDichroic++; } nextDichroicChannel++; } } else if (block instanceof IlluminationChannel) { IlluminationChannel channel = (IlluminationChannel) block; if (channel.acquire && channel.wavelength != null && channel.wavelength > 0) { store.setLaserWavelength(new PositiveInteger(channel.wavelength), instrument, nextIllumChannel); if (nextIllumChannel >= nextLaser) { String lightSourceID = MetadataTools.createLSID( "LightSource", instrument, nextIllumChannel); store.setLaserID(lightSourceID, instrument, nextIllumChannel); } nextIllumChannel++; } else if (channel.acquire) { LOGGER.warn("Expected positive value for Wavelength; got {}", channel.wavelength); } } } /** Parses overlay-related fields. */ protected void parseOverlays(int series, long data, String suffix, MetadataStore store) throws IOException { if (data == 0) return; String prefix = "Series " + series + " "; in.seek(data); int numberOfShapes = in.readInt(); int size = in.readInt(); if (size <= 194) return; in.skipBytes(20); boolean valid = in.readInt() == 1; in.skipBytes(164); for (int i=totalROIs; i<totalROIs+numberOfShapes; i++) { long offset = in.getFilePointer(); int type = in.readInt(); int blockLength = in.readInt(); double lineWidth = in.readInt(); int measurements = in.readInt(); double textOffsetX = in.readDouble(); double textOffsetY = in.readDouble(); int color = in.readInt(); boolean validShape = in.readInt() != 0; int knotWidth = in.readInt(); int catchArea = in.readInt(); int fontHeight = in.readInt(); int fontWidth = in.readInt(); int fontEscapement = in.readInt(); int fontOrientation = in.readInt(); int fontWeight = in.readInt(); boolean fontItalic = in.readInt() != 0; boolean fontUnderlined = in.readInt() != 0; boolean fontStrikeout = in.readInt() != 0; int fontCharSet = in.readInt(); int fontOutputPrecision = in.readInt(); int fontClipPrecision = in.readInt(); int fontQuality = in.readInt(); int fontPitchAndFamily = in.readInt(); String fontName = DataTools.stripString(in.readString(64)); boolean enabled = in.readShort() == 0; boolean moveable = in.readInt() == 0; in.skipBytes(34); String roiID = MetadataTools.createLSID("ROI", i); String shapeID = MetadataTools.createLSID("Shape", i, 0); switch (type) { case TEXT: double x = in.readDouble(); double y = in.readDouble(); String text = DataTools.stripString(in.readCString()); store.setLabelText(text, i, 0); if (fontHeight >= 0) { store.setLabelFontSize(new NonNegativeInteger(fontHeight), i, 0); } else { LOGGER.warn("Expected non-negative value for FontSize; got {}", fontHeight); } store.setLabelStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setLabelID(shapeID, i, 0); store.setImageROIRef(roiID, series, i); break; case LINE: in.skipBytes(4); double startX = in.readDouble(); double startY = in.readDouble(); double endX = in.readDouble(); double endY = in.readDouble(); store.setLineX1(startX, i, 0); store.setLineY1(startY, i, 0); store.setLineX2(endX, i, 0); store.setLineY2(endY, i, 0); if (fontHeight >= 0) { store.setLineFontSize(new NonNegativeInteger(fontHeight), i, 0); } else { LOGGER.warn("Expected non-negative value for FontSize; got {}", fontHeight); } store.setLineStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setImageROIRef(roiID, series, i); store.setLineID(shapeID, i, 0); break; case SCALE_BAR: case OPEN_ARROW: case CLOSED_ARROW: case PALETTE: in.skipBytes(36); break; case RECTANGLE: in.skipBytes(4); double topX = in.readDouble(); double topY = in.readDouble(); double bottomX = in.readDouble(); double bottomY = in.readDouble(); double width = Math.abs(bottomX - topX); double height = Math.abs(bottomY - topY); topX = Math.min(topX, bottomX); topY = Math.min(topY, bottomY); store.setRectangleX(topX, i, 0); store.setRectangleY(topY, i, 0); store.setRectangleWidth(width, i, 0); store.setRectangleHeight(height, i, 0); if (fontHeight >= 0) { store.setRectangleFontSize( new NonNegativeInteger(fontHeight), i, 0); } else { LOGGER.warn("Expected non-negative value for FontSize; got {}", fontHeight); } store.setRectangleStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setRectangleID(shapeID, i, 0); store.setImageROIRef(roiID, series, i); break; case ELLIPSE: int knots = in.readInt(); double[] xs = new double[knots]; double[] ys = new double[knots]; for (int j=0; j<xs.length; j++) { xs[j] = in.readDouble(); ys[j] = in.readDouble(); } double rx = 0, ry = 0, centerX = 0, centerY = 0; if (knots == 4) { double r1x = Math.abs(xs[2] - xs[0]) / 2; double r1y = Math.abs(ys[2] - ys[0]) / 2; double r2x = Math.abs(xs[3] - xs[1]) / 2; double r2y = Math.abs(ys[3] - ys[1]) / 2; if (r1x > r2x) { ry = r1y; rx = r2x; centerX = Math.min(xs[3], xs[1]) + rx; centerY = Math.min(ys[2], ys[0]) + ry; } else { ry = r2y; rx = r1x; centerX = Math.min(xs[2], xs[0]) + rx; centerY = Math.min(ys[3], ys[1]) + ry; } } else if (knots == 3) { // we are given the center point and one cut point for each axis centerX = xs[0]; centerY = ys[0]; rx = Math.sqrt(Math.pow(xs[1] - xs[0], 2) + Math.pow(ys[1] - ys[0], 2)); ry = Math.sqrt(Math.pow(xs[2] - xs[0], 2) + Math.pow(ys[2] - ys[0], 2)); // calculate rotation angle double slope = (ys[2] - centerY) / (xs[2] - centerX); double theta = Math.toDegrees(Math.atan(slope)); store.setEllipseTransform(getRotationTransform(theta), i, 0); } store.setEllipseX(centerX, i, 0); store.setEllipseY(centerY, i, 0); store.setEllipseRadiusX(rx, i, 0); store.setEllipseRadiusY(ry, i, 0); if (fontHeight >= 0) { store.setEllipseFontSize(new NonNegativeInteger(fontHeight), i, 0); } else { LOGGER.warn("Expected non-negative value for FontSize; got {}", fontHeight); } store.setEllipseStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setImageROIRef(roiID, series, i); store.setEllipseID(shapeID, i, 0); break; case CIRCLE: in.skipBytes(4); centerX = in.readDouble(); centerY = in.readDouble(); double curveX = in.readDouble(); double curveY = in.readDouble(); double radius = Math.sqrt(Math.pow(curveX - centerX, 2) + Math.pow(curveY - centerY, 2)); store.setEllipseX(centerX, i, 0); store.setEllipseY(centerY, i, 0); store.setEllipseRadiusX(radius, i, 0); store.setEllipseRadiusY(radius, i, 0); if (fontHeight >= 0) { store.setEllipseFontSize(new NonNegativeInteger(fontHeight), i, 0); } else { LOGGER.warn("Expected non-negative value for FontSize; got {}", fontHeight); } store.setEllipseStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setImageROIRef(roiID, series, i); store.setEllipseID(shapeID, i, 0); break; case CIRCLE_3POINT: in.skipBytes(4); // given 3 points on the perimeter of the circle, we need to // calculate the center and radius double[][] points = new double[3][2]; for (int j=0; j<points.length; j++) { for (int k=0; k<points[j].length; k++) { points[j][k] = in.readDouble(); } } double s = 0.5 * ((points[1][0] - points[2][0]) * (points[0][0] - points[2][0]) - (points[1][1] - points[2][1]) * (points[2][1] - points[0][1])); double div = (points[0][0] - points[1][0]) * (points[2][1] - points[0][1]) - (points[1][1] - points[0][1]) * (points[0][0] - points[2][0]); s /= div; double cx = 0.5 * (points[0][0] + points[1][0]) + s * (points[1][1] - points[0][1]); double cy = 0.5 * (points[0][1] + points[1][1]) + s * (points[0][0] - points[1][0]); double r = Math.sqrt(Math.pow(points[0][0] - cx, 2) + Math.pow(points[0][1] - cy, 2)); store.setEllipseX(cx, i, 0); store.setEllipseY(cy, i, 0); store.setEllipseRadiusX(r, i, 0); store.setEllipseRadiusY(r, i, 0); if (fontHeight >= 0) { store.setEllipseFontSize(new NonNegativeInteger(fontHeight), i, 0); } else { LOGGER.warn("Expected non-negative value for FontSize; got {}", fontHeight); } store.setEllipseStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setImageROIRef(roiID, series, i); store.setEllipseID(shapeID, i, 0); break; case ANGLE: in.skipBytes(4); points = new double[3][2]; for (int j=0; j<points.length; j++) { for (int k=0; k<points[j].length; k++) { points[j][k] = in.readDouble(); } } StringBuffer p = new StringBuffer(); for (int j=0; j<points.length; j++) { p.append(points[j][0]); p.append(","); p.append(points[j][1]); if (j < points.length - 1) p.append(" "); } store.setPolylinePoints(p.toString(), i, 0); if (fontHeight >= 0) { store.setPolylineFontSize(new NonNegativeInteger(fontHeight), i, 0); } else { LOGGER.warn("Expected non-negative value for FontSize; got {}", fontHeight); } store.setPolylineStrokeWidth(lineWidth, i, 0); store.setROIID(roiID, i); store.setImageROIRef(roiID, series, i); store.setPolylineID(shapeID, i, 0); break; case CLOSED_POLYLINE: case OPEN_POLYLINE: case POLYLINE_ARROW: int nKnots = in.readInt(); points = new double[nKnots][2]; for (int j=0; j<points.length; j++) { for (int k=0; k<points[j].length; k++) { points[j][k] = in.readDouble(); } } p = new StringBuffer(); for (int j=0; j<points.length; j++) { p.append(points[j][0]); p.append(","); p.append(points[j][1]); if (j < points.length - 1) p.append(" "); } store.setROIID(roiID, i); store.setImageROIRef(roiID, series, i); if (type != CLOSED_POLYLINE) { store.setPolylinePoints(p.toString(), i, 0); if (fontHeight >= 0) { store.setPolylineFontSize(new NonNegativeInteger(fontHeight), i, 0); } else { LOGGER.warn("Expected non-negative value for FontSize; got {}", fontHeight); } store.setPolylineStrokeWidth(lineWidth, i, 0); store.setPolylineID(shapeID, i, 0); } else { store.setPolygonPoints(p.toString(), i, 0); if (fontHeight >= 0) { store.setPolygonFontSize(new NonNegativeInteger(fontHeight), i, 0); } else { LOGGER.warn("Expected non-negative value for FontSize; got {}", fontHeight); } store.setPolygonStrokeWidth(lineWidth, i, 0); store.setPolygonID(shapeID, i, 0); } break; case CLOSED_BEZIER: case OPEN_BEZIER: case BEZIER_WITH_ARROW: nKnots = in.readInt(); points = new double[nKnots][2]; for (int j=0; j<points.length; j++) { for (int k=0; k<points[j].length; k++) { points[j][k] = in.readDouble(); } } p = new StringBuffer(); for (int j=0; j<points.length; j++) { p.append(points[j][0]); p.append(","); p.append(points[j][1]); if (j < points.length - 1) p.append(" "); } store.setROIID(roiID, i); store.setImageROIRef(roiID, series, i); if (type == OPEN_BEZIER) { store.setPolylinePoints(p.toString(), i, 0); if (fontHeight >= 0) { store.setPolylineFontSize(new NonNegativeInteger(fontHeight), i, 0); } else { LOGGER.warn("Expected non-negative value for FontSize; got {}", fontHeight); } store.setPolylineStrokeWidth(lineWidth, i, 0); store.setPolylineID(shapeID, i, 0); } else { store.setPolygonPoints(p.toString(), i, 0); if (fontHeight >= 0) { store.setPolygonFontSize(new NonNegativeInteger(fontHeight), i, 0); } else { LOGGER.warn("Expected non-negative value for FontSize; got {}", fontHeight); } store.setPolygonStrokeWidth(lineWidth, i, 0); store.setPolygonID(shapeID, i, 0); } break; default: i numberOfShapes continue; } // populate shape attributes in.seek(offset + blockLength); } totalROIs += numberOfShapes; } /** Parse a .mdb file and return a list of referenced .lsm files. */ private String[] parseMDB(String mdbFile) throws FormatException, IOException { Location mdb = new Location(mdbFile).getAbsoluteFile(); Location parent = mdb.getParentFile(); MDBService mdbService = null; try { ServiceFactory factory = new ServiceFactory(); mdbService = factory.getInstance(MDBService.class); } catch (DependencyException de) { throw new FormatException("MDB Tools Java library not found", de); } try { mdbService.initialize(mdbFile); } catch (Exception e) { return null; } Vector<Vector<String[]>> tables = mdbService.parseDatabase(); mdbService.close(); Vector<String> referencedLSMs = new Vector<String>(); int referenceCount = 0; for (Vector<String[]> table : tables) { String[] columnNames = table.get(0); String tableName = columnNames[0]; for (int row=1; row<table.size(); row++) { String[] tableRow = table.get(row); for (int col=0; col<tableRow.length; col++) { String key = tableName + " " + columnNames[col + 1] + " " + row; if (currentId != null) { addGlobalMeta(key, tableRow[col]); } if (tableName.equals("Recordings") && columnNames[col + 1] != null && columnNames[col + 1].equals("SampleData")) { String filename = tableRow[col].trim(); filename = filename.replace('\\', File.separatorChar); filename = filename.replace('/', File.separatorChar); filename = filename.substring(filename.lastIndexOf(File.separator) + 1); if (filename.length() > 0) { Location file = new Location(parent, filename); if (file.exists()) { referencedLSMs.add(file.getAbsolutePath()); } } referenceCount++; } } } } if (referencedLSMs.size() == referenceCount) { return referencedLSMs.toArray(new String[0]); } String[] fileList = parent.list(true); Arrays.sort(fileList); for (int i=0; i<fileList.length; i++) { String absolutePath = new Location(parent, fileList[i]).getAbsolutePath(); if (checkSuffix(fileList[i], "mdb") && (!absolutePath.equals(mdbFile) && !fileList[i].equals(mdbFile))) { if (referencedLSMs.size() > 0) { return referencedLSMs.toArray(new String[0]); } break; } } referencedLSMs.clear(); int mdbCount = 0; for (int i=0; i<fileList.length; i++) { String absolutePath = new Location(parent, fileList[i]).getAbsolutePath(); if (checkSuffix(fileList[i], "lsm")) { referencedLSMs.add(absolutePath); } else if (checkSuffix(fileList[i], "mdb")) { mdbCount++; } } if (mdbCount > 1 || ((referencedLSMs.size() > referenceCount) && mdbCount > 1)) { for (int i=0; i<fileList.length; i++) { String absolutePath = new Location(parent, fileList[i]).getAbsolutePath(); if (checkSuffix(fileList[i], "mdb") && !absolutePath.endsWith(mdbFile)) { String[] files = parseMDB(absolutePath); for (String f : files) { referencedLSMs.remove(f); } } } } return referencedLSMs.toArray(new String[0]); } private static Hashtable<Integer, String> createKeys() { Hashtable<Integer, String> h = new Hashtable<Integer, String>(); h.put(new Integer(0x10000001), "Name"); h.put(new Integer(0x4000000c), "Name"); h.put(new Integer(0x50000001), "Name"); h.put(new Integer(0x90000001), "Name"); h.put(new Integer(0x90000005), "Detection Channel Name"); h.put(new Integer(0xb0000003), "Name"); h.put(new Integer(0xd0000001), "Name"); h.put(new Integer(0x12000001), "Name"); h.put(new Integer(0x14000001), "Name"); h.put(new Integer(0x10000002), "Description"); h.put(new Integer(0x14000002), "Description"); h.put(new Integer(0x10000003), "Notes"); h.put(new Integer(0x10000004), "Objective"); h.put(new Integer(0x10000005), "Processing Summary"); h.put(new Integer(0x10000006), "Special Scan Mode"); h.put(new Integer(0x10000007), "Scan Type"); h.put(new Integer(0x10000008), "Scan Mode"); h.put(new Integer(0x10000009), "Number of Stacks"); h.put(new Integer(0x1000000a), "Lines Per Plane"); h.put(new Integer(0x1000000b), "Samples Per Line"); h.put(new Integer(0x1000000c), "Planes Per Volume"); h.put(new Integer(0x1000000d), "Images Width"); h.put(new Integer(0x1000000e), "Images Height"); h.put(new Integer(0x1000000f), "Number of Planes"); h.put(new Integer(0x10000010), "Number of Stacks"); h.put(new Integer(0x10000011), "Number of Channels"); h.put(new Integer(0x10000012), "Linescan XY Size"); h.put(new Integer(0x10000013), "Scan Direction"); h.put(new Integer(0x10000014), "Time Series"); h.put(new Integer(0x10000015), "Original Scan Data"); h.put(new Integer(0x10000016), "Zoom X"); h.put(new Integer(0x10000017), "Zoom Y"); h.put(new Integer(0x10000018), "Zoom Z"); h.put(new Integer(0x10000019), "Sample 0X"); h.put(new Integer(0x1000001a), "Sample 0Y"); h.put(new Integer(0x1000001b), "Sample 0Z"); h.put(new Integer(0x1000001c), "Sample Spacing"); h.put(new Integer(0x1000001d), "Line Spacing"); h.put(new Integer(0x1000001e), "Plane Spacing"); h.put(new Integer(0x1000001f), "Plane Width"); h.put(new Integer(0x10000020), "Plane Height"); h.put(new Integer(0x10000021), "Volume Depth"); h.put(new Integer(0x10000034), "Rotation"); h.put(new Integer(0x10000035), "Precession"); h.put(new Integer(0x10000036), "Sample 0Time"); h.put(new Integer(0x10000037), "Start Scan Trigger In"); h.put(new Integer(0x10000038), "Start Scan Trigger Out"); h.put(new Integer(0x10000039), "Start Scan Event"); h.put(new Integer(0x10000040), "Start Scan Time"); h.put(new Integer(0x10000041), "Stop Scan Trigger In"); h.put(new Integer(0x10000042), "Stop Scan Trigger Out"); h.put(new Integer(0x10000043), "Stop Scan Event"); h.put(new Integer(0x10000044), "Stop Scan Time"); h.put(new Integer(0x10000045), "Use ROIs"); h.put(new Integer(0x10000046), "Use Reduced Memory ROIs"); h.put(new Integer(0x10000047), "User"); h.put(new Integer(0x10000048), "Use B/C Correction"); h.put(new Integer(0x10000049), "Position B/C Contrast 1"); h.put(new Integer(0x10000050), "Position B/C Contrast 2"); h.put(new Integer(0x10000051), "Interpolation Y"); h.put(new Integer(0x10000052), "Camera Binning"); h.put(new Integer(0x10000053), "Camera Supersampling"); h.put(new Integer(0x10000054), "Camera Frame Width"); h.put(new Integer(0x10000055), "Camera Frame Height"); h.put(new Integer(0x10000056), "Camera Offset X"); h.put(new Integer(0x10000057), "Camera Offset Y"); h.put(new Integer(0x40000001), "Multiplex Type"); h.put(new Integer(0x40000002), "Multiplex Order"); h.put(new Integer(0x40000003), "Sampling Mode"); h.put(new Integer(0x40000004), "Sampling Method"); h.put(new Integer(0x40000005), "Sampling Number"); h.put(new Integer(0x40000006), "Acquire"); h.put(new Integer(0x50000002), "Acquire"); h.put(new Integer(0x7000000b), "Acquire"); h.put(new Integer(0x90000004), "Acquire"); h.put(new Integer(0xd0000017), "Acquire"); h.put(new Integer(0x40000007), "Sample Observation Time"); h.put(new Integer(0x40000008), "Time Between Stacks"); h.put(new Integer(0x4000000d), "Collimator 1 Name"); h.put(new Integer(0x4000000e), "Collimator 1 Position"); h.put(new Integer(0x4000000f), "Collimator 2 Name"); h.put(new Integer(0x40000010), "Collimator 2 Position"); h.put(new Integer(0x40000011), "Is Bleach Track"); h.put(new Integer(0x40000012), "Bleach After Scan Number"); h.put(new Integer(0x40000013), "Bleach Scan Number"); h.put(new Integer(0x40000014), "Trigger In"); h.put(new Integer(0x12000004), "Trigger In"); h.put(new Integer(0x14000003), "Trigger In"); h.put(new Integer(0x40000015), "Trigger Out"); h.put(new Integer(0x12000005), "Trigger Out"); h.put(new Integer(0x14000004), "Trigger Out"); h.put(new Integer(0x40000016), "Is Ratio Track"); h.put(new Integer(0x40000017), "Bleach Count"); h.put(new Integer(0x40000018), "SPI Center Wavelength"); h.put(new Integer(0x40000019), "Pixel Time"); h.put(new Integer(0x40000020), "ID Condensor Frontlens"); h.put(new Integer(0x40000021), "Condensor Frontlens"); h.put(new Integer(0x40000022), "ID Field Stop"); h.put(new Integer(0x40000023), "Field Stop Value"); h.put(new Integer(0x40000024), "ID Condensor Aperture"); h.put(new Integer(0x40000025), "Condensor Aperture"); h.put(new Integer(0x40000026), "ID Condensor Revolver"); h.put(new Integer(0x40000027), "Condensor Revolver"); h.put(new Integer(0x40000028), "ID Transmission Filter 1"); h.put(new Integer(0x40000029), "ID Transmission 1"); h.put(new Integer(0x40000030), "ID Transmission Filter 2"); h.put(new Integer(0x40000031), "ID Transmission 2"); h.put(new Integer(0x40000032), "Repeat Bleach"); h.put(new Integer(0x40000033), "Enable Spot Bleach Pos"); h.put(new Integer(0x40000034), "Spot Bleach Position X"); h.put(new Integer(0x40000035), "Spot Bleach Position Y"); h.put(new Integer(0x40000036), "Bleach Position Z"); h.put(new Integer(0x50000003), "Power"); h.put(new Integer(0x90000002), "Power"); h.put(new Integer(0x70000003), "Detector Gain"); h.put(new Integer(0x70000005), "Amplifier Gain"); h.put(new Integer(0x70000007), "Amplifier Offset"); h.put(new Integer(0x70000009), "Pinhole Diameter"); h.put(new Integer(0x7000000c), "Detector Name"); h.put(new Integer(0x7000000d), "Amplifier Name"); h.put(new Integer(0x7000000e), "Pinhole Name"); h.put(new Integer(0x7000000f), "Filter Set Name"); h.put(new Integer(0x70000010), "Filter Name"); h.put(new Integer(0x70000013), "Integrator Name"); h.put(new Integer(0x70000014), "Detection Channel Name"); h.put(new Integer(0x70000015), "Detector Gain B/C 1"); h.put(new Integer(0x70000016), "Detector Gain B/C 2"); h.put(new Integer(0x70000017), "Amplifier Gain B/C 1"); h.put(new Integer(0x70000018), "Amplifier Gain B/C 2"); h.put(new Integer(0x70000019), "Amplifier Offset B/C 1"); h.put(new Integer(0x70000020), "Amplifier Offset B/C 2"); h.put(new Integer(0x70000021), "Spectral Scan Channels"); h.put(new Integer(0x70000022), "SPI Wavelength Start"); h.put(new Integer(0x70000023), "SPI Wavelength End"); h.put(new Integer(0x70000026), "Dye Name"); h.put(new Integer(0xd0000014), "Dye Name"); h.put(new Integer(0x70000027), "Dye Folder"); h.put(new Integer(0xd0000015), "Dye Folder"); h.put(new Integer(0x90000003), "Wavelength"); h.put(new Integer(0x90000006), "Power B/C 1"); h.put(new Integer(0x90000007), "Power B/C 2"); h.put(new Integer(0xb0000001), "Filter Set"); h.put(new Integer(0xb0000002), "Filter"); h.put(new Integer(0xd0000004), "Color"); h.put(new Integer(0xd0000005), "Sample Type"); h.put(new Integer(0xd0000006), "Bits Per Sample"); h.put(new Integer(0xd0000007), "Ratio Type"); h.put(new Integer(0xd0000008), "Ratio Track 1"); h.put(new Integer(0xd0000009), "Ratio Track 2"); h.put(new Integer(0xd000000a), "Ratio Channel 1"); h.put(new Integer(0xd000000b), "Ratio Channel 2"); h.put(new Integer(0xd000000c), "Ratio Const. 1"); h.put(new Integer(0xd000000d), "Ratio Const. 2"); h.put(new Integer(0xd000000e), "Ratio Const. 3"); h.put(new Integer(0xd000000f), "Ratio Const. 4"); h.put(new Integer(0xd0000010), "Ratio Const. 5"); h.put(new Integer(0xd0000011), "Ratio Const. 6"); h.put(new Integer(0xd0000012), "Ratio First Images 1"); h.put(new Integer(0xd0000013), "Ratio First Images 2"); h.put(new Integer(0xd0000016), "Spectrum"); h.put(new Integer(0x12000003), "Interval"); return h; } private Integer readEntry() throws IOException { return new Integer(in.readInt()); } private Object readValue() throws IOException { int blockType = in.readInt(); int dataSize = in.readInt(); switch (blockType) { case TYPE_LONG: return new Long(in.readInt()); case TYPE_RATIONAL: return new Double(in.readDouble()); case TYPE_ASCII: String s = in.readString(dataSize).trim(); StringBuffer sb = new StringBuffer(); for (int i=0; i<s.length(); i++) { if (s.charAt(i) >= 10) sb.append(s.charAt(i)); else break; } return sb.toString(); case TYPE_SUBBLOCK: return null; } in.skipBytes(dataSize); return ""; } private void parseApplicationTags() throws IOException { int blockSize = in.readInt(); int numEntries = in.readInt(); for (int i=0; i<numEntries; i++) { long fp = in.getFilePointer(); int entrySize = in.readInt(); int entryNameLength = in.readInt(); String entryName = in.readString(entryNameLength); int dataType = in.readInt(); int dataSize = in.readInt(); Object data = null; switch (dataType) { case TYPE_ASCII: data = in.readString(dataSize); break; case TYPE_LONG: data = new Integer(in.readInt()); break; case TYPE_RATIONAL: data = new Double(in.readDouble()); break; case TYPE_DATE: data = new Long(in.readLong()); break; case TYPE_BOOLEAN: data = new Boolean(in.readInt() == 0); break; } addGlobalMeta(entryName, data); if (in.getFilePointer() == fp + entrySize) { continue; } int nDimensions = in.readInt(); int[] coordinate = new int[nDimensions]; for (int n=0; n<nDimensions; n++) { coordinate[n] = in.readInt(); } } } // -- Helper classes -- class SubBlock { public Hashtable<Integer, Object> blockData; public boolean acquire = true; public SubBlock() { try { read(); } catch (IOException e) { LOGGER.debug("Failed to read sub-block data", e); } } protected int getIntValue(int key) { Object o = blockData.get(new Integer(key)); if (o == null) return -1; return !(o instanceof Number) ? -1 : ((Number) o).intValue(); } protected float getFloatValue(int key) { Object o = blockData.get(new Integer(key)); if (o == null) return -1f; return !(o instanceof Number) ? -1f : ((Number) o).floatValue(); } protected double getDoubleValue(int key) { Object o = blockData.get(new Integer(key)); if (o == null) return -1d; return !(o instanceof Number) ? -1d : ((Number) o).doubleValue(); } protected String getStringValue(int key) { Object o = blockData.get(new Integer(key)); return o == null ? null : o.toString(); } protected void read() throws IOException { blockData = new Hashtable<Integer, Object>(); Integer entry = readEntry(); Object value = readValue(); while (value != null && in.getFilePointer() < in.length()) { if (!blockData.containsKey(entry)) blockData.put(entry, value); entry = readEntry(); value = readValue(); } } public void addToHashtable() { String prefix = this.getClass().getSimpleName() + " int index = 1; while (getSeriesMeta(prefix + index + " Acquire") != null) index++; prefix += index; Integer[] keys = blockData.keySet().toArray(new Integer[0]); for (Integer key : keys) { if (METADATA_KEYS.get(key) != null) { addSeriesMeta(prefix + " " + METADATA_KEYS.get(key), blockData.get(key)); if (METADATA_KEYS.get(key).equals("Bits Per Sample")) { core[getSeries()].bitsPerPixel = Integer.parseInt(blockData.get(key).toString()); } else if (METADATA_KEYS.get(key).equals("User")) { userName = blockData.get(key).toString(); } } } addGlobalMeta(prefix + " Acquire", new Boolean(acquire)); } } class Recording extends SubBlock { public String description; public String name; public String binning; public String startTime; // Objective data public String correction, immersion; public Integer magnification; public Double lensNA; public Boolean iris; protected void read() throws IOException { super.read(); description = getStringValue(RECORDING_DESCRIPTION); name = getStringValue(RECORDING_NAME); binning = getStringValue(RECORDING_CAMERA_BINNING); if (binning != null && binning.indexOf("x") == -1) { if (binning.equals("0")) binning = null; else binning += "x" + binning; } // start time in days since Dec 30 1899 long stamp = (long) (getDoubleValue(RECORDING_SAMPLE_0TIME) * 86400000); if (stamp > 0) { startTime = DateTools.convertDate(stamp, DateTools.MICROSOFT); } zoom = getDoubleValue(RECORDING_ZOOM); String objective = getStringValue(RECORDING_OBJECTIVE); correction = ""; if (objective == null) objective = ""; String[] tokens = objective.split(" "); int next = 0; for (; next<tokens.length; next++) { if (tokens[next].indexOf("/") != -1) break; correction += tokens[next]; } if (next < tokens.length) { String p = tokens[next++]; int slash = p.indexOf("/"); if (slash > 0) { try { magnification = new Integer(p.substring(0, slash - 1)); } catch (NumberFormatException e) { } } if (slash >= 0 && slash < p.length() - 1) { try { lensNA = new Double(p.substring(slash + 1)); } catch (NumberFormatException e) { } } } immersion = next < tokens.length ? tokens[next++] : "Unknown"; iris = Boolean.FALSE; if (next < tokens.length) { iris = new Boolean(tokens[next++].trim().equalsIgnoreCase("iris")); } } } class Laser extends SubBlock { public String medium, type, model; public Double power; protected void read() throws IOException { super.read(); model = getStringValue(LASER_NAME); type = getStringValue(LASER_NAME); if (type == null) type = ""; medium = ""; if (type.startsWith("HeNe")) { medium = "HeNe"; type = "Gas"; } else if (type.startsWith("Argon")) { medium = "Ar"; type = "Gas"; } else if (type.equals("Titanium:Sapphire") || type.equals("Mai Tai")) { medium = "TiSapphire"; type = "SolidState"; } else if (type.equals("YAG")) { medium = ""; type = "SolidState"; } else if (type.equals("Ar/Kr")) { medium = ""; type = "Gas"; } acquire = getIntValue(LASER_ACQUIRE) != 0; power = getDoubleValue(LASER_POWER); } } class Track extends SubBlock { public Double timeIncrement; protected void read() throws IOException { super.read(); timeIncrement = getDoubleValue(TRACK_TIME_BETWEEN_STACKS); acquire = getIntValue(TRACK_ACQUIRE) != 0; } } class DetectionChannel extends SubBlock { public Double pinhole; public Double gain, amplificationGain; public String filter, filterSet; public String channelName; protected void read() throws IOException { super.read(); pinhole = new Double(getDoubleValue(CHANNEL_PINHOLE_DIAMETER)); gain = new Double(getDoubleValue(CHANNEL_DETECTOR_GAIN)); amplificationGain = new Double(getDoubleValue(CHANNEL_AMPLIFIER_GAIN)); filter = getStringValue(CHANNEL_FILTER); if (filter != null) { filter = filter.trim(); if (filter.length() == 0 || filter.equals("None")) { filter = null; } } filterSet = getStringValue(CHANNEL_FILTER_SET); channelName = getStringValue(CHANNEL_NAME); acquire = getIntValue(CHANNEL_ACQUIRE) != 0; } } class IlluminationChannel extends SubBlock { public Integer wavelength; public Double attenuation; public String name; protected void read() throws IOException { super.read(); wavelength = new Integer(getIntValue(ILLUM_CHANNEL_WAVELENGTH)); attenuation = new Double(getDoubleValue(ILLUM_CHANNEL_ATTENUATION)); acquire = getIntValue(ILLUM_CHANNEL_ACQUIRE) != 0; name = getStringValue(ILLUM_CHANNEL_NAME); try { wavelength = new Integer(name); } catch (NumberFormatException e) { } } } class DataChannel extends SubBlock { public String name; protected void read() throws IOException { super.read(); name = getStringValue(DATA_CHANNEL_NAME); for (int i=0; i<name.length(); i++) { if (name.charAt(i) < 10) { name = name.substring(0, i); break; } } acquire = getIntValue(DATA_CHANNEL_ACQUIRE) != 0; } } class BeamSplitter extends SubBlock { public String filter, filterSet; protected void read() throws IOException { super.read(); filter = getStringValue(BEAM_SPLITTER_FILTER); if (filter != null) { filter = filter.trim(); if (filter.length() == 0 || filter.equals("None")) { filter = null; } } filterSet = getStringValue(BEAM_SPLITTER_FILTER_SET); } } class Timer extends SubBlock { } class Marker extends SubBlock { } }
// ZeissLSMReader.java package loci.formats.in; import java.io.*; import java.util.*; import loci.common.*; import loci.formats.*; import loci.formats.meta.FilterMetadata; import loci.formats.meta.MetadataStore; public class ZeissLSMReader extends BaseTiffReader { // -- Constants -- public static final String[] MDB_SUFFIX = {"mdb"}; /** Tag identifying a Zeiss LSM file. */ private static final int ZEISS_ID = 34412; /** Data types. */ private static final int TYPE_SUBBLOCK = 0; private static final int TYPE_ASCII = 2; private static final int TYPE_LONG = 4; private static final int TYPE_RATIONAL = 5; /** Subblock types. */ private static final int SUBBLOCK_RECORDING = 0x10000000; private static final int SUBBLOCK_LASERS = 0x30000000; private static final int SUBBLOCK_LASER = 0x50000000; private static final int SUBBLOCK_TRACKS = 0x20000000; private static final int SUBBLOCK_TRACK = 0x40000000; private static final int SUBBLOCK_DETECTION_CHANNELS = 0x60000000; private static final int SUBBLOCK_DETECTION_CHANNEL = 0x70000000; private static final int SUBBLOCK_ILLUMINATION_CHANNELS = 0x80000000; private static final int SUBBLOCK_ILLUMINATION_CHANNEL = 0x90000000; private static final int SUBBLOCK_BEAM_SPLITTERS = 0xa0000000; private static final int SUBBLOCK_BEAM_SPLITTER = 0xb0000000; private static final int SUBBLOCK_DATA_CHANNELS = 0xc0000000; private static final int SUBBLOCK_DATA_CHANNEL = 0xd0000000; private static final int SUBBLOCK_TIMERS = 0x11000000; private static final int SUBBLOCK_TIMER = 0x12000000; private static final int SUBBLOCK_MARKERS = 0x13000000; private static final int SUBBLOCK_MARKER = 0x14000000; private static final int SUBBLOCK_END = (int) 0xffffffff; private static final int SUBBLOCK_GAMMA = 1; private static final int SUBBLOCK_BRIGHTNESS = 2; private static final int SUBBLOCK_CONTRAST = 3; private static final int SUBBLOCK_RAMP = 4; private static final int SUBBLOCK_KNOTS = 5; private static final int SUBBLOCK_PALETTE = 6; /** Data types. */ private static final int RECORDING_ENTRY_DESCRIPTION = 0x10000002; private static final int RECORDING_ENTRY_OBJECTIVE = 0x10000004; private static final int TRACK_ENTRY_TIME_BETWEEN_STACKS = 0x4000000b; private static final int LASER_ENTRY_NAME = 0x50000001; private static final int CHANNEL_ENTRY_DETECTOR_GAIN = 0x70000003; private static final int CHANNEL_ENTRY_PINHOLE_DIAMETER = 0x70000009; private static final int CHANNEL_ENTRY_SPI_WAVELENGTH_START = 0x70000022; private static final int CHANNEL_ENTRY_SPI_WAVELENGTH_END = 0x70000023; private static final int ILLUM_CHANNEL_WAVELENGTH = 0x90000003; private static final int START_TIME = 0x10000036; private static final int DATA_CHANNEL_NAME = 0xd0000001; // -- Static fields -- private static Hashtable metadataKeys = createKeys(); // -- Fields -- private double pixelSizeX, pixelSizeY, pixelSizeZ; private boolean thumbnailsRemoved = false; private byte[] lut = null; private Vector timestamps; private int validChannels; private String mdbFilename; // -- Constructor -- /** Constructs a new Zeiss LSM reader. */ public ZeissLSMReader() { super("Zeiss Laser-Scanning Microscopy", "lsm"); } // -- IFormatHandler API methods -- /* @see loci.formats.IFormatHandler#close() */ public void close() throws IOException { super.close(); pixelSizeX = pixelSizeY = pixelSizeZ = 0f; lut = null; thumbnailsRemoved = false; timestamps = null; validChannels = 0; mdbFilename = null; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#getUsedFiles() */ public String[] getUsedFiles() { FormatTools.assertId(currentId, true, 1); if (mdbFilename == null) return super.getUsedFiles(); return new String[] {currentId, mdbFilename}; } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); if (lut == null || getPixelType() != FormatTools.UINT8) return null; byte[][] b = new byte[3][256]; for (int i=2; i>=3-validChannels; i for (int j=0; j<256; j++) { b[i][j] = (byte) j; } } return b; } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() throws FormatException, IOException { FormatTools.assertId(currentId, true, 1); if (lut == null || getPixelType() != FormatTools.UINT16) return null; short[][] s = new short[3][65536]; for (int i=2; i>=3-validChannels; i for (int j=0; j<s[i].length; j++) { s[i][j] = (short) j; } } return s; } // -- Internal BaseTiffReader API methods -- /* @see BaseTiffReader#initMetadata() */ protected void initMetadata() { if (!thumbnailsRemoved) return; Hashtable ifd = ifds[0]; status("Reading LSM metadata"); MetadataStore store = new FilterMetadata(getMetadataStore(), isMetadataFiltered()); try { super.initStandardMetadata(); // get TIF_CZ_LSMINFO structure short[] s = TiffTools.getIFDShortArray(ifd, ZEISS_ID, true); byte[] cz = new byte[s.length]; for (int i=0; i<s.length; i++) { cz[i] = (byte) s[i]; } RandomAccessStream ras = new RandomAccessStream(cz); ras.order(isLittleEndian()); put("MagicNumber", ras.readInt()); put("StructureSize", ras.readInt()); put("DimensionX", ras.readInt()); put("DimensionY", ras.readInt()); core[0].sizeZ = ras.readInt(); ras.skipBytes(4); core[0].sizeT = ras.readInt(); int dataType = ras.readInt(); switch (dataType) { case 2: put("DataType", "12 bit unsigned integer"); break; case 5: put("DataType", "32 bit float"); break; case 0: put("DataType", "varying data types"); break; default: put("DataType", "8 bit unsigned integer"); } put("ThumbnailX", ras.readInt()); put("ThumbnailY", ras.readInt()); // pixel sizes are stored in meters, we need them in microns pixelSizeX = ras.readDouble() * 1000000; pixelSizeY = ras.readDouble() * 1000000; pixelSizeZ = ras.readDouble() * 1000000; put("VoxelSizeX", new Double(pixelSizeX)); put("VoxelSizeY", new Double(pixelSizeY)); put("VoxelSizeZ", new Double(pixelSizeZ)); put("OriginX", ras.readDouble()); put("OriginY", ras.readDouble()); put("OriginZ", ras.readDouble()); int scanType = ras.readShort(); switch (scanType) { case 0: put("ScanType", "x-y-z scan"); core[0].dimensionOrder = "XYZCT"; break; case 1: put("ScanType", "z scan (x-z plane)"); core[0].dimensionOrder = "XYZCT"; break; case 2: put("ScanType", "line scan"); core[0].dimensionOrder = "XYZCT"; break; case 3: put("ScanType", "time series x-y"); core[0].dimensionOrder = "XYTCZ"; break; case 4: put("ScanType", "time series x-z"); core[0].dimensionOrder = "XYZTC"; break; case 5: put("ScanType", "time series 'Mean of ROIs'"); core[0].dimensionOrder = "XYTCZ"; break; case 6: put("ScanType", "time series x-y-z"); core[0].dimensionOrder = "XYZTC"; break; case 7: put("ScanType", "spline scan"); core[0].dimensionOrder = "XYCTZ"; break; case 8: put("ScanType", "spline scan x-z"); core[0].dimensionOrder = "XYCZT"; break; case 9: put("ScanType", "time series spline plane x-z"); core[0].dimensionOrder = "XYTCZ"; break; case 10: put("ScanType", "point mode"); core[0].dimensionOrder = "XYZCT"; break; default: put("ScanType", "x-y-z scan"); core[0].dimensionOrder = "XYZCT"; } store.setImageName("", 0); MetadataTools.setDefaultCreationDate(store, getCurrentFile(), 0); int spectralScan = ras.readShort(); if (spectralScan != 1) put("SpectralScan", "no spectral scan"); else put("SpectralScan", "acquired with spectral scan"); int type = ras.readInt(); switch (type) { case 1: put("DataType2", "calculated data"); break; case 2: put("DataType2", "animation"); break; default: put("DataType2", "original scan data"); } long[] overlayOffsets = new long[9]; String[] overlayKeys = new String[] {"VectorOverlay", "InputLut", "OutputLut", "ROI", "BleachROI", "MeanOfRoisOverlay", "TopoIsolineOverlay", "TopoProfileOverlay", "LinescanOverlay"}; overlayOffsets[0] = ras.readInt(); overlayOffsets[1] = ras.readInt(); overlayOffsets[2] = ras.readInt(); long channelColorsOffset = ras.readInt(); put("TimeInterval", ras.readDouble()); ras.skipBytes(4); long scanInformationOffset = ras.readInt(); ras.skipBytes(4); long timeStampOffset = ras.readInt(); long eventListOffset = ras.readInt(); overlayOffsets[3] = ras.readInt(); overlayOffsets[4] = ras.readInt(); ras.skipBytes(4); put("DisplayAspectX", ras.readDouble()); put("DisplayAspectY", ras.readDouble()); put("DisplayAspectZ", ras.readDouble()); put("DisplayAspectTime", ras.readDouble()); overlayOffsets[5] = ras.readInt(); overlayOffsets[6] = ras.readInt(); overlayOffsets[7] = ras.readInt(); overlayOffsets[8] = ras.readInt(); for (int i=0; i<overlayOffsets.length; i++) { parseOverlays(overlayOffsets[i], overlayKeys[i]); } put("ToolbarFlags", ras.readInt()); ras.close(); // read referenced structures core[0].indexed = lut != null && getSizeC() == 1; if (isIndexed()) { core[0].sizeC = 1; core[0].rgb = false; } if (getSizeC() == 0) core[0].sizeC = 1; if (isRGB()) { // shuffle C to front of order string core[0].dimensionOrder = getDimensionOrder().replaceAll("C", ""); core[0].dimensionOrder = getDimensionOrder().replaceAll("XY", "XYC"); } put("DimensionZ", getSizeZ()); put("DimensionChannels", getSizeC()); if (channelColorsOffset != 0) { in.seek(channelColorsOffset + 16); int namesOffset = in.readInt(); // read in the intensity value for each color if (namesOffset > 0) { in.skipBytes(namesOffset - 16); for (int i=0; i<getSizeC(); i++) { if (in.getFilePointer() >= in.length() - 1) break; // we want to read until we find a null char String name = in.readCString(); if (name.length() <= 128) put("ChannelName" + i, name); } } } if (timeStampOffset != 0) { in.seek(timeStampOffset + 8); for (int i=0; i<getSizeT(); i++) { double stamp = in.readDouble(); put("TimeStamp" + i, stamp); timestamps.add(new Double(stamp)); } } if (eventListOffset != 0) { in.seek(eventListOffset + 4); int numEvents = in.readInt(); in.seek(in.getFilePointer() - 4); in.order(!in.isLittleEndian()); int tmpEvents = in.readInt(); if (numEvents < 0) numEvents = tmpEvents; else numEvents = (int) Math.min(numEvents, tmpEvents); in.order(!in.isLittleEndian()); if (numEvents > 65535) numEvents = 0; for (int i=0; i<numEvents; i++) { if (in.getFilePointer() + 16 <= in.length()) { int size = in.readInt(); double eventTime = in.readDouble(); int eventType = in.readInt(); put("Event" + i + " Time", eventTime); put("Event" + i + " Type", eventType); long fp = in.getFilePointer(); int len = size - 16; if (len > 65536) len = 65536; if (len < 0) len = 0; put("Event" + i + " Description", in.readString(len)); in.seek(fp + size - 16); if (in.getFilePointer() < 0) break; } } } if (scanInformationOffset != 0) { in.seek(scanInformationOffset); Stack prefix = new Stack(); int count = 1; Object value = null; boolean done = false; int nextLaserMedium = 0, nextLaserType = 0, nextGain = 0; int nextPinhole = 0, nextEmWave = 0, nextExWave = 0; int nextChannelName = 0; while (!done) { int entry = in.readInt(); int blockType = in.readInt(); int dataSize = in.readInt(); switch (blockType) { case TYPE_SUBBLOCK: switch (entry) { case SUBBLOCK_RECORDING: prefix.push("Recording"); break; case SUBBLOCK_LASERS: prefix.push("Lasers"); break; case SUBBLOCK_LASER: prefix.push("Laser " + count); count++; break; case SUBBLOCK_TRACKS: prefix.push("Tracks"); break; case SUBBLOCK_TRACK: prefix.push("Track " + count); count++; break; case SUBBLOCK_DETECTION_CHANNELS: prefix.push("Detection Channels"); break; case SUBBLOCK_DETECTION_CHANNEL: prefix.push("Detection Channel " + count); count++; validChannels = count; break; case SUBBLOCK_ILLUMINATION_CHANNELS: prefix.push("Illumination Channels"); break; case SUBBLOCK_ILLUMINATION_CHANNEL: prefix.push("Illumination Channel " + count); count++; break; case SUBBLOCK_BEAM_SPLITTERS: prefix.push("Beam Splitters"); break; case SUBBLOCK_BEAM_SPLITTER: prefix.push("Beam Splitter " + count); count++; break; case SUBBLOCK_DATA_CHANNELS: prefix.push("Data Channels"); break; case SUBBLOCK_DATA_CHANNEL: prefix.push("Data Channel " + count); count++; break; case SUBBLOCK_TIMERS: prefix.push("Timers"); break; case SUBBLOCK_TIMER: prefix.push("Timer " + count); count++; break; case SUBBLOCK_MARKERS: prefix.push("Markers"); break; case SUBBLOCK_MARKER: prefix.push("Marker " + count); count++; break; case SUBBLOCK_END: count = 1; if (prefix.size() > 0) prefix.pop(); if (prefix.size() == 0) done = true; break; } break; case TYPE_LONG: value = new Long(in.readInt()); break; case TYPE_RATIONAL: value = new Double(in.readDouble()); break; case TYPE_ASCII: value = in.readString(dataSize); break; } String key = getKey(prefix, entry).trim(); if (value instanceof String) value = ((String) value).trim(); if (key != null) addMeta(key, value); float n; switch (entry) { case RECORDING_ENTRY_DESCRIPTION: store.setImageDescription(value.toString(), 0); break; case RECORDING_ENTRY_OBJECTIVE: String[] tokens = value.toString().split(" "); StringBuffer model = new StringBuffer(); int next = 0; for (; next<tokens.length; next++) { if (tokens[next].indexOf("/") != -1) break; model.append(tokens[next]); } store.setObjectiveModel(model.toString(), 0, 0); if (next < tokens.length) { String p = tokens[next++]; String mag = p.substring(0, p.indexOf("/") - 1); String na = p.substring(p.indexOf("/") + 1); store.setObjectiveNominalMagnification(new Integer(mag), 0, 0); store.setObjectiveLensNA(new Float(na), 0, 0); } if (next < tokens.length) { store.setObjectiveImmersion(tokens[next++], 0, 0); } break; case TRACK_ENTRY_TIME_BETWEEN_STACKS: store.setDimensionsTimeIncrement( new Float(value.toString()), 0, 0); break; case LASER_ENTRY_NAME: String medium = value.toString(); String laserType = null; if (medium.startsWith("HeNe")) { medium = "HeNe"; laserType = "Gas"; } else if (medium.startsWith("Argon")) { medium = "Ar"; laserType = "Gas"; } else if (medium.equals("Titanium:Sapphire") || medium.equals("Mai Tai")) { medium = "TiSapphire"; laserType = "SolidState"; } else if (medium.equals("YAG")) { medium = null; laserType = "SolidState"; } else if (medium.equals("Ar/Kr")) { medium = null; laserType = "Gas"; } else if (medium.equals("Enterprise")) medium = null; if (medium != null && laserType != null) { store.setLaserLaserMedium(medium, 0, nextLaserMedium++); store.setLaserType(laserType, 0, nextLaserType++); } break; //case LASER_POWER: // TODO: this is a setting, not a fixed value //n = Float.parseFloat(value.toString()); //store.setLaserPower(new Float(n), 0, count - 1); //break; case CHANNEL_ENTRY_DETECTOR_GAIN: //n = Float.parseFloat(value.toString()); //store.setDetectorSettingsGain(new Float(n), 0, nextGain++); break; case CHANNEL_ENTRY_PINHOLE_DIAMETER: n = Float.parseFloat(value.toString()); store.setLogicalChannelPinholeSize(new Float(n), 0, nextPinhole++); break; case ILLUM_CHANNEL_WAVELENGTH: n = Float.parseFloat(value.toString()); if (nextEmWave < getSizeC()) { store.setLogicalChannelEmWave(new Integer((int) n), 0, nextEmWave++); } if (nextExWave < getSizeC()) { store.setLogicalChannelExWave(new Integer((int) n), 0, nextExWave++); } break; case START_TIME: // date/time on which the first pixel was acquired, in days // since 30 December 1899 double time = Double.parseDouble(value.toString()); store.setImageCreationDate(DataTools.convertDate( (long) (time * 86400000), DataTools.MICROSOFT), 0); break; case DATA_CHANNEL_NAME: store.setLogicalChannelName(value.toString(), 0, nextChannelName++); break; } if (!done) done = in.getFilePointer() >= in.length() - 12; } } } catch (FormatException exc) { if (debug) trace(exc); } catch (IOException exc) { if (debug) trace(exc); } if (isIndexed()) core[0].rgb = false; if (getEffectiveSizeC() == 0) core[0].imageCount = getSizeZ() * getSizeT(); else core[0].imageCount = getSizeZ() * getSizeT() * getEffectiveSizeC(); if (getImageCount() != ifds.length) { int diff = getImageCount() - ifds.length; core[0].imageCount = ifds.length; if (diff % getSizeZ() == 0) { core[0].sizeT -= (diff / getSizeZ()); } else if (diff % getSizeT() == 0) { core[0].sizeZ -= (diff / getSizeT()); } else if (getSizeZ() > 1) { core[0].sizeZ = ifds.length; core[0].sizeT = 1; } else if (getSizeT() > 1) { core[0].sizeT = ifds.length; core[0].sizeZ = 1; } } if (getSizeZ() == 0) core[0].sizeZ = getImageCount(); if (getSizeT() == 0) core[0].sizeT = getImageCount() / getSizeZ(); MetadataTools.populatePixels(store, this, true); Float pixX = new Float((float) pixelSizeX); Float pixY = new Float((float) pixelSizeY); Float pixZ = new Float((float) pixelSizeZ); store.setDimensionsPhysicalSizeX(pixX, 0, 0); store.setDimensionsPhysicalSizeY(pixY, 0, 0); store.setDimensionsPhysicalSizeZ(pixZ, 0, 0); float firstStamp = timestamps.size() == 0 ? 0f : ((Double) timestamps.get(0)).floatValue(); for (int i=0; i<getImageCount(); i++) { int[] zct = FormatTools.getZCTCoords(this, i); if (zct[2] < timestamps.size()) { float thisStamp = ((Double) timestamps.get(zct[2])).floatValue(); store.setPlaneTimingDeltaT(new Float(thisStamp - firstStamp), 0, 0, i); float nextStamp = zct[2] < getSizeT() - 1 ? ((Double) timestamps.get(zct[2] + 1)).floatValue() : thisStamp; if (i == getSizeT() - 1 && zct[2] > 0) { thisStamp = ((Double) timestamps.get(zct[2] - 1)).floatValue(); } store.setPlaneTimingExposureTime(new Float(nextStamp - thisStamp), 0, 0, i); } } // see if we have an associated MDB file Location dir = new Location(currentId).getAbsoluteFile().getParentFile(); String[] dirList = dir.list(); for (int i=0; i<dirList.length; i++) { if (checkSuffix(dirList[i], MDB_SUFFIX)) { try { Location file = new Location(dir.getPath(), dirList[i]); if (!file.isDirectory()) { mdbFilename = file.getAbsolutePath(); Vector[] tables = MDBParser.parseDatabase(mdbFilename); for (int table=0; table<tables.length; table++) { String[] columnNames = (String[]) tables[table].get(0); for (int row=1; row<tables[table].size(); row++) { String[] tableRow = (String[]) tables[table].get(row); String baseKey = columnNames[0] + " "; for (int col=0; col<tableRow.length; col++) { addMeta(baseKey + columnNames[col + 1] + " " + row, tableRow[col]); } } } } } catch (Exception exc) { if (debug) trace(exc); } i = dirList.length; } } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { if (debug) debug("ZeissLSMReader.initFile(" + id + ")"); thumbnailsRemoved = false; super.initFile(id); timestamps = new Vector(); // go through the IFD hashtable array and // remove anything with NEW_SUBFILE_TYPE = 1 // NEW_SUBFILE_TYPE = 1 indicates that the IFD // contains a thumbnail image status("Removing thumbnails"); Vector newIFDs = new Vector(); for (int i=0; i<ifds.length; i++) { long subFileType = TiffTools.getIFDLongValue(ifds[i], TiffTools.NEW_SUBFILE_TYPE, true, 0); if (subFileType == 0) { // check that predictor is set to 1 if anything other // than LZW compression is used if (TiffTools.getCompression(ifds[i]) != TiffTools.LZW) { ifds[i].put(new Integer(TiffTools.PREDICTOR), new Integer(1)); } newIFDs.add(ifds[i]); } } // reset numImages and ifds ifds = (Hashtable[]) newIFDs.toArray(new Hashtable[0]); thumbnailsRemoved = true; initMetadata(); core[0].littleEndian = !isLittleEndian(); } // -- Helper methods -- /** Parses overlay-related fields. */ protected void parseOverlays(long data, String suffix) throws IOException { if (data == 0) return; in.seek(data); int nde = in.readInt(); put("NumberDrawingElements-" + suffix, nde); int size = in.readInt(); int idata = in.readInt(); put("LineWidth-" + suffix, idata); idata = in.readInt(); put("Measure-" + suffix, idata); in.skipBytes(8); put("ColorRed-" + suffix, in.read()); put("ColorGreen-" + suffix, in.read()); put("ColorBlue-" + suffix, in.read()); in.skipBytes(1); put("Valid-" + suffix, in.readInt()); put("KnotWidth-" + suffix, in.readInt()); put("CatchArea-" + suffix, in.readInt()); // some fields describing the font put("FontHeight-" + suffix, in.readInt()); put("FontWidth-" + suffix, in.readInt()); put("FontEscapement-" + suffix, in.readInt()); put("FontOrientation-" + suffix, in.readInt()); put("FontWeight-" + suffix, in.readInt()); put("FontItalic-" + suffix, in.readInt()); put("FontUnderline-" + suffix, in.readInt()); put("FontStrikeOut-" + suffix, in.readInt()); put("FontCharSet-" + suffix, in.readInt()); put("FontOutPrecision-" + suffix, in.readInt()); put("FontClipPrecision-" + suffix, in.readInt()); put("FontQuality-" + suffix, in.readInt()); put("FontPitchAndFamily-" + suffix, in.readInt()); put("FontFaceName-" + suffix, in.readString(64)); // some flags for measuring values of different drawing element types put("ClosedPolyline-" + suffix, in.read()); put("OpenPolyline-" + suffix, in.read()); put("ClosedBezierCurve-" + suffix, in.read()); put("OpenBezierCurve-" + suffix, in.read()); put("ArrowWithClosedTip-" + suffix, in.read()); put("ArrowWithOpenTip-" + suffix, in.read()); put("Ellipse-" + suffix, in.read()); put("Circle-" + suffix, in.read()); put("Rectangle-" + suffix, in.read()); put("Line-" + suffix, in.read()); /* try { int drawingEl = (size - 194) / nde; if (drawingEl <= 0) return; if (DataTools.swap(nde) < nde) nde = DataTools.swap(nde); for (int i=0; i<nde; i++) { put("DrawingElement" + i + "-" + suffix, in.readString(drawingEl)); } } catch (ArithmeticException exc) { if (debug) trace(exc); } */ } /** Construct a metadata key from the given stack. */ private String getKey(Stack stack, int entry) { StringBuffer sb = new StringBuffer(); for (int i=0; i<stack.size(); i++) { sb.append((String) stack.get(i)); sb.append("/"); } sb.append(" - "); sb.append(metadataKeys.get(new Integer(entry))); return sb.toString(); } private static Hashtable createKeys() { Hashtable h = new Hashtable(); h.put(new Integer(0x10000001), "Name"); h.put(new Integer(0x4000000c), "Name"); h.put(new Integer(0x50000001), "Name"); h.put(new Integer(0x90000001), "Name"); h.put(new Integer(0x90000005), "Name"); h.put(new Integer(0xb0000003), "Name"); h.put(new Integer(0xd0000001), "Name"); h.put(new Integer(0x12000001), "Name"); h.put(new Integer(0x14000001), "Name"); h.put(new Integer(0x10000002), "Description"); h.put(new Integer(0x14000002), "Description"); h.put(new Integer(0x10000003), "Notes"); h.put(new Integer(0x10000004), "Objective"); h.put(new Integer(0x10000005), "Processing Summary"); h.put(new Integer(0x10000006), "Special Scan Mode"); h.put(new Integer(0x10000007), "Scan Type"); h.put(new Integer(0x10000008), "Scan Mode"); h.put(new Integer(0x10000009), "Number of Stacks"); h.put(new Integer(0x1000000a), "Lines Per Plane"); h.put(new Integer(0x1000000b), "Samples Per Line"); h.put(new Integer(0x1000000c), "Planes Per Volume"); h.put(new Integer(0x1000000d), "Images Width"); h.put(new Integer(0x1000000e), "Images Height"); h.put(new Integer(0x1000000f), "Number of Planes"); h.put(new Integer(0x10000010), "Number of Stacks"); h.put(new Integer(0x10000011), "Number of Channels"); h.put(new Integer(0x10000012), "Linescan XY Size"); h.put(new Integer(0x10000013), "Scan Direction"); h.put(new Integer(0x10000014), "Time Series"); h.put(new Integer(0x10000015), "Original Scan Data"); h.put(new Integer(0x10000016), "Zoom X"); h.put(new Integer(0x10000017), "Zoom Y"); h.put(new Integer(0x10000018), "Zoom Z"); h.put(new Integer(0x10000019), "Sample 0X"); h.put(new Integer(0x1000001a), "Sample 0Y"); h.put(new Integer(0x1000001b), "Sample 0Z"); h.put(new Integer(0x1000001c), "Sample Spacing"); h.put(new Integer(0x1000001d), "Line Spacing"); h.put(new Integer(0x1000001e), "Plane Spacing"); h.put(new Integer(0x1000001f), "Plane Width"); h.put(new Integer(0x10000020), "Plane Height"); h.put(new Integer(0x10000021), "Volume Depth"); h.put(new Integer(0x10000034), "Rotation"); h.put(new Integer(0x10000035), "Precession"); h.put(new Integer(0x10000036), "Sample 0Time"); h.put(new Integer(0x10000037), "Start Scan Trigger In"); h.put(new Integer(0x10000038), "Start Scan Trigger Out"); h.put(new Integer(0x10000039), "Start Scan Event"); h.put(new Integer(0x10000040), "Start Scan Time"); h.put(new Integer(0x10000041), "Stop Scan Trigger In"); h.put(new Integer(0x10000042), "Stop Scan Trigger Out"); h.put(new Integer(0x10000043), "Stop Scan Event"); h.put(new Integer(0x10000044), "Stop Scan Time"); h.put(new Integer(0x10000045), "Use ROIs"); h.put(new Integer(0x10000046), "Use Reduced Memory ROIs"); h.put(new Integer(0x10000047), "User"); h.put(new Integer(0x10000048), "Use B/C Correction"); h.put(new Integer(0x10000049), "Position B/C Contrast 1"); h.put(new Integer(0x10000050), "Position B/C Contrast 2"); h.put(new Integer(0x10000051), "Interpolation Y"); h.put(new Integer(0x10000052), "Camera Binning"); h.put(new Integer(0x10000053), "Camera Supersampling"); h.put(new Integer(0x10000054), "Camera Frame Width"); h.put(new Integer(0x10000055), "Camera Frame Height"); h.put(new Integer(0x10000056), "Camera Offset X"); h.put(new Integer(0x10000057), "Camera Offset Y"); h.put(new Integer(0x40000001), "Multiplex Type"); h.put(new Integer(0x40000002), "Multiplex Order"); h.put(new Integer(0x40000003), "Sampling Mode"); h.put(new Integer(0x40000004), "Sampling Method"); h.put(new Integer(0x40000005), "Sampling Number"); h.put(new Integer(0x40000006), "Acquire"); h.put(new Integer(0x50000002), "Acquire"); h.put(new Integer(0x7000000b), "Acquire"); h.put(new Integer(0x90000004), "Acquire"); h.put(new Integer(0xd0000017), "Acquire"); h.put(new Integer(0x40000007), "Sample Observation Time"); h.put(new Integer(0x40000008), "Time Between Stacks"); h.put(new Integer(0x4000000d), "Collimator 1 Name"); h.put(new Integer(0x4000000e), "Collimator 1 Position"); h.put(new Integer(0x4000000f), "Collimator 2 Name"); h.put(new Integer(0x40000010), "Collimator 2 Position"); h.put(new Integer(0x40000011), "Is Bleach Track"); h.put(new Integer(0x40000012), "Bleach After Scan Number"); h.put(new Integer(0x40000013), "Bleach Scan Number"); h.put(new Integer(0x40000014), "Trigger In"); h.put(new Integer(0x12000004), "Trigger In"); h.put(new Integer(0x14000003), "Trigger In"); h.put(new Integer(0x40000015), "Trigger Out"); h.put(new Integer(0x12000005), "Trigger Out"); h.put(new Integer(0x14000004), "Trigger Out"); h.put(new Integer(0x40000016), "Is Ratio Track"); h.put(new Integer(0x40000017), "Bleach Count"); h.put(new Integer(0x40000018), "SPI Center Wavelength"); h.put(new Integer(0x40000019), "Pixel Time"); h.put(new Integer(0x40000020), "ID Condensor Frontlens"); h.put(new Integer(0x40000021), "Condensor Frontlens"); h.put(new Integer(0x40000022), "ID Field Stop"); h.put(new Integer(0x40000023), "Field Stop Value"); h.put(new Integer(0x40000024), "ID Condensor Aperture"); h.put(new Integer(0x40000025), "Condensor Aperture"); h.put(new Integer(0x40000026), "ID Condensor Revolver"); h.put(new Integer(0x40000027), "Condensor Revolver"); h.put(new Integer(0x40000028), "ID Transmission Filter 1"); h.put(new Integer(0x40000029), "ID Transmission 1"); h.put(new Integer(0x40000030), "ID Transmission Filter 2"); h.put(new Integer(0x40000031), "ID Transmission 2"); h.put(new Integer(0x40000032), "Repeat Bleach"); h.put(new Integer(0x40000033), "Enable Spot Bleach Pos"); h.put(new Integer(0x40000034), "Spot Bleach Position X"); h.put(new Integer(0x40000035), "Spot Bleach Position Y"); h.put(new Integer(0x40000036), "Bleach Position Z"); h.put(new Integer(0x50000003), "Power"); h.put(new Integer(0x90000002), "Power"); h.put(new Integer(0x70000003), "Detector Gain"); h.put(new Integer(0x70000005), "Amplifier Gain"); h.put(new Integer(0x70000007), "Amplifier Offset"); h.put(new Integer(0x70000009), "Pinhole Diameter"); h.put(new Integer(0x7000000c), "Detector Name"); h.put(new Integer(0x7000000d), "Amplifier Name"); h.put(new Integer(0x7000000e), "Pinhole Name"); h.put(new Integer(0x7000000f), "Filter Set Name"); h.put(new Integer(0x70000010), "Filter Name"); h.put(new Integer(0x70000013), "Integrator Name"); h.put(new Integer(0x70000014), "Detection Channel Name"); h.put(new Integer(0x70000015), "Detector Gain B/C 1"); h.put(new Integer(0x70000016), "Detector Gain B/C 2"); h.put(new Integer(0x70000017), "Amplifier Gain B/C 1"); h.put(new Integer(0x70000018), "Amplifier Gain B/C 2"); h.put(new Integer(0x70000019), "Amplifier Offset B/C 1"); h.put(new Integer(0x70000020), "Amplifier Offset B/C 2"); h.put(new Integer(0x70000021), "Spectral Scan Channels"); h.put(new Integer(0x70000022), "SPI Wavelength Start"); h.put(new Integer(0x70000023), "SPI Wavelength End"); h.put(new Integer(0x70000026), "Dye Name"); h.put(new Integer(0xd0000014), "Dye Name"); h.put(new Integer(0x70000027), "Dye Folder"); h.put(new Integer(0xd0000015), "Dye Folder"); h.put(new Integer(0x90000003), "Wavelength"); h.put(new Integer(0x90000006), "Power B/C 1"); h.put(new Integer(0x90000007), "Power B/C 2"); h.put(new Integer(0xb0000001), "Filter Set"); h.put(new Integer(0xb0000002), "Filter"); h.put(new Integer(0xd0000004), "Color"); h.put(new Integer(0xd0000005), "Sample Type"); h.put(new Integer(0xd0000006), "Bits Per Sample"); h.put(new Integer(0xd0000007), "Ratio Type"); h.put(new Integer(0xd0000008), "Ratio Track 1"); h.put(new Integer(0xd0000009), "Ratio Track 2"); h.put(new Integer(0xd000000a), "Ratio Channel 1"); h.put(new Integer(0xd000000b), "Ratio Channel 2"); h.put(new Integer(0xd000000c), "Ratio Const. 1"); h.put(new Integer(0xd000000d), "Ratio Const. 2"); h.put(new Integer(0xd000000e), "Ratio Const. 3"); h.put(new Integer(0xd000000f), "Ratio Const. 4"); h.put(new Integer(0xd0000010), "Ratio Const. 5"); h.put(new Integer(0xd0000011), "Ratio Const. 6"); h.put(new Integer(0xd0000012), "Ratio First Images 1"); h.put(new Integer(0xd0000013), "Ratio First Images 2"); h.put(new Integer(0xd0000016), "Spectrum"); h.put(new Integer(0x12000003), "Interval"); return h; } }
package loci.formats.in; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.ArrayList; import java.util.Comparator; import java.util.Vector; import loci.common.DataTools; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.common.services.DependencyException; import loci.common.services.ServiceFactory; import loci.formats.FormatException; import loci.formats.FormatTools; import loci.formats.codec.CodecOptions; import loci.formats.codec.JPEGCodec; import loci.formats.codec.ZlibCodec; import loci.formats.meta.DummyMetadata; import loci.formats.meta.MetadataStore; import loci.formats.services.POIService; public class ZeissZVIReader extends BaseZeissReader { // -- Constants -- public static final int ZVI_MAGIC_BYTES = 0xd0cf11e0; private static final long ROI_SIGNATURE = 0x21fff6977547000dL; // -- Fields -- protected POIService poi; protected String[] files; // -- Constructor -- /** Constructs a new ZeissZVI reader. */ public ZeissZVIReader() { super("Zeiss Vision Image (ZVI)", "zvi"); domains = new String[] {FormatTools.LM_DOMAIN}; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { final int blockLen = 65536; if (!FormatTools.validStream(stream, blockLen, false)) return false; int magic = stream.readInt(); if (magic != ZVI_MAGIC_BYTES) return false; return true; } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); lastPlane = no; int bytes = FormatTools.getBytesPerPixel(getPixelType()); int pixel = bytes * getRGBChannelCount(); CodecOptions options = new CodecOptions(); options.littleEndian = isLittleEndian(); options.interleaved = isInterleaved(); int index = 0; int[] coords = getZCTCoords(no); int seriesCount = -1; for (int q=0; q<coordinates.length; q++) { if (coordinates[q][0] == coords[0] && coordinates[q][1] == coords[1] && coordinates[q][2] == coords[2]) { index = q; seriesCount++; if (seriesCount == getSeries()) { break; } } } if (index >= imageFiles.length) { return buf; } RandomAccessInputStream s = poi.getDocumentStream(imageFiles[index]); s.seek(offsets[index]); int len = w * pixel; int row = getSizeX() * pixel; if (isJPEG) { byte[] t = new JPEGCodec().decompress(s, options); for (int yy=0; yy<h; yy++) { System.arraycopy(t, (yy + y) * row + x * pixel, buf, yy*len, len); } } else if (isZlib) { byte[] t = new ZlibCodec().decompress(s, options); for (int yy=0; yy<h; yy++) { int src = (yy + y) * row + x * pixel; int dest = yy * len; if (src + len <= t.length && dest + len <= buf.length) { System.arraycopy(t, src, buf, dest, len); } else break; } } else { readPlane(s, x, y, w, h, buf); } s.close(); if (isRGB() && !isJPEG) { // reverse bytes in groups of 3 to account for BGR storage byte[] bb = new byte[bytes]; for (int i=0; i<buf.length; i+=bpp) { System.arraycopy(buf, i + 2*bytes, bb, 0, bytes); System.arraycopy(buf, i, buf, i + 2*bytes, bytes); System.arraycopy(bb, 0, buf, i, bytes); } } return buf; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (poi != null) poi.close(); poi = null; files = null; } // -- Internal FormatReader API methods -- protected void initFile(String id) throws FormatException, IOException { super.initFile(id); super.initFileMain(id); } protected void initVars(String id) throws FormatException, IOException { super.initVars(id); try { ServiceFactory factory = new ServiceFactory(); poi = factory.getInstance(POIService.class); } catch (DependencyException de) { throw new FormatException("POI library not found", de); } poi.initialize(Location.getMappedId(id)); countImages(); } /* @see loci.formats.FormatReader#initFile(String) */ protected void fillMetadataPass1(MetadataStore store) throws FormatException, IOException { super.fillMetadataPass1(store); // parse each embedded file for (String name : files) { String relPath = name.substring(name.lastIndexOf(File.separator) + 1); if (!relPath.toUpperCase().equals("CONTENTS")) continue; String dirName = name.substring(0, name.lastIndexOf(File.separator)); if (dirName.indexOf(File.separator) != -1) { dirName = dirName.substring(dirName.lastIndexOf(File.separator) + 1); } if (name.indexOf("Scaling") == -1 && dirName.equals("Tags")) { int imageNum = getImageNumber(name, -1); if (imageNum == -1) { parseTags(imageNum, name, new DummyMetadata()); } else tagsToParse.add(name); } else if (dirName.equals("Shapes") && name.indexOf("Item") != -1) { int imageNum = getImageNumber(name, -1); if (imageNum != -1) { try { parseROIs(imageNum, name, store); } catch (IOException e) { LOGGER.debug("Could not parse all ROIs.", e); } } } else if (dirName.equals("Image") || dirName.toUpperCase().indexOf("ITEM") != -1) { int imageNum = getImageNumber(dirName, getImageCount() == 1 ? 0 : -1); if (imageNum == -1) continue; // found a valid image stream RandomAccessInputStream s = poi.getDocumentStream(name); s.order(true); if (s.length() <= 1024) { s.close(); continue; } for (int q=0; q<11; q++) { getNextTag(s); } s.skipBytes(2); int len = s.readInt() - 20; s.skipBytes(8); int zidx = s.readInt(); int cidx = s.readInt(); int tidx = s.readInt(); zIndices.add(zidx); timepointIndices.add(tidx); channelIndices.add(cidx); s.skipBytes(len); for (int q=0; q<5; q++) { getNextTag(s); } s.skipBytes(4); //if (getSizeX() == 0) { core.get(0).sizeX = s.readInt(); core.get(0).sizeY = s.readInt(); //else s.skipBytes(8); s.skipBytes(4); if (bpp == 0) { bpp = s.readInt(); } else s.skipBytes(4); s.skipBytes(4); int valid = s.readInt(); String check = s.readString(4).trim(); isZlib = (valid == 0 || valid == 1) && check.equals("WZL"); isJPEG = (valid == 0 || valid == 1) && !isZlib; // save the offset to the pixel data offsets[imageNum] = (int) s.getFilePointer() - 4; if (isZlib) offsets[imageNum] += 8; coordinates[imageNum][0] = zidx; coordinates[imageNum][1] = cidx; coordinates[imageNum][2] = tidx; imageFiles[imageNum] = name; s.close(); } } } protected void fillMetadataPass3(MetadataStore store) throws FormatException, IOException { super.fillMetadataPass3(store); // calculate tile dimensions and number of tiles if (core.size() > 1) { Integer[] t = tiles.keySet().toArray(new Integer[tiles.size()]); Arrays.sort(t); Vector<Integer> tmpOffsets = new Vector<Integer>(); Vector<String> tmpFiles = new Vector<String>(); int index = 0; for (Integer key : t) { int nTiles = tiles.get(key).intValue(); if (nTiles < getImageCount()) { tiles.remove(key); } else { for (int p=0; p<nTiles; p++) { tmpOffsets.add(new Integer(offsets[index + p])); tmpFiles.add(imageFiles[index + p]); } } index += nTiles; } offsets = new int[tmpOffsets.size()]; for (int i=0; i<offsets.length; i++) { offsets[i] = tmpOffsets.get(i).intValue(); } imageFiles = tmpFiles.toArray(new String[tmpFiles.size()]); } } protected void fillMetadataPass5(MetadataStore store) throws FormatException, IOException { super.fillMetadataPass5(store); for (String name : tagsToParse) { int imageNum = getImageNumber(name, -1); parseTags(imageNum, name, store); } } protected void countImages() { // count number of images files = (String[]) poi.getDocumentList().toArray(new String[0]); Arrays.sort(files, new Comparator() { public int compare(Object o1, Object o2) { int n1 = getImageNumber((String) o1, -1); int n2 = getImageNumber((String) o2, -1); return new Integer(n1).compareTo(new Integer(n2)); } }); core.get(0).imageCount = 0; for (String file : files) { String uname = file.toUpperCase(); uname = uname.substring(uname.indexOf(File.separator) + 1); if (uname.endsWith("CONTENTS") && (uname.startsWith("IMAGE") || uname.indexOf("ITEM") != -1) && poi.getFileSize(file) > 1024) { int imageNumber = getImageNumber(file, 0); if (imageNumber >= getImageCount()) { core.get(0).imageCount++; } } } super.countImages(); } private int getImageNumber(String dirName, int defaultNumber) { if (dirName.toUpperCase().indexOf("ITEM") != -1) { int open = dirName.indexOf("("); int close = dirName.indexOf(")"); if (open < 0 || close < 0 || close < open) return defaultNumber; return Integer.parseInt(dirName.substring(open + 1, close)); } return defaultNumber; } private String getNextTag(RandomAccessInputStream s) throws IOException { int type = s.readShort(); switch (type) { case 0: case 1: return ""; case 2: return String.valueOf(s.readShort()); case 3: case 22: case 23: return String.valueOf(s.readInt()); case 4: return String.valueOf(s.readFloat()); case 5: return String.valueOf(s.readDouble()); case 7: case 20: case 21: return String.valueOf(s.readLong()); case 8: case 69: int len = s.readInt(); return s.readString(len); case 9: case 13: s.skipBytes(16); return ""; case 63: case 65: len = s.readInt(); s.skipBytes(len); return ""; case 66: len = s.readShort(); return s.readString(len); default: long old = s.getFilePointer(); while (s.readShort() != 3 && s.getFilePointer() + 2 < s.length()); long fp = s.getFilePointer() - 2; s.seek(old - 2); return s.readString((int) (fp - old + 2)); } } /** Parse all of the tags in a stream. */ private void parseTags(int image, String file, MetadataStore store) throws FormatException, IOException { ArrayList<Tag> tags = new ArrayList<Tag>(); RandomAccessInputStream s = poi.getDocumentStream(file); s.order(true); s.seek(8); int count = s.readInt(); for (int i=0; i<count; i++) { if (s.getFilePointer() + 2 >= s.length()) break; String value = DataTools.stripString(getNextTag(s)); s.skipBytes(2); int tagID = s.readInt(); s.skipBytes(6); tags.add(new Tag(tagID, value, Context.MAIN)); } parseMainTags(image, store, tags); s.close(); } /** * Parse ROI data from the given RandomAccessInputStream and store it in the * given MetadataStore. */ private void parseROIs(int imageNum, String name, MetadataStore store) throws IOException { MetadataLevel level = getMetadataOptions().getMetadataLevel(); if (level == MetadataLevel.MINIMUM || level == MetadataLevel.NO_OVERLAYS) { return; } RandomAccessInputStream s = poi.getDocumentStream(name); s.order(true); // scan stream for offsets to each ROI Vector<Long> roiOffsets = new Vector<Long>(); // Bytes 0x0-1 == 0x3 // Bytes 0x2-5 == Layer version (04100010) // Byte 0x10 == Shape count s.seek(16); int roiCount = s.readShort(); int roiFound = 0; // Add new layer for this set of shapes. Layer nlayer = new Layer(); layers.add(nlayer); // Following signature (from sig start): // Bytes 0x12-15 == Shape version (0B200010) // Bytes 0x28-nn == Shape attributes (size is first short) while (roiFound < roiCount && s.getFilePointer() < s.length() - 8) { // find next ROI signature long signature = s.readLong() & 0xffffffffffffffffL; while (signature != ROI_SIGNATURE) { if (s.getFilePointer() >= s.length()) break; s.seek(s.getFilePointer() - 6); signature = s.readLong() & 0xffffffffffffffffL; } if (s.getFilePointer() >= s.length()) { break; } long roiOffset = s.getFilePointer() - 8; roiOffsets.add(new Long(roiOffset)); LOGGER.debug("ROI@" + roiOffset); // Found ROI; now fill out the shape details and add to the // layer. s.seek(roiOffset + 26); int length = s.readInt(); Shape nshape = new Shape(); s.skipBytes(length + 6); long shapeAttrOffset = s.getFilePointer(); int shapeAttrLength = s.readInt(); nshape.type = FeatureType.get(s.readInt()); LOGGER.debug(" ShapeAttrs@" + shapeAttrOffset + " len="+shapeAttrLength); if (shapeAttrLength < 32) // Broken attrs. break; // read the bounding box s.skipBytes(8); nshape.x1 = s.readInt(); nshape.y1 = s.readInt(); nshape.x2 = s.readInt(); nshape.y2 = s.readInt(); nshape.width = nshape.x2 - nshape.x1; nshape.height = nshape.y2 - nshape.y1; LOGGER.debug(" Bounding Box"); if (shapeAttrLength >= 72) { // Basic shape styling s.skipBytes(16); nshape.fillColour = s.readInt(); nshape.textColour = s.readInt(); nshape.drawColour = s.readInt(); nshape.lineWidth = s.readInt(); nshape.drawStyle = DrawStyle.get(s.readInt()); nshape.fillStyle = FillStyle.get(s.readInt()); nshape.strikeout = (s.readInt() != 0); LOGGER.debug(" Shape styles"); } if (shapeAttrLength >= 100) { // Font styles // Windows TrueType font weighting. nshape.fontWeight = s.readInt(); nshape.bold = (nshape.fontWeight >= 600); nshape.fontSize = s.readInt(); nshape.italic = (s.readInt() != 0); nshape.underline = (s.readInt() != 0); nshape.textAlignment = TextAlignment.get(s.readInt()); LOGGER.debug(" Font styles"); } if (shapeAttrLength >= 148) { // Line styles s.skipBytes(36); nshape.lineEndStyle = BaseZeissReader.LineEndStyle.get(s.readInt()); nshape.pointStyle = BaseZeissReader.PointStyle.get(s.readInt()); nshape.lineEndSize = s.readInt(); nshape.lineEndPositions = BaseZeissReader.LineEndPositions.get(s.readInt()); LOGGER.debug(" Line styles"); } if (shapeAttrLength >= 152) { nshape.displayTag = (s.readInt() != 0); LOGGER.debug(" Tag display"); } if (shapeAttrLength >= 152) { nshape.charset = Charset.get(s.readInt()); LOGGER.debug(" Charset"); } // Label (text). nshape.text = parseROIString(s); if (nshape.text == null) break; LOGGER.debug(" Text=" + nshape.text); // Tag ID if (s.getFilePointer() + 8 > s.length()) break; s.skipBytes(6); nshape.tagID = new Tag(s.readInt(), BaseZeissReader.Context.MAIN); LOGGER.debug(" TagID=" + nshape.tagID); // Font name nshape.fontName = parseROIString(s); if (nshape.fontName == null) break; LOGGER.debug(" Font name=" + nshape.fontName); // Label (name). nshape.name = parseROIString(s); if (nshape.name == null) break; LOGGER.debug(" Name=" + nshape.name); // Handle size and point count. if (s.getFilePointer() + 20 > s.length()) break; s.skipBytes(4); nshape.handleSize = s.readInt(); s.skipBytes(2); nshape.pointCount = s.readInt(); s.skipBytes(6); LOGGER.debug(" Handle size=" + nshape.handleSize); LOGGER.debug(" Point count=" + nshape.pointCount); if (s.getFilePointer() + (8*2*nshape.pointCount) > s.length()) break; nshape.points = new double[nshape.pointCount*2]; for (int p=0; p<nshape.pointCount; p++) { nshape.points[(p*2)] = s.readDouble(); nshape.points[(p*2)+1] = s.readDouble(); } nlayer.shapes.add(nshape); ++roiFound; } if (roiCount != roiFound) { LOGGER.warn("Found " + roiFound + " ROIs, but " + roiCount + " ROIs expected"); } s.close(); } protected String parseROIString(RandomAccessInputStream s) throws IOException { // String is 0x0008 followed by int length for string+NUL. while (s.getFilePointer() < s.length() - 4 && s.readShort() != 8); if (s.getFilePointer() >= s.length() - 8) return null; int strlen = s.readInt(); if (strlen + s.getFilePointer() > s.length()) return null; // Strip off NUL. String text = null; if (strlen >= 2) { // Don't read NUL text = s.readString(strlen-2); s.skipBytes(2); } else { s.skipBytes(strlen); } return text; } }
package ro.pub.cs.systems.eim.practicaltest01var06; import android.app.Activity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; public class PracticalTest01Var06MainActivity extends Activity { private EditText topEditText = null, lowEditText = null; private Button details = null, passButton = null, naviButton = null; private PassListener passListener = new PassListener(); private ButtonListener buttonListener = new ButtonListener(); private class ButtonListener implements View.OnClickListener { @Override public void onClick(View arg0) { // TODO Auto-generated method stub switch (arg0.getId()) { case R.id.details: if (details.getText().toString().contains("More details")) { details.setText("Less details"); passButton.setVisibility(View.VISIBLE); lowEditText.setVisibility(View.VISIBLE); } else if (details.getText().toString() .contains("Less details")) { details.setText("More details"); passButton.setVisibility(View.INVISIBLE); lowEditText.setVisibility(View.INVISIBLE); } else break; break; default: break; } } } private class PassListener implements TextWatcher { @Override public void afterTextChanged(Editable arg0) { // TODO Auto-generated method stub } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { // TODO Auto-generated method stub if (arg0.toString().startsWith("http")) { passButton.setText("Pass"); passButton.setBackground(getApplicationContext().getResources().getDrawable( R.color.green)); } else { passButton.setText("Failed"); passButton.setBackground(getApplicationContext().getResources().getDrawable( R.color.green)); } ; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_practical_test01_var06_main); topEditText = (EditText) findViewById(R.id.top_edit_text); lowEditText = (EditText) findViewById(R.id.lower_edit_text); details = (Button) findViewById(R.id.details); passButton = (Button) findViewById(R.id.pass_button); naviButton = (Button) findViewById(R.id.navigate_to_secondary_activity); details.setOnClickListener(buttonListener); passButton.addTextChangedListener(passListener); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.practical_test01_var06_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
package de.naoth.rc.dialogs.multiagentconfiguration.ui; import de.naoth.rc.dialogs.multiagentconfiguration.AgentItem; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.TreeSet; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.regex.Pattern; import java.util.stream.Collectors; import javafx.application.Platform; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.EventHandler; import javafx.event.EventType; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.ButtonType; import javafx.scene.control.CheckBox; import javafx.scene.control.Dialog; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.control.cell.CheckBoxListCell; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyEvent; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.scene.layout.HBox; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import javafx.stage.StageStyle; /** * * @author Philipp Strobel <philippstrobel@posteo.de> */ public class AgentSelectionDialog extends Dialog { private final ObservableList<AgentItem> hostList = FXCollections.observableArrayList(new TreeSet()); private final List<AgentItem> existing = new ArrayList<>(); private final ExecutorService executor = Executors.newCachedThreadPool(); private List<String> hosts; private TextField host; private TextField port; private Button addHost; private CheckBox allAgents; private Pattern ip_pattern = Pattern.compile("\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\."+ "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." + "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\." + "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"); public AgentSelectionDialog(List<String> ips) { setTitle("Agent Selection"); initStyle(StageStyle.UTILITY); getDialogPane().getStylesheets().add(getClass().getResource("style.css").toExternalForm()); this.hosts = ips; initUi(); setResultConverter(dialogButton -> { if (dialogButton == ButtonType.OK) { return hostList.stream().filter(AgentItem::getActive).collect(Collectors.toList()); } return new ArrayList<>(); }); setOnShowing((e) -> { onShowing(); }); } public AgentSelectionDialog() { this(new ArrayList<>()); } private void initUi() { VBox vb = new VBox(); ListView<AgentItem> l = new ListView(hostList); //l.setCellFactory(CheckBoxListCell.forListView((param) -> { return param.activeProperty(); })); l.setCellFactory((ListView<AgentItem> list) -> { // create new cell and bind to agent active property CheckBoxListCell<AgentItem> c = new CheckBoxListCell<>((p) -> { return p.activeProperty(); }); // set mouse listener to cell c.setOnMouseClicked((e) -> { c.getItem().activeProperty().set(!c.getItem().activeProperty().get()); }); return c; }); // enable selection via 'space' key l.setOnKeyReleased((e) -> { if(e.getCode() == KeyCode.SPACE) { AgentItem a = l.getSelectionModel().getSelectedItem(); a.activeProperty().set(!a.activeProperty().get()); } }); vb.getChildren().add(l); host = new TextField(); host.setPromptText("host ip"); host.setOnKeyPressed((e) -> { if(e.getCode() == KeyCode.ENTER) { host.commitValue(); addHost.fire(); e.consume(); // prevent closing dialog, when host textfield has focus } }); Label sep = new Label(" : "); sep.setAlignment(Pos.BOTTOM_CENTER); port = new TextField(); port.setPromptText("port"); port.setPrefColumnCount(5); port.setOnKeyPressed((e) -> { if(e.getCode() == KeyCode.ENTER) { port.commitValue(); addHost.fire(); e.consume(); // prevent closing dialog, when host textfield has focus } }); addHost = new Button("+"); // prevent closing dialog, when host textfield has focus addHost.setOnKeyPressed((e) -> { if(e.getCode() == KeyCode.ENTER) { e.consume(); } }); addHost.setOnAction((e) -> { boolean error = false; String rawHost = host.getText().trim(); String rawPort = port.getText().trim(); int p = 0; // check host ip format is valid if(!ip_pattern.matcher(rawHost).matches()) { host.setStyle("-fx-border-color:red;"); error = true; } // check if port is valid try { p = Integer.parseInt(rawPort); } catch (NumberFormatException ex) { port.setStyle("-fx-border-color:red;"); error = true; } // if there wasn't an error, add host to agent list if(!error) { // reset style host.setStyle(""); port.setStyle(""); addAgent(new AgentItem(rawHost, p)); } }); HBox hb = new HBox(); hb.setAlignment(Pos.CENTER); hb.getChildren().addAll(host, sep, port, addHost); vb.getChildren().add(hb); BorderPane bp = new BorderPane(); bp.setPadding(new Insets(10, 0, 0, 0)); allAgents = new CheckBox("All Agents"); allAgents.setSelected(true); GridPane.setVgrow(allAgents, Priority.ALWAYS); allAgents.setOnAction((e) -> { hostList.stream().forEach((a) -> { a.activeProperty().set(allAgents.isSelected()); }); }); bp.setLeft(allAgents); Button refresh = new Button(); refresh.setTooltip(new Tooltip("Refresh agents list")); refresh.getStyleClass().add("refresh_button"); // TODO: doesn't work ?! refresh.setOnAction((e) -> { pingAgents(); }); bp.setRight(refresh); vb.getChildren().add(bp); getDialogPane().setContent(vb); getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL); //((Button)getDialogPane().lookupButton(ButtonType.OK)).setDefaultButton(false); } private void resetTextFields() { host.setText(""); port.setText("5401"); } private void onShowing() { // clear "old" list hostList.clear(); // clear textfields resetTextFields(); // retrieve agents pingAgents(); // set to a fixed size setHeight(500); } public void setHosts(List<String> h) { hosts = h; } private void pingAgents() { // try to find some naos for(final String ip: hosts) { executor.submit(() -> { try { InetAddress address = InetAddress.getByName(ip); if(address.isReachable(500)) { Platform.runLater(() -> { // check if agent is already in the list addAgent(new AgentItem(ip)); }); } } catch (IOException e) { /* ignore exception */ } }); } // try to find some simspark agents for (int p = 5401; p < 5411; p++) { final int port = p; executor.submit(() -> { try { // NOTE: throws an exception, if the port isn't used. (new Socket("localhost", port)).close(); Platform.runLater(() -> { // check if agent is already in the list addAgent(new AgentItem("127.0.0.1", port)); }); } catch (IOException ex) { /* ignore exception */ } }); } } // END pingAgents() private boolean addAgent(AgentItem agent) { if(!hostList.stream().anyMatch((other) -> { return agent.getHost().equals(other.getHost()) && agent.getPort() == other.getPort(); })) { // deactivate agent item, if it already open agent.activeProperty().set(!existing.stream().anyMatch((i) -> { return i.compareTo(agent) == 0; })); hostList.add(agent); return true; } return false; } public void setExisting(List<AgentItem> l) { existing.clear(); existing.addAll(l); } } // END AgentSelectionDialog
package im.actor.core.modules.messaging.router; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import im.actor.core.api.ApiDialogGroup; import im.actor.core.api.ApiDialogShort; import im.actor.core.api.rpc.RequestLoadGroupedDialogs; import im.actor.core.api.rpc.ResponseLoadGroupedDialogs; import im.actor.core.entity.Avatar; import im.actor.core.entity.ContentDescription; import im.actor.core.entity.ConversationState; import im.actor.core.entity.Group; import im.actor.core.entity.Message; import im.actor.core.entity.MessageState; import im.actor.core.entity.Peer; import im.actor.core.entity.PeerType; import im.actor.core.entity.Reaction; import im.actor.core.entity.User; import im.actor.core.entity.content.AbsContent; import im.actor.core.entity.content.TextContent; import im.actor.core.modules.AbsModule; import im.actor.core.modules.ModuleActor; import im.actor.core.modules.ModuleContext; import im.actor.core.modules.messaging.actions.CursorReaderActor; import im.actor.core.modules.messaging.actions.CursorReceiverActor; import im.actor.core.modules.messaging.dialogs.DialogsActor; import im.actor.core.modules.messaging.history.entity.DialogHistory; import im.actor.core.modules.messaging.router.entity.ActiveDialogGroup; import im.actor.core.modules.messaging.router.entity.ActiveDialogStorage; import im.actor.core.modules.messaging.router.entity.RouterActiveDialogsChanged; import im.actor.core.modules.messaging.router.entity.RouterAppHidden; import im.actor.core.modules.messaging.router.entity.RouterAppVisible; import im.actor.core.modules.messaging.router.entity.RouterApplyChatHistory; import im.actor.core.modules.messaging.router.entity.RouterApplyDialogsHistory; import im.actor.core.modules.messaging.router.entity.RouterChangedContent; import im.actor.core.modules.messaging.router.entity.RouterChangedReactions; import im.actor.core.modules.messaging.router.entity.RouterChatClear; import im.actor.core.modules.messaging.router.entity.RouterChatDelete; import im.actor.core.modules.messaging.router.entity.RouterConversationHidden; import im.actor.core.modules.messaging.router.entity.RouterConversationVisible; import im.actor.core.modules.messaging.router.entity.RouterDeletedMessages; import im.actor.core.modules.messaging.router.entity.RouterDifferenceEnd; import im.actor.core.modules.messaging.router.entity.RouterDifferenceStart; import im.actor.core.modules.messaging.router.entity.RouterMessageOnlyActive; import im.actor.core.modules.messaging.router.entity.RouterMessageRead; import im.actor.core.modules.messaging.router.entity.RouterMessageReadByMe; import im.actor.core.modules.messaging.router.entity.RouterMessageReceived; import im.actor.core.modules.messaging.router.entity.RouterNewMessages; import im.actor.core.modules.messaging.router.entity.RouterOutgoingError; import im.actor.core.modules.messaging.router.entity.RouterOutgoingMessage; import im.actor.core.modules.messaging.router.entity.RouterOutgoingSent; import im.actor.core.modules.messaging.router.entity.RouterPeersChanged; import im.actor.core.util.JavaUtil; import im.actor.core.viewmodel.DialogGroup; import im.actor.core.viewmodel.DialogSmall; import im.actor.core.viewmodel.generics.ArrayListDialogSmall; import im.actor.runtime.actors.messages.Void; import im.actor.runtime.function.Consumer; import im.actor.runtime.storage.KeyValueEngine; import im.actor.runtime.storage.ListEngine; import static im.actor.core.entity.EntityConverter.convert; import static im.actor.core.util.AssertUtils.assertTrue; public class RouterActor extends ModuleActor { private static final String TAG = "RouterActor"; // Visibility private final HashSet<Peer> visiblePeers = new HashSet<>(); private boolean isAppVisible = false; // Storage private KeyValueEngine<ConversationState> conversationStates; // Active Dialogs private ActiveDialogStorage activeDialogStorage; public RouterActor(ModuleContext context) { super(context); } @Override public void preStart() { super.preStart(); conversationStates = context().getMessagesModule().getConversationStates().getEngine(); // Loading Active Dialogs activeDialogStorage = new ActiveDialogStorage(); byte[] data = context().getStorageModule().getBlobStorage().loadItem(AbsModule.BLOB_DIALOGS_ACTIVE); if (data != null) { try { activeDialogStorage = new ActiveDialogStorage(data); } catch (IOException e) { e.printStackTrace(); } } if (!activeDialogStorage.isLoaded()) { api(new RequestLoadGroupedDialogs()).then(new Consumer<ResponseLoadGroupedDialogs>() { @Override public void apply(final ResponseLoadGroupedDialogs responseLoadGroupedDialogs) { updates().applyRelatedData(responseLoadGroupedDialogs.getUsers(), responseLoadGroupedDialogs.getGroups()).then(new Consumer<Void>() { @Override public void apply(Void aVoid) { boolean showArchived = false; boolean showInvite = false; if (responseLoadGroupedDialogs.showArchived() != null) { showArchived = responseLoadGroupedDialogs.showArchived(); } if (responseLoadGroupedDialogs.showInvite() != null) { showInvite = responseLoadGroupedDialogs.showInvite(); } onActiveDialogsChanged(responseLoadGroupedDialogs.getDialogs(), showArchived, showInvite); } }).done(self()); } }).done(self()); } else { notifyActiveDialogsVM(); } } // Active Dialogs private void onActiveDialogsChanged(List<ApiDialogGroup> dialogs, boolean showArchived, boolean showInvite) { // Updating Counters ArrayList<ConversationState> convStates = new ArrayList<>(); for (ApiDialogGroup g : dialogs) { for (ApiDialogShort s : g.getDialogs()) { Peer peer = convert(s.getPeer()); ConversationState state = conversationStates.getValue(peer.getUnuqueId()); boolean isChanged = false; if (state.getUnreadCount() != s.getCounter() && !isConversationVisible(peer)) { state = state.changeCounter(s.getCounter()); isChanged = true; } if (state.getInMaxMessageDate() < s.getDate()) { state = state.changeInMaxDate(s.getDate()); isChanged = true; } if (isChanged) { convStates.add(state); } } } conversationStates.addOrUpdateItems(convStates); // Updating storage activeDialogStorage.setHaveArchived(showArchived); activeDialogStorage.setShowInvite(showInvite); activeDialogStorage.setLoaded(true); activeDialogStorage.getGroups().clear(); for (ApiDialogGroup g : dialogs) { ArrayList<Peer> peers = new ArrayList<>(); for (ApiDialogShort s : g.getDialogs()) { Peer peer = convert(s.getPeer()); peers.add(peer); } activeDialogStorage.getGroups().add(new ActiveDialogGroup(g.getKey(), g.getTitle(), peers)); } context().getStorageModule().getBlobStorage() .addOrUpdateItem(AbsModule.BLOB_DIALOGS_ACTIVE, activeDialogStorage.toByteArray()); // Notify VM notifyActiveDialogsVM(); // Unstash all messages after initial loading unstashAll(); } // Incoming Messages private void onNewMessages(Peer peer, List<Message> messages) { assertTrue(messages.size() != 0); boolean isConversationVisible = isConversationVisible(peer); // Collecting Information ConversationState state = conversationStates.getValue(peer.getUnuqueId()); Message topMessage = null; int unreadCount = 0; long maxInDate = 0; for (Message m : messages) { if (topMessage == null || topMessage.getSortDate() < m.getSortDate()) { topMessage = m; } if (m.getSenderId() != myUid()) { if (m.getSortDate() > state.getInReadDate()) { unreadCount++; } maxInDate = Math.max(maxInDate, m.getSortDate()); } } // Writing to Conversation conversation(peer).addOrUpdateItems(messages); // Updating Counter boolean isRead = false; if (unreadCount != 0) { if (isConversationVisible) { // Auto Reading message if (maxInDate > 0) { state = state .changeInReadDate(maxInDate) .changeInMaxDate(maxInDate) .changeCounter(0); context().getMessagesModule().getPlainReadActor() .send(new CursorReaderActor.MarkRead(peer, maxInDate)); context().getNotificationsModule().onOwnRead(peer, maxInDate); isRead = true; conversationStates.addOrUpdateItem(state); } } else { // Updating counter state = state.changeCounter(state.getUnreadCount() + unreadCount); if (maxInDate > 0) { state = state .changeInMaxDate(maxInDate); } conversationStates.addOrUpdateItem(state); notifyActiveDialogsVM(); } } // Marking As Received if (maxInDate > 0 && !isRead) { context().getMessagesModule().getPlainReceiverActor() .send(new CursorReceiverActor.MarkReceived(peer, maxInDate)); } // Updating Dialog List dialogsActor(new DialogsActor.InMessage(peer, topMessage, state.getUnreadCount())); // Playing notifications if (!isConversationVisible) { for (Message m : messages) { if (m.getSenderId() != myUid()) { boolean hasCurrentMention = false; if (m.getContent() instanceof TextContent) { if (((TextContent) m.getContent()).getMentions().contains(myUid())) { hasCurrentMention = true; } } context().getNotificationsModule().onInMessage( peer, m.getSenderId(), m.getSortDate(), ContentDescription.fromContent(m.getContent()), hasCurrentMention); } } } } // Outgoing Messages private void onOutgoingMessage(Peer peer, Message message) { conversation(peer).addOrUpdateItem(message); } private void onOutgoingSent(Peer peer, long rid, long date) { Message msg = conversation(peer).getValue(rid); // If we have pending message if (msg != null && (msg.getMessageState() == MessageState.PENDING)) { // Updating message Message updatedMsg = msg .changeAllDate(date) .changeState(MessageState.SENT); conversation(peer).addOrUpdateItem(updatedMsg); // Notify dialogs dialogsActor(new DialogsActor.InMessage(peer, updatedMsg, -1)); } } private void onOutgoingError(Peer peer, long rid) { Message msg = conversation(peer).getValue(rid); // If we have pending message if (msg != null && (msg.getMessageState() == MessageState.PENDING)) { // Updating message Message updatedMsg = msg .changeState(MessageState.ERROR); conversation(peer).addOrUpdateItem(updatedMsg); } } // History Messages private void onDialogHistoryLoaded(List<DialogHistory> dialogs) { for (DialogHistory d : dialogs) { ConversationState state = conversationStates.getValue(d.getPeer().getUnuqueId()); if (d.getUnreadCount() > 0) { state = state .changeCounter(d.getUnreadCount()) .changeInMaxDate(d.getDate()); } if (d.isRead()) { state = state .changeOutReadDate(d.getDate()) .changeOutReceiveDate(d.getDate()); } else if (d.isReceived()) { state = state .changeOutReceiveDate(d.getDate()); } conversationStates.addOrUpdateItem(state); } dialogsActor(new DialogsActor.HistoryLoaded(dialogs)); } private void onChatHistoryLoaded(Peer peer, List<Message> messages, Long maxReadDate, Long maxReceiveDate, boolean isEnded) { long maxMessageDate = 0; // Processing all new messages ArrayList<Message> updated = new ArrayList<>(); for (Message historyMessage : messages) { // Ignore already present messages if (conversation(peer).getValue(historyMessage.getEngineId()) != null) { continue; } updated.add(historyMessage); if (historyMessage.getSenderId() != myUid()) { maxMessageDate = Math.max(maxMessageDate, historyMessage.getSortDate()); } } // Writing messages conversation(peer).addOrUpdateItems(updated); // Updating conversation state ConversationState state = conversationStates.getValue(peer.getUnuqueId()); boolean isChanged = false; if (state.getInMaxMessageDate() < maxMessageDate) { state = state.changeInMaxDate(maxMessageDate); isChanged = true; } if (maxReadDate != null && maxReadDate != 0 && state.getOutReadDate() < maxMessageDate) { state = state.changeOutReadDate(maxReadDate); isChanged = true; } if (maxReceiveDate != null && maxReceiveDate != 0 && state.getOutReceiveDate() < maxReceiveDate) { state = state.changeOutReceiveDate(maxReceiveDate); isChanged = true; } if (state.isLoaded() != isEnded) { state = state.changeIsLoaded(isEnded); isChanged = true; } if (isChanged) { conversationStates.addOrUpdateItem(state); } } // Message Updating private void onContentUpdate(Peer peer, long rid, AbsContent content) { Message message = conversation(peer).getValue(rid); // Ignore if we already doesn't have this message if (message == null) { return; } conversation(peer).addOrUpdateItem(message.changeContent(content)); } private void onReactionsUpdate(Peer peer, long rid, List<Reaction> reactions) { Message message = conversation(peer).getValue(rid); // Ignore if we already doesn't have this message if (message == null) { return; } conversation(peer).addOrUpdateItem(message.changeReactions(reactions)); } // Message Deletions private void onMessageDeleted(Peer peer, List<Long> rids) { // Delete Messages conversation(peer).removeItems(JavaUtil.unbox(rids)); Message head = conversation(peer).getHeadValue(); dialogsActor(new DialogsActor.MessageDeleted(peer, head)); } private void onChatClear(Peer peer) { conversation(peer).clear(); dialogsActor(new DialogsActor.ChatClear(peer)); } private void onChatDelete(Peer peer) { conversation(peer).clear(); dialogsActor(new DialogsActor.ChatDelete(peer)); } // Read States private void onMessageRead(Peer peer, long date) { ConversationState state = conversationStates.getValue(peer.getUnuqueId()); boolean isChanged = false; if (date > state.getOutReadDate()) { state = state.changeOutReadDate(date); dialogsActor(new DialogsActor.PeerReadChanged(peer, date)); isChanged = true; } if (date > state.getOutReceiveDate()) { state = state.changeOutReceiveDate(date); isChanged = true; } if (isChanged) { conversationStates.addOrUpdateItem(state); } } private void onMessageReceived(Peer peer, long date) { ConversationState state = conversationStates.getValue(peer.getUnuqueId()); if (date > state.getOutReceiveDate()) { dialogsActor(new DialogsActor.PeerReceiveChanged(peer, date)); state = state.changeOutReceiveDate(date); conversationStates.addOrUpdateItem(state); } } private void onMessageReadByMe(Peer peer, long date, int counter) { ConversationState state = conversationStates.getValue(peer.getUnuqueId()); state = state .changeCounter(counter) .changeInReadDate(date); conversationStates.addOrUpdateItem(state); dialogsActor(new DialogsActor.CounterChanged(peer, counter)); notifyActiveDialogsVM(); context().getNotificationsModule().onOwnRead(peer, date); } // Peer Changed private void onPeersChanged(List<User> users, List<Group> groups) { boolean isActiveNeedUpdate = false; for (User u : users) { if (!isActiveNeedUpdate) { for (ActiveDialogGroup g : activeDialogStorage.getGroups()) { if (g.getPeers().contains(u.peer())) { isActiveNeedUpdate = true; break; } } } dialogsActor(new DialogsActor.UserChanged(u)); } for (Group group : groups) { if (!isActiveNeedUpdate) { for (ActiveDialogGroup g : activeDialogStorage.getGroups()) { if (g.getPeers().contains(group.peer())) { isActiveNeedUpdate = true; break; } } } dialogsActor(new DialogsActor.GroupChanged(group)); } if (isActiveNeedUpdate) { notifyActiveDialogsVM(); } } // Auto Messages Read private void onConversationVisible(Peer peer) { visiblePeers.add(peer); markAsReadIfNeeded(peer); } private void onConversationHidden(Peer peer) { visiblePeers.remove(peer); } private void onAppVisible() { isAppVisible = true; for (Peer p : visiblePeers) { markAsReadIfNeeded(p); } } private void onAppHidden() { isAppVisible = false; } private boolean isConversationVisible(Peer peer) { return visiblePeers.contains(peer) && isAppVisible; } private void markAsReadIfNeeded(Peer peer) { if (isConversationVisible(peer)) { ConversationState state = conversationStates.getValue(peer.getUnuqueId()); if (state.getUnreadCount() != 0 || state.getInReadDate() < state.getInMaxMessageDate()) { state = state .changeCounter(0) .changeInReadDate(state.getInMaxMessageDate()); conversationStates.addOrUpdateItem(state); context().getMessagesModule().getPlainReadActor() .send(new CursorReaderActor.MarkRead(peer, state.getInMaxMessageDate())); dialogsActor(new DialogsActor.CounterChanged(peer, 0)); notifyActiveDialogsVM(); } } } // Difference Handling public void onDifferenceStart() { context().getNotificationsModule().pauseNotifications(); } public void onDifferenceEnd() { context().getNotificationsModule().resumeNotifications(); } // Tools private void dialogsActor(Object message) { context().getMessagesModule().getDialogsActor().send(message); } private ListEngine<Message> conversation(Peer peer) { return context().getMessagesModule().getConversationEngine(peer); } private void notifyActiveDialogsVM() { int counter = 0; ArrayList<DialogGroup> groups = new ArrayList<>(); for (ActiveDialogGroup i : activeDialogStorage.getGroups()) { ArrayListDialogSmall dialogSmalls = new ArrayListDialogSmall(); for (Peer p : i.getPeers()) { String title; Avatar avatar; if (p.getPeerType() == PeerType.GROUP) { Group group = getGroup(p.getPeerId()); title = group.getTitle(); avatar = group.getAvatar(); } else if (p.getPeerType() == PeerType.PRIVATE) { User user = getUser(p.getPeerId()); title = user.getName(); avatar = user.getAvatar(); } else { continue; } int unreadCount = conversationStates.getValue(p.getUnuqueId()).getUnreadCount(); counter += unreadCount; dialogSmalls.add(new DialogSmall(p, title, avatar, unreadCount)); } groups.add(new DialogGroup(i.getTitle(), i.getKey(), dialogSmalls)); } context().getMessagesModule().getDialogGroupsVM().getGroupsValueModel().change(groups); context().getAppStateModule().getAppStateVM().onGlobalCounterChanged(counter); } // Messages @Override public void onReceive(Object message) { if (!activeDialogStorage.isLoaded() && message instanceof RouterMessageOnlyActive) { stash(); return; } if (message instanceof RouterConversationVisible) { RouterConversationVisible conversationVisible = (RouterConversationVisible) message; onConversationVisible(conversationVisible.getPeer()); } else if (message instanceof RouterConversationHidden) { RouterConversationHidden conversationHidden = (RouterConversationHidden) message; onConversationHidden(conversationHidden.getPeer()); } else if (message instanceof RouterAppVisible) { onAppVisible(); } else if (message instanceof RouterAppHidden) { onAppHidden(); } else if (message instanceof RouterNewMessages) { RouterNewMessages routerNewMessages = (RouterNewMessages) message; onNewMessages(routerNewMessages.getPeer(), routerNewMessages.getMessages()); } else if (message instanceof RouterOutgoingMessage) { RouterOutgoingMessage routerOutgoingMessage = (RouterOutgoingMessage) message; onOutgoingMessage(routerOutgoingMessage.getPeer(), routerOutgoingMessage.getMessage()); } else if (message instanceof RouterOutgoingSent) { RouterOutgoingSent routerOutgoingSent = (RouterOutgoingSent) message; onOutgoingSent(routerOutgoingSent.getPeer(), routerOutgoingSent.getRid(), routerOutgoingSent.getDate()); } else if (message instanceof RouterOutgoingError) { RouterOutgoingError outgoingError = (RouterOutgoingError) message; onOutgoingError(outgoingError.getPeer(), outgoingError.getRid()); } else if (message instanceof RouterChangedContent) { RouterChangedContent routerChangedContent = (RouterChangedContent) message; onContentUpdate(routerChangedContent.getPeer(), routerChangedContent.getRid(), routerChangedContent.getContent()); } else if (message instanceof RouterChangedReactions) { RouterChangedReactions routerChangedReactions = (RouterChangedReactions) message; onReactionsUpdate(routerChangedReactions.getPeer(), routerChangedReactions.getRid(), routerChangedReactions.getReactions()); } else if (message instanceof RouterDeletedMessages) { RouterDeletedMessages routerDeletedMessages = (RouterDeletedMessages) message; onMessageDeleted(routerDeletedMessages.getPeer(), routerDeletedMessages.getRids()); } else if (message instanceof RouterMessageRead) { RouterMessageRead messageRead = (RouterMessageRead) message; onMessageRead(messageRead.getPeer(), messageRead.getDate()); } else if (message instanceof RouterMessageReadByMe) { RouterMessageReadByMe readByMe = (RouterMessageReadByMe) message; onMessageReadByMe(readByMe.getPeer(), readByMe.getDate(), readByMe.getCounter()); } else if (message instanceof RouterMessageReceived) { RouterMessageReceived messageReceived = (RouterMessageReceived) message; onMessageReceived(messageReceived.getPeer(), messageReceived.getDate()); } else if (message instanceof RouterApplyDialogsHistory) { RouterApplyDialogsHistory dialogsHistory = (RouterApplyDialogsHistory) message; onDialogHistoryLoaded(dialogsHistory.getDialogs()); dialogsHistory.getExecuteAfter().run(); } else if (message instanceof RouterApplyChatHistory) { RouterApplyChatHistory chatHistory = (RouterApplyChatHistory) message; onChatHistoryLoaded(chatHistory.getPeer(), chatHistory.getMessages(), chatHistory.getMaxReadDate(), chatHistory.getMaxReceiveDate(), chatHistory.isEnded()); } else if (message instanceof RouterChatClear) { RouterChatClear routerChatClear = (RouterChatClear) message; onChatClear(routerChatClear.getPeer()); } else if (message instanceof RouterChatDelete) { RouterChatDelete chatDelete = (RouterChatDelete) message; onChatDelete(chatDelete.getPeer()); } else if (message instanceof RouterPeersChanged) { RouterPeersChanged peersChanged = (RouterPeersChanged) message; onPeersChanged(peersChanged.getUsers(), peersChanged.getGroups()); } else if (message instanceof RouterActiveDialogsChanged) { RouterActiveDialogsChanged dialogsChanged = (RouterActiveDialogsChanged) message; onActiveDialogsChanged(dialogsChanged.getGroups(), dialogsChanged.isHasArchived(), dialogsChanged.isShowInvite()); } else if (message instanceof RouterDifferenceStart) { onDifferenceStart(); } else if (message instanceof RouterDifferenceEnd) { onDifferenceEnd(); } else { super.onReceive(message); } } }
package qa.qcri.aidr.manager.repository.impl; import java.io.Serializable; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import org.hibernate.Criteria; import org.hibernate.FetchMode; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import qa.qcri.aidr.manager.persistence.entities.Collection; import qa.qcri.aidr.manager.persistence.entities.CollectionCollaborator; import qa.qcri.aidr.manager.persistence.entities.UserAccount; import qa.qcri.aidr.manager.repository.CollectionCollaboratorRepository; import qa.qcri.aidr.manager.util.CollectionStatus; /** * @author Latika * */ @Repository public class CollectionCollaboratorRepositoryImpl extends GenericRepositoryImpl<CollectionCollaborator, Serializable> implements CollectionCollaboratorRepository { @SuppressWarnings("unchecked") @Override @Transactional public List<UserAccount> getCollaboratorsByCollection(Long collectionId) { Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(CollectionCollaborator.class); criteria.add(Restrictions.eq("collection.id", collectionId)); List<CollectionCollaborator> collections = (List<CollectionCollaborator>) criteria.list(); List<UserAccount> collaborators = new ArrayList<UserAccount>(); if(collections != null) { for(CollectionCollaborator collaborator : collections) { collaborators.add(collaborator.getAccount()); } } return collaborators; } @Override public CollectionCollaborator findByCollaboratorIdAndCollectionId( Long userId, Long collectionId) { Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(CollectionCollaborator.class); criteria.add(Restrictions.eq("collection.id", collectionId)); criteria.add(Restrictions.eq("account.id", userId)); CollectionCollaborator collectionCollaborator = (CollectionCollaborator) criteria.uniqueResult(); return collectionCollaborator; } @Override public void save(CollectionCollaborator collectionCollaborator) { Timestamp now = new Timestamp(System.currentTimeMillis()); collectionCollaborator.setUpdatedAt(now); collectionCollaborator.setCreatedAt(now); super.save(collectionCollaborator); } @SuppressWarnings("unchecked") @Override public List<Collection> getCollectionByCollaborator(Long userId, Integer start, Integer limit, boolean trashed) { Criteria criteria = getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(CollectionCollaborator.class); criteria.createAlias("collection", "col").setFetchMode("col", FetchMode.JOIN); criteria.add(Restrictions.eq("account.id", userId)); if(trashed) { criteria.add(Restrictions.eq("col.status", CollectionStatus.TRASHED)); } else { criteria.add(Restrictions.ne("col.status", CollectionStatus.TRASHED)); } criteria.addOrder(Order.asc("col.status")); criteria.addOrder(Order.desc("col.createdAt")); if(start != null) { criteria.setFirstResult(start); } if(limit != null) { criteria.setMaxResults(limit); } List<CollectionCollaborator> collectionCollaborators = (List<CollectionCollaborator>) criteria.list(); List<Collection> collections = new ArrayList<Collection>(); if(collectionCollaborators != null) { for(CollectionCollaborator collaborator : collectionCollaborators) { collections.add(collaborator.getCollection()); } } return collections; } }
package com.birdbraintechnologies.birdblox.httpservice.RequestHandlers; import android.app.AlertDialog; import android.bluetooth.BluetoothGatt; import android.bluetooth.le.ScanFilter; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Handler; import android.os.ParcelUuid; import android.util.Log; import android.widget.Toast; import com.birdbraintechnologies.birdblox.Bluetooth.BluetoothHelper; import com.birdbraintechnologies.birdblox.Bluetooth.UARTConnection; import com.birdbraintechnologies.birdblox.Bluetooth.UARTSettings; import com.birdbraintechnologies.birdblox.Robots.Hummingbird; import com.birdbraintechnologies.birdblox.Robots.Hummingbit; import com.birdbraintechnologies.birdblox.Robots.Microbit; import com.birdbraintechnologies.birdblox.Robots.Robot; import com.birdbraintechnologies.birdblox.Robots.RobotType; import com.birdbraintechnologies.birdblox.httpservice.HttpService; import com.birdbraintechnologies.birdblox.httpservice.RequestHandler; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.UUID; import fi.iki.elonen.NanoHTTPD; import static com.birdbraintechnologies.birdblox.MainWebView.bbxEncode; import static com.birdbraintechnologies.birdblox.MainWebView.mainWebViewContext; import static com.birdbraintechnologies.birdblox.MainWebView.runJavascript; import static com.birdbraintechnologies.birdblox.Robots.RobotType.robotTypeFromString; import static fi.iki.elonen.NanoHTTPD.MIME_PLAINTEXT; /** * @author AppyFizz (Shreyan Bakshi) * @author Zhendong Yuan (yzd1998111) */ public class RobotRequestHandler implements RequestHandler { private final String TAG = this.getClass().getName(); private static final String FIRMWARE_UPDATE_URL = "http://www.hummingbirdkit.com/learning/installing-birdblox#BurnFirmware"; /* UUIDs for different Hummingbird features */ private static final String DEVICE_UUID = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"; private static final UUID HB_UART_UUID = UUID.fromString("6E400001-B5A3-F393-E0A9-E50E24DCCA9E"); private static final UUID HB_TX_UUID = UUID.fromString("6E400002-B5A3-F393-E0A9-E50E24DCCA9E"); private static final UUID HB_RX_UUID = UUID.fromString("6E400003-B5A3-F393-E0A9-E50E24DCCA9E"); // TODO: Remove this, it is the same across devices private static final UUID RX_CONFIG_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"); public static HashSet<String> hummingbirdsToConnect = new HashSet<>(); public static HashSet<String> hummingbitsToConnect = new HashSet<>(); public static HashSet<String> microbitsToConnect = new HashSet<>(); HttpService service; private static BluetoothHelper btHelper; private static HashMap<String, Thread> threadMap; private static UARTSettings HBUARTSettings; private static HashMap<String, Hummingbird> connectedHummingbirds; private static UARTSettings HBitUARTSettings; private static HashMap<String, Hummingbit> connectedHummingbits; private static UARTSettings MBitUARTSettings; private static HashMap<String, Microbit> connectedMicrobits; private AlertDialog.Builder builder; private AlertDialog robotInfoDialog; public static HashMap<String, BluetoothGatt> deviceGatt; public RobotRequestHandler(HttpService service) { this.service = service; btHelper = service.getBluetoothHelper(); threadMap = new HashMap<>(); connectedHummingbirds = new HashMap<>(); connectedHummingbits = new HashMap<>(); connectedMicrobits = new HashMap<>(); deviceGatt = new HashMap<>(); // Build Hummingbird UART settings HBUARTSettings = (new UARTSettings.Builder()) .setUARTServiceUUID(HB_UART_UUID) .setRxCharacteristicUUID(HB_RX_UUID) .setTxCharacteristicUUID(HB_TX_UUID) .setRxConfigUUID(RX_CONFIG_UUID) .build(); HBitUARTSettings = (new UARTSettings.Builder()) .setUARTServiceUUID(HB_UART_UUID) .setRxCharacteristicUUID(HB_RX_UUID) .setTxCharacteristicUUID(HB_TX_UUID) .setRxConfigUUID(RX_CONFIG_UUID) .build(); MBitUARTSettings = (new UARTSettings.Builder()) .setUARTServiceUUID(HB_UART_UUID) .setRxCharacteristicUUID(HB_RX_UUID) .setTxCharacteristicUUID(HB_TX_UUID) .setRxConfigUUID(RX_CONFIG_UUID) .build(); } @Override public NanoHTTPD.Response handleRequest(NanoHTTPD.IHTTPSession session, List<String> args) { String[] path = args.get(0).split("/"); Map<String, List<String>> m = session.getParameters(); // Generate response body String responseBody = ""; Robot robot; switch (path[0]) { case "startDiscover": responseBody = startScan(); break; case "stopDiscover": responseBody = stopDiscover(); break; case "totalStatus": responseBody = getTotalStatus(robotTypeFromString(m.get("type").get(0))); break; case "connect": responseBody = connectToRobot(robotTypeFromString(m.get("type").get(0)), m.get("id").get(0)); break; case "disconnect": responseBody = disconnectFromRobot(robotTypeFromString(m.get("type").get(0)), m.get("id").get(0)); break; case "out": robot = getRobotFromId(robotTypeFromString(m.get("type").get(0)), m.get("id").get(0)); if (robot == null) { runJavascript("CallbackManager.robot.updateStatus('" + m.get("id").get(0) + "', false);"); return NanoHTTPD.newFixedLengthResponse( NanoHTTPD.Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Robot " + m.get("id").get(0) + " was not found."); } else if (!robot.setOutput(path[1], m)) { runJavascript("CallbackManager.robot.updateStatus('" + m.get("id").get(0) + "', false);"); return NanoHTTPD.newFixedLengthResponse( NanoHTTPD.Response.Status.EXPECTATION_FAILED, MIME_PLAINTEXT, "Failed to send to robot " + m.get("id").get(0) + "."); } else { runJavascript("CallbackManager.robot.updateStatus('" + m.get("id").get(0) + "', true);"); responseBody = "Sent to robot " + m.get("type").get(0) + " successfully."; } break; case "in": robot = getRobotFromId(robotTypeFromString(m.get("type").get(0)), m.get("id").get(0)); if (robot == null) { runJavascript("CallbackManager.robot.updateStatus('" + m.get("id").get(0) + "', false);"); return NanoHTTPD.newFixedLengthResponse( NanoHTTPD.Response.Status.NOT_FOUND, MIME_PLAINTEXT, "Robot " + m.get("id").get(0) + " was not found."); } else { String sensorPort = null; String sensorAxis = null; if (m.get("port") != null) { sensorPort = m.get("port").get(0); } if (m.get("axis") != null) { sensorAxis = m.get("axis").get(0); } String sensorValue = robot.readSensor(m.get("sensor").get(0), sensorPort, sensorAxis); if (sensorValue == null) { runJavascript("CallbackManager.robot.updateStatus('" + m.get("id").get(0) + "', false);"); return NanoHTTPD.newFixedLengthResponse( NanoHTTPD.Response.Status.NO_CONTENT, MIME_PLAINTEXT, "Failed to read sensors from robot " + m.get("id").get(0) + "."); } else { runJavascript("CallbackManager.robot.updateStatus('" + m.get("id").get(0) + "', true);"); responseBody = sensorValue; } } break; case "showInfo": responseBody = showRobotInfo(robotTypeFromString(m.get("type").get(0)), m.get("id").get(0)); break; case "showUpdateInstructions": showFirmwareUpdateInstructions(); break; case "stopAll": stopAll(); break; } return NanoHTTPD.newFixedLengthResponse( NanoHTTPD.Response.Status.OK, MIME_PLAINTEXT, responseBody); } // TODO: Properly define Robot Object // TODO: Synchronization of below functions // TODO: Finish implementing new Robot commands and callbacks private static String startScan() { final List deviceFilter = generateDeviceFilter(); if (BluetoothHelper.currentlyScanning) { return ""; } if (BluetoothHelper.currentlyScanning) { stopDiscover(); } new Thread() { @Override public void run() { btHelper.scanDevices(deviceFilter); } }.start(); return ""; } /** * Finds a robotId in the list of connected robots. Null if it does not exist. * * @param robotType The type of the robot to be found. Must be 'hummingbird' or 'hummingbit' or 'microbit'. * @param robotId Robot ID to find. * @return The connected Robot if it exists, null otherwise. */ private static Robot getRobotFromId(RobotType robotType, String robotId) { if (robotType == RobotType.Hummingbird) { return connectedHummingbirds.get(robotId); } else if (robotType == RobotType.Hummingbit) { return connectedHummingbits.get(robotId); } else { return connectedMicrobits.get(robotId); } } /** * Creates a Bluetooth scan Robot filter that only matches the required 'type' of Robot. * * @return List of scan filters. */ private static List<ScanFilter> generateDeviceFilter() { String ROBOT_UUID = DEVICE_UUID; ScanFilter scanFilter = (new ScanFilter.Builder()) .setServiceUuid(ParcelUuid.fromString(ROBOT_UUID)) .build(); List<ScanFilter> robotFilters = new ArrayList<>(); robotFilters.add(scanFilter); return robotFilters; } /** * @param robotType * @param robotId * @return */ public static String connectToRobot(RobotType robotType, String robotId) { if (robotType == RobotType.Hummingbird) { connectToHummingbird(robotId); } else if (robotType == RobotType.Hummingbit) { connectToHummingbit(robotId); } else { connectToMicrobit(robotId); } return ""; } private static void connectToHummingbird(final String hummingbirdId) { if (connectedHummingbirds.containsKey(hummingbirdId) == false) { final UARTSettings HBUART = HBUARTSettings; if (hummingbirdsToConnect.contains(hummingbirdId)) { hummingbirdsToConnect.remove(hummingbirdId); } try { Thread hbConnectionThread = new Thread() { @Override public void run() { UARTConnection hbConn = btHelper.connectToDeviceUART(hummingbirdId, HBUART); if (hbConn != null && hbConn.isConnected() && connectedHummingbirds != null) { Hummingbird hummingbird = new Hummingbird(hbConn); connectedHummingbirds.put(hummingbirdId, hummingbird); hummingbird.setConnected(); } } }; hbConnectionThread.start(); final Thread oldThread = threadMap.put(hummingbirdId, hbConnectionThread); if (oldThread != null) { new Thread() { @Override public void run() { super.run(); oldThread.interrupt(); } }.start(); } } catch (Exception e) { Log.e("ConnectHB", " Error while connecting to HB " + e.getMessage()); } } } private static void connectToHummingbit(final String hummingbitId) { if (connectedHummingbits.containsKey(hummingbitId) == false) { final UARTSettings HBitUART = HBitUARTSettings; if (hummingbitsToConnect.contains(hummingbitId)) { hummingbitsToConnect.remove(hummingbitId); } try { Thread hbitConnectionThread = new Thread() { @Override public void run() { UARTConnection hbitConn = btHelper.connectToDeviceUART(hummingbitId, HBitUART); if (hbitConn != null && hbitConn.isConnected() && connectedHummingbits != null) { Hummingbit hummingbit = new Hummingbit(hbitConn); connectedHummingbits.put(hummingbitId, hummingbit); hummingbit.setConnected(); } } }; hbitConnectionThread.start(); final Thread oldThread = threadMap.put(hummingbitId, hbitConnectionThread); if (oldThread != null) { new Thread() { @Override public void run() { super.run(); oldThread.interrupt(); } }.start(); } } catch (Exception e) { Log.e("ConnectHBit", " Error while connecting to HBit " + e.getMessage()); } } } private static void connectToMicrobit(final String microbitId) { if (connectedMicrobits.containsKey(microbitId) == false) { final UARTSettings MBitUART = MBitUARTSettings; if (microbitsToConnect.contains(microbitId)) { microbitsToConnect.remove(microbitId); } try { Thread mbitConnectionThread = new Thread() { @Override public void run() { UARTConnection mbitConn = btHelper.connectToDeviceUART(microbitId, MBitUART); if (mbitConn != null && mbitConn.isConnected() && connectedMicrobits != null) { Microbit microbit = new Microbit(mbitConn); connectedMicrobits.put(microbitId, microbit); microbit.setConnected(); } } }; mbitConnectionThread.start(); final Thread oldThread = threadMap.put(microbitId, mbitConnectionThread); if (oldThread != null) { new Thread() { @Override public void run() { super.run(); oldThread.interrupt(); } }.start(); } } catch (Exception e) { Log.e("ConnectHBit", " Error while connecting to HBit " + e.getMessage()); } } } /** * @param robotType * @param robotId * @return */ private String disconnectFromRobot(RobotType robotType, final String robotId) { new Thread() { @Override public void run() { super.run(); Thread connThread = threadMap.get(robotId); if (connThread != null) connThread.interrupt(); } }.start(); if (robotType == RobotType.Hummingbird) { disconnectFromHummingbird(robotId); } else if (robotType == RobotType.Hummingbit) { disconnectFromHummingbit(robotId); } else { disconnectFromMicrobit(robotId); } hummingbirdsToConnect = new HashSet<>(); hummingbitsToConnect = new HashSet<>(); microbitsToConnect = new HashSet<>(); btHelper.stopScan(); runJavascript("CallbackManager.robot.updateStatus('" + bbxEncode(robotId) + "', false);"); Log.d("TotStat", "Connected Hummingbirds: " + connectedHummingbirds.toString()); Log.d("TotStat", "Connected Hummingbits: " + connectedHummingbits.toString()); Log.d("TotStat", "Connected Hummingbits: " + connectedMicrobits.toString()); return robotType.toString() + " disconnected successfully."; } /** * @param hummingbirdId */ public static void disconnectFromHummingbird(String hummingbirdId) { try { Hummingbird hummingbird = (Hummingbird) getRobotFromId(RobotType.Hummingbird, hummingbirdId); if (hummingbird != null) { hummingbird.disconnect(); if (hummingbird.getDisconnected()) { connectedHummingbirds.remove(hummingbirdId); } Log.d("TotStat", "Removing hummingbird: " + hummingbirdId); } else { BluetoothGatt curDeviceGatt = deviceGatt.get(hummingbirdId); if (curDeviceGatt != null) { curDeviceGatt.disconnect(); curDeviceGatt.close(); curDeviceGatt = null; if (deviceGatt.containsKey(hummingbirdId)) { deviceGatt.remove(hummingbirdId); } } } } catch (Exception e) { Log.e("ConnectHB", " Error while disconnecting from HB " + e.getMessage()); } } /** * @param hummingbitId */ public static void disconnectFromHummingbit(String hummingbitId) { try { Hummingbit hummingbit = (Hummingbit) getRobotFromId(RobotType.Hummingbit, hummingbitId); if (hummingbit != null) { hummingbit.disconnect(); if (hummingbit.getDisconnected()) { connectedHummingbits.remove(hummingbitId); } Log.d("TotStat", "Removing hummingbit: " + hummingbitId); } else { BluetoothGatt curDeviceGatt = deviceGatt.get(hummingbitId); if (curDeviceGatt != null) { curDeviceGatt.disconnect(); curDeviceGatt.close(); curDeviceGatt = null; if (deviceGatt.containsKey(hummingbitId)) { deviceGatt.remove(hummingbitId); } } } } catch (Exception e) { Log.e("ConnectHB", " Error while disconnecting from HB " + e.getMessage()); } } /** * @param microbitId */ public static void disconnectFromMicrobit(String microbitId) { try { Microbit microbit = (Microbit) getRobotFromId(RobotType.Microbit, microbitId); if (microbit != null) { microbit.disconnect(); if (microbit.getDisconnected()) { connectedMicrobits.remove(microbitId); } Log.d("TotStat", "Removing microbit: " + microbitId); } else { BluetoothGatt curDeviceGatt = deviceGatt.get(microbitId); if (curDeviceGatt != null) { curDeviceGatt.disconnect(); curDeviceGatt.close(); curDeviceGatt = null; if (deviceGatt.containsKey(microbitId)) { deviceGatt.remove(microbitId); } } } } catch (Exception e) { Log.e("ConnectHB", " Error while disconnecting from MB " + e.getMessage()); } } public static void disconnectAll() { hummingbirdsToConnect = null; hummingbitsToConnect = null; microbitsToConnect = null; if (connectedHummingbirds != null) { for (String individualHummingBird : connectedHummingbirds.keySet()) { disconnectFromHummingbird(individualHummingBird); } } if (connectedHummingbits != null) { for (String individualHummingBit : connectedHummingbits.keySet()) { disconnectFromHummingbit(individualHummingBit); } } if (connectedMicrobits != null) { for (String individualMicroBit : connectedMicrobits.keySet()) { disconnectFromMicrobit(individualMicroBit); } } } /** * @param robotType * @return */ private String getTotalStatus(RobotType robotType) { if (robotType == RobotType.Hummingbird) { return getTotalHBStatus(); } else if (robotType == RobotType.Hummingbit) { return getTotalHBitStatus(); } else { return getTotalMBitStatus(); } } /** * @return */ private String getTotalHBStatus() { Log.d("TotStat", "Connected Hummingbirds: " + connectedHummingbirds.toString()); if (connectedHummingbirds.size() == 0) { return "2"; // No hummingbirds connected } for (Hummingbird hummingbird : connectedHummingbirds.values()) { if (!hummingbird.isConnected()) { return "0"; // Some hummingbird is disconnected } } return "1"; // All hummingbirds are OK } /** * @return */ private String getTotalHBitStatus() { Log.d("TotStat", "Connected Hummingbits: " + connectedHummingbits.toString()); if (connectedHummingbits.size() == 0) { return "2"; // No hummingbits connected } for (Hummingbit hummingbit : connectedHummingbits.values()) { if (!hummingbit.isConnected()) { return "0"; // Some hummingbit is disconnected } } return "1"; // All hummingbits are OK } /** * @return */ private String getTotalMBitStatus() { Log.d("TotStat", "Connected Microbits: " + connectedMicrobits.toString()); if (connectedMicrobits.size() == 0) { return "2"; // No hummingbits connected } for (Microbit microbit : connectedMicrobits.values()) { if (!microbit.isConnected()) { return "0"; // Some hummingbit is disconnected } } return "1"; // All hummingbits are OK } private static String stopDiscover() { if (btHelper != null) btHelper.stopScan(); runJavascript("CallbackManager.robot.stopDiscover();"); return "Bluetooth discovery stopped."; } private String showRobotInfo(RobotType robotType, String robotId) { builder = new AlertDialog.Builder(mainWebViewContext); // Get details Robot robot = getRobotFromId(robotType, robotId); String name = robot.getName(); String macAddress = robot.getMacAddress(); String gapName = robot.getGAPName(); String hardwareVersion = ""; String firmwareVersion = ""; if (robotType == RobotType.Hummingbird) { hardwareVersion = ((Hummingbird) robot).getHardwareVersion(); firmwareVersion = ((Hummingbird) robot).getFirmwareVersion(); } else if (robotType == RobotType.Hummingbit) { hardwareVersion = ((Hummingbit) robot).getHardwareVersion(); firmwareVersion = "microBit: " + ((Hummingbit) robot).getMicroBitVersion() + "SMD: " + ((Hummingbit) robot).getSMDVersion(); } else if (robotType == RobotType.Microbit) { hardwareVersion = ((Microbit) robot).getHardwareVersion(); firmwareVersion = "microBit: " + ((Microbit) robot).getMicroBitVersion(); } builder.setTitle(robotType.toString() + " Peripheral"); String message = ""; if (name != null) message += ("Name: " + name + "\n"); if (macAddress != null) message += ("MAC Address: " + macAddress + "\n"); if (gapName != null) message += ("Bluetooth Name: " + gapName + "\n"); if (hardwareVersion != null) message += ("Hardware Version: " + hardwareVersion + "\n"); if (firmwareVersion != null) message += ("Firmware Version: " + firmwareVersion + "\n"); if (!robot.hasLatestFirmware()) message += ("\nFirmware update available."); builder.setMessage(message); builder.setCancelable(true); if (!robot.hasLatestFirmware()) { builder.setPositiveButton( "Update Firmware", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); showFirmwareUpdateInstructions(); } }); builder.setNegativeButton( "Dismiss", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); } else { builder.setNeutralButton( "Dismiss", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); } new Thread() { @Override public void run() { super.run(); new Handler(mainWebViewContext.getMainLooper()).post(new Runnable() { @Override public void run() { robotInfoDialog = builder.create(); robotInfoDialog.show(); } }); } }.start(); return "Successfully showed robot info."; } private static void showFirmwareUpdateInstructions() { mainWebViewContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(FIRMWARE_UPDATE_URL))); } /** * Resets the values of the peripherals of all connected hummingbirds * and microbits and hummingbits to their default values. */ private void stopAll() { for (Hummingbird hummingbird : connectedHummingbirds.values()) hummingbird.stopAll(); for (Hummingbit hummingbit : connectedHummingbits.values()) hummingbit.stopAll(); for (Microbit microbit : connectedMicrobits.values()) microbit.stopAll(); } }
package org.appwork.swing.event; import java.awt.AWTEvent; import java.awt.EventQueue; import java.awt.Toolkit; public class AWTEventQueueLinker extends EventQueue { private static AWTEventQueueLinker INSTANCE; public synchronized static void link() { if (INSTANCE != null) { return; } INSTANCE = new AWTEventQueueLinker(); } public static boolean isLinked() { return INSTANCE != null; } private AWTDispatchEventSender eventSender; private AWTEventQueueLinker() { super(); eventSender = new AWTDispatchEventSender(); Toolkit.getDefaultToolkit().getSystemEventQueue().push(this); } @Override protected void dispatchEvent(final AWTEvent event) { eventSender.fireEvent(new AWTDispatchEvent(this, AWTDispatchEvent.Type.PRE_DISPATCH, event)); super.dispatchEvent(event); eventSender.fireEvent(new AWTDispatchEvent(this, AWTDispatchEvent.Type.POST_DISPATCH, event)); } public AWTDispatchEventSender getEventSender() { return eventSender; } /** * @return */ public static AWTEventQueueLinker getInstance() { // TODO Auto-generated method stub return INSTANCE; } }
package org.citydb.modules.kml.database; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashSet; import org.citydb.api.concurrent.WorkerPool; import org.citydb.api.database.DatabaseSrs; import org.citydb.api.geometry.BoundingBox; import org.citydb.api.geometry.BoundingBoxCorner; import org.citydb.api.geometry.GeometryObject; import org.citydb.api.geometry.GeometryObject.GeometryType; import org.citydb.config.Config; import org.citydb.config.project.database.Database; import org.citydb.config.project.database.Database.PredefinedSrsName; import org.citydb.config.project.exporter.ExportFilterConfig; import org.citydb.config.project.kmlExporter.DisplayForm; import org.citydb.database.DatabaseConnectionPool; import org.citydb.database.adapter.AbstractDatabaseAdapter; import org.citydb.log.Logger; import org.citydb.modules.common.filter.ExportFilter; import org.citydb.modules.kml.util.CityObject4JSON; import org.citydb.util.Util; import org.citygml4j.geometry.Point; import org.citygml4j.model.citygml.CityGMLClass; import org.citygml4j.model.gml.geometry.primitives.Envelope; public class KmlSplitter { private final HashSet<CityGMLClass> CURRENTLY_ALLOWED_CITY_OBJECT_TYPES = new HashSet<CityGMLClass>(); private final WorkerPool<KmlSplittingResult> dbWorkerPool; private final DisplayForm displayForm; private final ExportFilter exportFilter; private ExportFilterConfig filterConfig; private volatile boolean shouldRun = true; private AbstractDatabaseAdapter databaseAdapter; private Connection connection; private DatabaseSrs dbSrs; public KmlSplitter(DatabaseConnectionPool dbConnectionPool, WorkerPool<KmlSplittingResult> dbWorkerPool, ExportFilter exportFilter, DisplayForm displayForm, Config config) throws SQLException { this.dbWorkerPool = dbWorkerPool; this.exportFilter = exportFilter; this.displayForm = displayForm; this.filterConfig = config.getProject().getKmlExporter().getFilter(); CURRENTLY_ALLOWED_CITY_OBJECT_TYPES.clear(); boolean allowAllTypes = !filterConfig.isSetComplexFilter(); if (allowAllTypes || filterConfig.getComplexFilter().getFeatureClass().isSetBuilding()) { CURRENTLY_ALLOWED_CITY_OBJECT_TYPES.add(CityGMLClass.BUILDING); } if (allowAllTypes || filterConfig.getComplexFilter().getFeatureClass().isSetWaterBody()) { CURRENTLY_ALLOWED_CITY_OBJECT_TYPES.add(CityGMLClass.WATER_BODY); } if (allowAllTypes || filterConfig.getComplexFilter().getFeatureClass().isSetLandUse()) { CURRENTLY_ALLOWED_CITY_OBJECT_TYPES.add(CityGMLClass.LAND_USE); } if (allowAllTypes || filterConfig.getComplexFilter().getFeatureClass().isSetVegetation() && config.getProject().getKmlExporter().getLodToExportFrom() > 0) { CURRENTLY_ALLOWED_CITY_OBJECT_TYPES.add(CityGMLClass.SOLITARY_VEGETATION_OBJECT); CURRENTLY_ALLOWED_CITY_OBJECT_TYPES.add(CityGMLClass.PLANT_COVER); } if (allowAllTypes || filterConfig.getComplexFilter().getFeatureClass().isSetTransportation()) { CURRENTLY_ALLOWED_CITY_OBJECT_TYPES.add(CityGMLClass.TRANSPORTATION_COMPLEX); CURRENTLY_ALLOWED_CITY_OBJECT_TYPES.add(CityGMLClass.TRACK); CURRENTLY_ALLOWED_CITY_OBJECT_TYPES.add(CityGMLClass.RAILWAY); CURRENTLY_ALLOWED_CITY_OBJECT_TYPES.add(CityGMLClass.ROAD); CURRENTLY_ALLOWED_CITY_OBJECT_TYPES.add(CityGMLClass.SQUARE); } if (allowAllTypes || filterConfig.getComplexFilter().getFeatureClass().isSetReliefFeature() && config.getProject().getKmlExporter().getLodToExportFrom() > 0) { CURRENTLY_ALLOWED_CITY_OBJECT_TYPES.add(CityGMLClass.RELIEF_FEATURE); } if (allowAllTypes || filterConfig.getComplexFilter().getFeatureClass().isSetGenericCityObject()) { CURRENTLY_ALLOWED_CITY_OBJECT_TYPES.add(CityGMLClass.GENERIC_CITY_OBJECT); } if (allowAllTypes || filterConfig.getComplexFilter().getFeatureClass().isSetCityFurniture() && config.getProject().getKmlExporter().getLodToExportFrom() > 0) { CURRENTLY_ALLOWED_CITY_OBJECT_TYPES.add(CityGMLClass.CITY_FURNITURE); } if (allowAllTypes || filterConfig.getComplexFilter().getFeatureClass().isSetCityObjectGroup() && config.getProject().getKmlExporter().getLodToExportFrom() > 0) { CURRENTLY_ALLOWED_CITY_OBJECT_TYPES.add(CityGMLClass.CITY_OBJECT_GROUP); } if (allowAllTypes || filterConfig.getComplexFilter().getFeatureClass().isSetBridge() && config.getProject().getKmlExporter().getLodToExportFrom() > 0) { CURRENTLY_ALLOWED_CITY_OBJECT_TYPES.add(CityGMLClass.BRIDGE); } if (allowAllTypes || filterConfig.getComplexFilter().getFeatureClass().isSetTunnel() && config.getProject().getKmlExporter().getLodToExportFrom() > 0) { CURRENTLY_ALLOWED_CITY_OBJECT_TYPES.add(CityGMLClass.TUNNEL); } databaseAdapter = dbConnectionPool.getActiveDatabaseAdapter(); connection = dbConnectionPool.getConnection(); dbSrs = databaseAdapter.getConnectionMetaData().getReferenceSystem(); // try and change workspace for connection if needed if (dbConnectionPool.getActiveDatabaseAdapter().hasVersioningSupport()) { Database database = config.getProject().getDatabase(); dbConnectionPool.getActiveDatabaseAdapter().getWorkspaceManager().gotoWorkspace(connection, database.getWorkspaces().getKmlExportWorkspace()); } } private void queryObjects() throws SQLException { if (filterConfig.isSetSimpleFilter()) { for (String gmlId: filterConfig.getSimpleFilter().getGmlIdFilter().getGmlIds()) { if (!shouldRun) break; ResultSet rs = null; PreparedStatement query = null; try { query = connection.prepareStatement(Queries.GET_ID_AND_OBJECTCLASS_FROM_GMLID); query.setString(1, gmlId); rs = query.executeQuery(); if (rs.next()) { long id = rs.getLong("id"); CityGMLClass cityObjectType = Util.classId2cityObject(rs.getInt("objectclass_id")); addWorkToQueue(id, gmlId, cityObjectType, null, 0, 0); } } catch (SQLException sqlEx) { throw sqlEx; } finally { if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { throw sqlEx; } rs = null; } if (query != null) { try { query.close(); } catch (SQLException sqlEx) { throw sqlEx; } query = null; } } } } else if (filterConfig.isSetComplexFilter() && filterConfig.getComplexFilter().getTiledBoundingBox().isSet()) { ResultSet rs = null; PreparedStatement spatialQuery = null; try { spatialQuery = connection.prepareStatement(Queries.GET_IDS(databaseAdapter.getDatabaseType())); spatialQuery.setObject(1, databaseAdapter.getGeometryConverter().getDatabaseObject(GeometryObject.createEnvelope(exportFilter.getBoundingBoxFilter().getFilterState()), connection)); rs = spatialQuery.executeQuery(); int objectCount = 0; while (rs.next() && shouldRun) { long id = rs.getLong("id"); String gmlId = rs.getString("gmlId"); CityGMLClass cityObjectType = Util.classId2cityObject(rs.getInt("objectclass_id")); GeometryObject envelope = null; Object geomObj = rs.getObject("envelope"); if (!rs.wasNull() && geomObj != null) envelope = databaseAdapter.getGeometryConverter().getEnvelope(geomObj); addWorkToQueue(id, gmlId, cityObjectType, envelope, exportFilter.getBoundingBoxFilter().getTileRow(), exportFilter.getBoundingBoxFilter().getTileColumn()); objectCount++; } Logger.getInstance().debug("Tile_" + exportFilter.getBoundingBoxFilter().getTileRow() + "_" + exportFilter.getBoundingBoxFilter().getTileColumn() + " contained " + objectCount + " objects."); } catch (SQLException sqlEx) { throw sqlEx; } finally { if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { throw sqlEx; } rs = null; } if (spatialQuery != null) { try { spatialQuery.close(); } catch (SQLException sqlEx) { throw sqlEx; } spatialQuery = null; } } } } public void startQuery() throws SQLException { try { queryObjects(); } finally { if (connection != null) { try { connection.close(); } catch (SQLException sqlEx) {} connection = null; } } } public void shutdown() { shouldRun = false; } private void addWorkToQueue(long id, String gmlId, CityGMLClass cityObjectType, GeometryObject envelope, int row, int column) throws SQLException { if (CURRENTLY_ALLOWED_CITY_OBJECT_TYPES.contains(cityObjectType)) { // check whether center point of the feature's envelope is within the tile extent if (envelope != null && envelope.getGeometryType() == GeometryType.ENVELOPE) { double coordinates[] = envelope.getCoordinates(0); Envelope tmp = new Envelope(); tmp.setLowerCorner(new Point(coordinates[0], coordinates[1], 0)); tmp.setUpperCorner(new Point(coordinates[3], coordinates[4], 0)); if (exportFilter.getBoundingBoxFilter().filter(tmp)) return; } // create json CityObject4JSON cityObject4Json = new CityObject4JSON(gmlId); cityObject4Json.setTileRow(row); cityObject4Json.setTileColumn(column); cityObject4Json.setEnvelope(getEnvelopeInWGS84(envelope)); // put on work queue KmlSplittingResult splitter = new KmlSplittingResult(id, gmlId, cityObjectType, cityObject4Json, displayForm); dbWorkerPool.addWork(splitter); if (splitter.isCityObjectGroup() && (filterConfig.isSetSimpleFilter() || CURRENTLY_ALLOWED_CITY_OBJECT_TYPES.size() > 1)) { ResultSet rs = null; PreparedStatement query = null; try { if (filterConfig.isSetComplexFilter() && filterConfig.getComplexFilter().getTiledBoundingBox().isSet()) { query = connection.prepareStatement(Queries.CITYOBJECTGROUP_MEMBERS_IN_BBOX(databaseAdapter.getDatabaseType())); query.setObject(2, databaseAdapter.getGeometryConverter().getDatabaseObject(GeometryObject.createEnvelope(exportFilter.getBoundingBoxFilter().getFilterState()), connection)); } else query = connection.prepareStatement(Queries.CITYOBJECTGROUP_MEMBERS); // set group's id query.setLong(1, id); rs = query.executeQuery(); while (rs.next() && shouldRun) { long _id = rs.getLong("id"); String _gmlId = rs.getString("gmlId"); CityGMLClass _cityObjectType = Util.classId2cityObject(rs.getInt("objectclass_id")); GeometryObject _envelope = null; Object geomObj = rs.getObject("envelope"); if (!rs.wasNull() && geomObj != null) _envelope = databaseAdapter.getGeometryConverter().getEnvelope(geomObj); addWorkToQueue(_id, _gmlId, _cityObjectType, _envelope, row, column); } } catch (SQLException sqlEx) { throw sqlEx; } finally { if (rs != null) { try { rs.close(); } catch (SQLException sqlEx) { throw sqlEx; } rs = null; } if (query != null) { try { query.close(); } catch (SQLException sqlEx) { throw sqlEx; } query = null; } } } } } private double[] getEnvelopeInWGS84(GeometryObject envelope) throws SQLException { if (envelope == null) return null; double[] coordinates = envelope.getCoordinates(0); BoundingBox bbox = new BoundingBox(new BoundingBoxCorner(coordinates[0], coordinates[1]), new BoundingBoxCorner(coordinates[3], coordinates[4])); BoundingBox wgs84 = databaseAdapter.getUtil().transformBoundingBox(bbox, dbSrs, Database.PREDEFINED_SRS.get(PredefinedSrsName.WGS84_2D)); double[] result = new double[6]; result[0] = wgs84.getLowerLeftCorner().getX(); result[1] = wgs84.getLowerLeftCorner().getY(); result[2] = 0; result[3] = wgs84.getUpperRightCorner().getX(); result[4] = wgs84.getUpperRightCorner().getY(); result[5] = 0; return result; } }
package org.ovirt.engine.core.bll.storage; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.ovirt.engine.core.bll.validator.ValidationResultMatchers.failsWith; import static org.ovirt.engine.core.bll.validator.ValidationResultMatchers.isValid; import static org.ovirt.engine.core.utils.MockConfigRule.mockConfig; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.ovirt.engine.core.common.businessentities.StoragePoolStatus; import org.ovirt.engine.core.common.businessentities.StoragePool; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.errors.VdcBllMessages; import org.ovirt.engine.core.compat.Version; import org.ovirt.engine.core.utils.MockConfigRule; public class StoragePoolValidatorTest { private static final Version UNSUPPORTED_VERSION = Version.v3_0; private static final Version SUPPORTED_VERSION = Version.v3_3; @ClassRule public static MockConfigRule mce = new MockConfigRule (mockConfig(ConfigValues.PosixStorageEnabled, UNSUPPORTED_VERSION.toString(), false), mockConfig(ConfigValues.PosixStorageEnabled, SUPPORTED_VERSION.toString(), true), mockConfig(ConfigValues.GlusterFsStorageEnabled, UNSUPPORTED_VERSION.toString(), false), mockConfig(ConfigValues.GlusterFsStorageEnabled, SUPPORTED_VERSION.toString(), true)); private StoragePoolValidator validator; private StoragePool storagePool; @Before public void setup() { storagePool = new StoragePool(); storagePool.setStatus(StoragePoolStatus.Up); validator = spy(new StoragePoolValidator(storagePool)); } @Test public void testPosixDcAndMatchingCompatiblityVersion() { storagePool.setcompatibility_version(SUPPORTED_VERSION); storagePool.setIsLocal(false); assertThat(validator.isPosixSupportedInDC(), isValid()); } @Test public void testPosixDcAndNotMatchingCompatiblityVersion() { storagePool.setcompatibility_version(UNSUPPORTED_VERSION); storagePool.setIsLocal(false); assertThat(validator.isPosixSupportedInDC(), failsWith(VdcBllMessages.DATA_CENTER_POSIX_STORAGE_NOT_SUPPORTED_IN_CURRENT_VERSION)); } @Test public void testGlusterDcAndMatchingCompatiblityVersion() { storagePool.setcompatibility_version(SUPPORTED_VERSION); storagePool.setIsLocal(false); assertThat(validator.isGlusterSupportedInDC(), isValid()); } @Test public void testGlusterDcAndNotMatchingCompatiblityVersion() { storagePool.setcompatibility_version(UNSUPPORTED_VERSION); storagePool.setIsLocal(false); assertThat(validator.isGlusterSupportedInDC(), failsWith(VdcBllMessages.DATA_CENTER_GLUSTER_STORAGE_NOT_SUPPORTED_IN_CURRENT_VERSION)); } @Test public void testLocalDcAndMatchingCompatiblityVersion() { storagePool.setcompatibility_version(UNSUPPORTED_VERSION); storagePool.setIsLocal(true); assertThat(validator.isPosixSupportedInDC(), isValid()); } @Test public void testIsNotLocalFsWithDefaultCluster() { storagePool.setIsLocal(true); doReturn(false).when(validator).containsDefaultCluster(); assertThat(validator.isNotLocalfsWithDefaultCluster(), isValid()); } @Test public void testIsNotLocalFsWithDefaultClusterWhenClusterIsDefault() { storagePool.setIsLocal(true); doReturn(true).when(validator).containsDefaultCluster(); assertThat(validator.isNotLocalfsWithDefaultCluster(), failsWith(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_WITH_DEFAULT_VDS_GROUP_CANNOT_BE_LOCALFS)); } @Test public void testIsUpdValid() { assertThat("Storage pool should be up", validator.isUp(), isValid()); } @Test public void testIsUpdInvalid() { storagePool.setStatus(StoragePoolStatus.NonResponsive); assertThat(validator.isUp(), failsWith(VdcBllMessages.ACTION_TYPE_FAILED_IMAGE_REPOSITORY_NOT_FOUND)); } }
package org.encog.app.analyst.analyze; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.encog.app.analyst.script.AnalystClassItem; import org.encog.app.analyst.script.AnalystScript; import org.encog.app.analyst.script.DataField; import org.encog.app.analyst.script.prop.ScriptProperties; /** * This class represents a field that the Encog Analyst is in the process of * analyzing. This class is used to track statistical information on the field * that will help the Encog analyst determine what type of field this is, and * how to normalize it. * */ public class AnalyzedField extends DataField { private double total; private int instances; private double devTotal; private Map<String, AnalystClassItem> classMap = new HashMap<String, AnalystClassItem>(); private AnalystScript script; public AnalyzedField(AnalystScript script, String name) { super(name); this.instances = 0; this.script = script; } public void analyze1(String str) { boolean accountedFor = false; if (str.trim().length() == 0) { this.setComplete(false); return; } this.instances++; if (this.isReal()) { try { double d = Double.parseDouble(str); this.setMax(Math.max(d, this.getMax())); this.setMin(Math.min(d, this.getMin())); this.total += d; accountedFor = true; } catch (NumberFormatException ex) { this.setReal(false); if (!this.isInteger()) { this.setMax(0); this.setMin(0); this.setStandardDeviation(0); } } } if (this.isInteger()) { try { int i = Integer.parseInt(str); this.setMax(Math.max(i, this.getMax())); this.setMin(Math.min(i, this.getMin())); if(!accountedFor) this.total += i; } catch (NumberFormatException ex) { this.setInteger(false); if (!this.isReal()) { this.setMax(0); this.setMin(0); this.setStandardDeviation(0); } } } if (this.isClass()) { AnalystClassItem item; // is this a new class? if (!this.classMap.containsKey(str)) { this.classMap.put(str, item = new AnalystClassItem(str, str, 1)); // do we have too many different classes? int max = script.getProperties().getPropertyInt( ScriptProperties.SETUP_CONFIG_maxClassCount); if (this.classMap.size() > max) this.setClass(false); } else { item = this.classMap.get(str); item.increaseCount(); } } } public void completePass1() { this.devTotal = 0; if (this.instances == 0) this.setMean(0); else this.setMean(this.total / this.instances); } public void analyze2(String str) { if (str.trim().length() == 0) { return; } if (this.isReal() || this.isInteger()) { double d = Double.parseDouble(str); this.devTotal += Math.pow((d - this.getMean()), 2); } } public void completePass2() { this.setStandardDeviation(Math.sqrt(this.devTotal / this.instances)); } public List<AnalystClassItem> getClassMembers() { List<String> sorted = new ArrayList<String>(); sorted.addAll(this.classMap.keySet()); Collections.sort(sorted); List<AnalystClassItem> result = new ArrayList<AnalystClassItem>(); for (String str : sorted) { result.add(this.classMap.get(str)); } return result; } public DataField finalizeField() { DataField result = new DataField(this.getName()); result.setName(getName()); result.setMin(getMin()); result.setMax(getMax()); result.setMean(getMean()); result.setStandardDeviation(getStandardDeviation()); result.setInteger(isInteger()); result.setReal(isReal()); result.setClass(isClass()); result.setComplete(isComplete()); result.getClassMembers().clear(); if (result.isClass()) { List<AnalystClassItem> list = getClassMembers(); result.getClassMembers().addAll(list); } return result; } /** {@inheritDoc} */ public String toString() { StringBuilder result = new StringBuilder("["); result.append(getClass().getSimpleName()); result.append(" total="); result.append(this.total); result.append(", instances="); result.append(this.instances); result.append("]"); return result.toString(); } }
package org.griphyn.common.catalog.replica; import org.griphyn.common.catalog.ReplicaCatalog; import org.griphyn.common.catalog.ReplicaCatalogEntry; import org.griphyn.cPlanner.common.LogManager; import edu.isi.ikcap.workflows.dc.DataCharacterization; import edu.isi.ikcap.workflows.dc.DataCharacterizationFactory; import edu.isi.ikcap.workflows.dc.classes.DataSourceLocationObject; import edu.isi.ikcap.workflows.util.FactoryException; import java.util.List; import java.util.LinkedList; import java.util.Iterator; import java.util.Map; import java.util.HashMap; import java.util.Set; import java.util.HashSet; import java.util.Collection; import java.util.Properties; /** * An implementation of the Replica Catalog interface that talks to Windward * Data Characterization Catalog. * * @author Karan Vahi * @version $Revision$ */ public class Windward implements ReplicaCatalog { /** * The property that designates which data characterization catalog impl to pick up. */ public static final String DATA_CHARACTERIZATION_IMPL_PROPERTY = "windward"; /** * The handle to the Data Characterization Catalog. */ private DataCharacterization mDCharCatalog; /** * The handle to the log manager. */ protected LogManager mLogger; /** * Converts a DataSourceLocationObject to ReplicaCatalogEntry. * * * @param ds the DataSourceLocation to be converted. * * @return ReplicaCatalogEntry */ public static ReplicaCatalogEntry convertToRCE( DataSourceLocationObject ds ){ ReplicaCatalogEntry rce = new ReplicaCatalogEntry( ); rce.setPFN( ds.getLocation() ); rce.setResourceHandle( ds.getSite() ); //other attributes to converted later on. return rce; } /** * The default constructor. */ public Windward() { } /** * Removes everything. The SR DC API does not support removes or deletes. * Always returns 0. * * @return the number of removed entries. */ public int clear() { return 0; } /** * Explicitely free resources before the garbage collection hits. * * */ public void close() { mDCharCatalog.close(); mDCharCatalog = null; } /** * Establishes a link between the implementation and the thing the * implementation is build upon. * * @param props contains all necessary data to establish the link. * @return true if connected now, or false to indicate a failure. */ public boolean connect( Properties props ) { boolean connect = true; //figure out how to specify via properties try{ String implementor = props.getProperty( this.DATA_CHARACTERIZATION_IMPL_PROPERTY ); mDCharCatalog = DataCharacterizationFactory.loadInstance( implementor, props ); }catch( FactoryException e ){ connect = false; mLogger.log( "Unable to connect to Data Characterization Catalog " + e.convertException(), LogManager.DEBUG_MESSAGE_LEVEL ); } return connect; } /** * Deletes all PFN entries for a given LFN from the replica catalog where * the PFN attribute is found, and matches exactly the object value. * The SR DC API does not support removes or deletes. Always returns 0. * * @param lfn is the logical filename to look for. * @param name is the PFN attribute name to look for. * @param value is an exact match of the attribute value to match. * @return the number of removed entries. */ public int delete(String lfn, String name, Object value) { return 0; } /** * Deletes a very specific mapping from the replica catalog. * The SR DC API does not support removes or deletes. * Always returns 0. * * @param lfn is the logical filename in the tuple. * @param tuple is a description of the PFN and its attributes. * @return the number of removed entries, either 0 or 1. */ public int delete(String lfn, ReplicaCatalogEntry tuple) { return 0; } /** * Deletes multiple mappings into the replica catalog. * The SR DC API does not support removes or deletes. * Always returns 0. * * @param x is a map from logical filename string to list of replica * catalog entries. * @param matchAttributes whether mapping should be deleted only if all * attributes match. * * @return the number of deletions. * */ public int delete(Map x, boolean matchAttributes) { return 0; } /** * Deletes a specific mapping from the replica catalog. * The SR DC API does not support removes or deletes. * Always returns 0. * * @param lfn is the logical filename in the tuple. * @param pfn is the physical filename in the tuple. * * @return the number of removed entries. */ public int delete( String lfn, String pfn ) { return 0; } /** * Deletes all PFN entries for a given LFN from the replica catalog where * the resource handle is found. The SR DC API does not support removes or deletes. * Always returns 0. * * @param lfn is the logical filename to look for. * @param handle is the resource handle * * @return the number of entries removed. */ public int deleteByResource(String lfn, String handle) { return 0; } /** * Inserts a new mapping into the replica catalog. * * @param lfn is the logical filename under which to book the entry. * @param pfn is the physical filename associated with it. * @param handle is a resource handle where the PFN resides. * @return number of insertions, should always be 1. On failure, throw * an exception, don't use zero. * */ public int insert(String lfn, String pfn, String handle) { DataSourceLocationObject ds = new DataSourceLocationObject( ); ds.setDataObjectID( lfn ); ds.setLocation( pfn ); ds.setSite( handle ); return mDCharCatalog.registerDataObject( ds ) ? 1: 0; } /** * Inserts a new mapping into the replica catalog. * For the time being only the pfn and site attribute are registered. * * @param lfn is the logical filename under which to book the entry. * @param tuple is the physical filename and associated PFN attributes. * * @return number of insertions, should always be 1. On failure, throw * an exception, don't use zero. */ public int insert( String lfn, ReplicaCatalogEntry tuple ) { //for the time being only populating the pfn and site attribute DataSourceLocationObject ds = new DataSourceLocationObject(); ds.setDataObjectID( lfn ); ds.setLocation( tuple.getPFN() ); ds.setSite( tuple.getResourceHandle() ); return mDCharCatalog.registerDataObject( ds ) ? 1: 0; } /** * Inserts multiple mappings into the replica catalog. * For the time being only the pfn and site attribute are registered for * each entry. * * @param x is a map from logical filename string to list of replica * catalog entries. * * @return the number of insertions. * */ public int insert( Map x ) { int result = 0; //traverse through the entries and insert one by one for( Iterator it = x.entrySet().iterator(); it.hasNext(); ){ Map.Entry entry = ( Map.Entry )it.next(); String lfn = ( String )entry.getKey(); //traverse through rce's for each lfn for( Iterator rceIt = ((List)entry.getValue()).iterator(); rceIt.hasNext(); ){ ReplicaCatalogEntry rce = ( ReplicaCatalogEntry )rceIt.next(); result += this.insert( lfn, rce ); } } return result; } /** * Predicate to check, if the connection with the catalog's * implementation is still active. * * @return true, if the implementation is disassociated, false otherwise. */ public boolean isClosed() { return mDCharCatalog == null ; } /** * Lists a subset of all logical filenames in the catalog. * * @param constraint is a constraint for the logical filename only. It * is a string that has some meaning to the implementing system. This * can be a SQL wildcard for queries, or a regular expression for * Java-based memory collections. * * @return A set of logical filenames that match. The set may be empty * * @throws UnsupportedOperationException * */ public Set list( String constraint ) { throw new UnsupportedOperationException( "Unsupported operation list( String )" ); } /** * Lists all logical filenames in the catalog. * * @return A set of all logical filenames known to the catalog. * * * @throws UnsupportedOperationException */ public Set list() { throw new UnsupportedOperationException( "Unsupported operation list( String )" ); } /** * Retrieves the entry for a given filename and resource handle from the * replica catalog. * * @param lfn is the logical filename to obtain information for. * @param handle is the resource handle to obtain entries for. * * @return the (first) matching physical filename, or <code>null</code> * if no match was found. */ public String lookup( String lfn, String handle) { String result = null; Collection l = mDCharCatalog.findDataObjectLocationsAndAccessAttributes( lfn ); //sanity check if( l == null ){ return result; } for( Iterator it = l.iterator(); it.hasNext(); ){ DataSourceLocationObject ds = ( DataSourceLocationObject )it.next(); if( ( result = ds.getSite() ).equals( handle ) ){ return result; } } return null; } /** * Retrieves all entries for a given LFN from the replica catalog. * For the time being only the pfn and site attribute are retrieved for * the lfn. * * @param lfn is the logical filename to obtain information for. * * @return a collection of replica catalog entries */ public Collection lookup( String lfn ) { Collection result = new LinkedList(); Collection l = mDCharCatalog.findDataObjectLocationsAndAccessAttributes( lfn ); //sanity check if( l == null ){ return result; } for( Iterator it = l.iterator(); it.hasNext(); ){ DataSourceLocationObject ds = (DataSourceLocationObject) it.next(); l.add( convertToRCE( ds ) ); } return result; } /** * Retrieves multiple entries for a given logical filename, up to the * complete catalog. For the time being only the pfn and site attribute are * retrieved for the lfn. * * @param lfns is a set of logical filename strings to look up. * @param handle is the resource handle, restricting the LFNs. * * @return a map indexed by the LFN. Each value is a collection of * replica catalog entries (all attributes). */ public Map lookup(Set lfns, String handle ) { Map result = new HashMap(); Map m = mDCharCatalog.findDataObjectLocationsAndAccessAttributes( lfns ); //iterate through the entries and match for handle for( Iterator it = m.entrySet().iterator(); it.hasNext(); ){ Map.Entry entry = ( Map.Entry )it.next(); String lfn = ( String )entry.getKey(); List rces = new LinkedList(); //traverse through all the DataSourceLocationObjects for lfn List l = ( List )entry.getValue(); //sanity check if( l == null ){ continue ; } for( Iterator dit = l.iterator(); dit.hasNext(); ){ DataSourceLocationObject ds = ( DataSourceLocationObject )dit.next(); if( ds.getSite().equals( handle ) ){ //add to the rces list rces.add( convertToRCE( ds ) ); } } //populate the entry for lfn into result //Do we checks for empty rce list ??? result.put( lfn, rces ); } return result; } /** * Retrieves multiple entries for a given logical filename, up to the * complete catalog. * * @param constraints is mapping of keys 'lfn', 'pfn', or any attribute * name, e.g. the resource handle 'site', to a string that has some * meaning to the implementing system. This can be a SQL wildcard for * queries, or a regular expression for Java-based memory collections. * Unknown keys are ignored. Using an empty map requests the complete * catalog. * * @return a map indexed by the LFN. Each value is a collection of * replica catalog entries. * * @throws new UnsupportedOperationException( "Unsupported operation list( String )" ); */ public Map lookup( Map constraints ) { throw new UnsupportedOperationException( "Unsupported operation lookup( Map )" ); } /** * Retrieves multiple entries for a given logical filename, up to the * complete catalog. For the time being only the pfn and site attribute are * retrieved for the lfn. * * @param lfns is a set of logical filename strings to look up. * * @return a map indexed by the LFN. Each value is a collection of * replica catalog entries for the LFN. */ public Map lookup( Set lfns ) { Map result = new HashMap(); Map m = mDCharCatalog.findDataObjectLocationsAndAccessAttributes( lfns ); //iterate through the entries and match for handle for( Iterator it = m.entrySet().iterator(); it.hasNext(); ){ Map.Entry entry = ( Map.Entry )it.next(); String lfn = ( String )entry.getKey(); List rces = new LinkedList(); //traverse through all the DataSourceLocationObjects for lfn List l = ( List )entry.getValue(); //sanity check if( l == null ){ continue ; } for( Iterator dit = l.iterator(); dit.hasNext(); ){ DataSourceLocationObject ds = ( DataSourceLocationObject )dit.next(); //add to the rces list rces.add( convertToRCE( ds ) ); } //populate the entry for lfn into result //Do we checks for empty rce list ??? result.put( lfn, rces ); } return result; } /** * Retrieves all entries for a given LFN from the replica catalog. * * @param lfn is the logical filename to obtain information for. * * @return a set of PFN strings * */ public Set lookupNoAttributes( String lfn ) { Set result = new HashSet(); for( Iterator it = this.lookup( lfn ).iterator(); it.hasNext(); ){ ReplicaCatalogEntry rce = ( ReplicaCatalogEntry )it.next(); result.add( rce.getPFN() ); } return result; } /** * Retrieves multiple entries for a given logical filename, up to the * complete catalog. * * @param lfns is a set of logical filename strings to look up. * * @return a map indexed by the LFN. Each value is a set of PFN strings. */ public Map lookupNoAttributes( Set lfns ) { Map result = new HashMap(); for( Iterator it = this.lookup( lfns ).entrySet().iterator(); it.hasNext(); ){ Map.Entry entry = ( Map.Entry )it.next(); String lfn = ( String ) entry.getKey(); Set pfns = new HashSet(); //traverse through the rce's and put only pfn's for( Iterator rceIt = (( Collection )entry.getValue()).iterator(); rceIt.hasNext(); ){ ReplicaCatalogEntry rce = ( ReplicaCatalogEntry )rceIt.next(); pfns.add( rce.getPFN() ); } //populate the entry for lfn into result //Do we checks for empty rce list ??? result.put( lfn, pfns ); } return result; } /** * Retrieves multiple entries for a given logical filename, up to the * complete catalog. * * @param lfns is a set of logical filename strings to look up. * @param handle is the resource handle, restricting the LFNs. * * @return a map indexed by the LFN. Each value is a set of physical * filenames. */ public Map lookupNoAttributes(Set lfns, String handle) { Map result = new HashMap(); for( Iterator it = this.lookup( lfns, handle ).entrySet().iterator(); it.hasNext(); ){ Map.Entry entry = ( Map.Entry )it.next(); String lfn = ( String ) entry.getKey(); Set pfns = new HashSet(); //traverse through the rce's and put only pfn's for( Iterator rceIt = (( Collection )entry.getValue()).iterator(); rceIt.hasNext(); ){ ReplicaCatalogEntry rce = ( ReplicaCatalogEntry )rceIt.next(); pfns.add( rce.getPFN() ); } //populate the entry for lfn into result //Do we checks for empty rce list ??? result.put( lfn, pfns ); } return result; } /** * Removes all mappings for an LFN from the replica catalog. * * @param lfn is the logical filename to remove all mappings for. * @return the number of removed entries. */ public int remove(String lfn) { return 0; } /** * Removes all mappings for a set of LFNs. * The SR DC API does not support removes or deletes. Always returns 0. * * @param lfns is a set of logical filename to remove all mappings for. * * @return the number of removed entries. * */ public int remove(Set lfns) { return 0; } /** * Removes all entries from the replica catalog where the PFN attribute * is found, and matches exactly the object value. * * The SR DC API does not support removes or deletes. Always returns 0. * * @param name is the PFN attribute name to look for. * @param value is an exact match of the attribute value to match. * * @return the number of removed entries. * */ public int removeByAttribute(String name, Object value) { return 0; } /** * Removes all entries associated with a particular resource handle. * * * The SR DC API does not support removes or deletes. Always returns 0. * * @param handle is the site handle to remove all entries for. * * @return the number of removed entries. */ public int removeByAttribute(String handle) { return 0; } }
package org.eclipse.smarthome.core.net; import org.osgi.framework.BundleContext; import org.osgi.framework.Constants; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Some utility functions related to the http service * * @author Markus Rathgeb - Initial contribution and API */ public class HttpServiceUtil { private HttpServiceUtil() { } /** * Get the port that is used by the HTTP service. * * @param bc the bundle context used for lookup * @return the port if used, -1 if no port could be found */ public static int getHttpServicePort(final BundleContext bc) { return getHttpServicePortProperty(bc, "org.osgi.service.http.port"); } public static int getHttpServicePortSecure(final BundleContext bc) { return getHttpServicePortProperty(bc, "org.osgi.service.http.port.secure"); } // Utility method that could be used for non-secure and secure port. private static int getHttpServicePortProperty(final BundleContext bc, final String propertyName) { Object value; int port = -1; // Try to find the port by using the service property (respect service ranking). final ServiceReference<?>[] refs; try { refs = bc.getAllServiceReferences("org.osgi.service.http.HttpService", null); } catch (final InvalidSyntaxException ex) { // This point of code should never be reached. final Logger logger = LoggerFactory.getLogger(HttpServiceUtil.class); logger.warn("This error should only be thrown if a filter could not be parsed. We don't use a filter..."); return -1; } if (refs != null) { int candidate = Integer.MIN_VALUE; for (final ServiceReference<?> ref : refs) { value = ref.getProperty(propertyName); if (value == null) { continue; } final int servicePort; try { servicePort = Integer.parseInt(value.toString()); } catch (final NumberFormatException ex) { continue; } value = ref.getProperty(Constants.SERVICE_RANKING); final int serviceRanking; if (value == null || !(value instanceof Integer)) { serviceRanking = 0; } else { serviceRanking = (Integer) value; } if (serviceRanking >= candidate) { candidate = serviceRanking; port = servicePort; } } } if (port > 0) { return port; } // If the service does not provide the port, try to use the system property. value = bc.getProperty(propertyName); if (value != null) { if (value instanceof String) { try { return Integer.parseInt(value.toString()); } catch (final NumberFormatException ex) { // If the property could not be parsed, the HTTP servlet itself has to care and warn about. } } else if (value instanceof Integer) { return (Integer) value; } } return -1; } }
package org.nschmidt.ldparteditor.text; import java.io.File; import java.io.FileNotFoundException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Arrays; import java.util.Locale; import java.util.Set; import java.util.regex.Pattern; import org.lwjgl.util.vector.Matrix4f; import org.lwjgl.util.vector.Vector3f; import org.lwjgl.util.vector.Vector4f; import org.nschmidt.ldparteditor.data.BFC; import org.nschmidt.ldparteditor.data.DatFile; import org.nschmidt.ldparteditor.data.GColour; import org.nschmidt.ldparteditor.data.GData; import org.nschmidt.ldparteditor.data.GData1; import org.nschmidt.ldparteditor.data.GData2; import org.nschmidt.ldparteditor.data.GData3; import org.nschmidt.ldparteditor.data.GData4; import org.nschmidt.ldparteditor.data.GData5; import org.nschmidt.ldparteditor.data.GDataBFC; import org.nschmidt.ldparteditor.data.GDataCSG; import org.nschmidt.ldparteditor.data.GDataTEX; import org.nschmidt.ldparteditor.data.GTexture; import org.nschmidt.ldparteditor.data.TexMeta; import org.nschmidt.ldparteditor.data.TexType; import org.nschmidt.ldparteditor.data.Vertex; import org.nschmidt.ldparteditor.data.colour.GCDithered; import org.nschmidt.ldparteditor.enums.Threshold; import org.nschmidt.ldparteditor.enums.View; import org.nschmidt.ldparteditor.project.Project; import org.nschmidt.ldparteditor.workbench.WorkbenchManager; /** * @author nils * */ public enum TexMapParser { INSTANCE; private static final Pattern WHITESPACE = Pattern.compile("\\s+"); //$NON-NLS-1$ public static GDataTEX parseGeometry(String line, int depth, float r, float g, float b, float a, GData1 gData1, Matrix4f pMatrix, Set<String> alreadyParsed, DatFile datFile) { String tline = line.replaceAll("0\\s+\\Q!:\\E\\s+", ""); //$NON-NLS-1$ //$NON-NLS-2$ GData data = parseLine(tline, depth, r, g, b, a, gData1, pMatrix, alreadyParsed, datFile); return new GDataTEX(data, line, TexMeta.GEOMETRY, null); } public static GDataTEX parseTEXMAP(String[] data_segments, String line, GData1 parent, DatFile datFile) { int segs = data_segments.length; if (segs == 3) { if (data_segments[2].equals("END")) { //$NON-NLS-1$ return new GDataTEX(null, line, TexMeta.END, null); } else if (data_segments[2].equals("FALLBACK")) { //$NON-NLS-1$ return new GDataTEX(null, line, TexMeta.FALLBACK, null); } } else if (segs > 3) { Vector4f v1 = new Vector4f(); Vector4f v2 = new Vector4f(); Vector4f v3 = new Vector4f(); float a = 0f; float b = 0f; TexMeta meta = data_segments[2].equals("START") ? TexMeta.START : data_segments[2].equals("NEXT") ? TexMeta.NEXT : null; //$NON-NLS-1$ //$NON-NLS-2$ if (meta != null && data_segments[3].equals("PLANAR") || data_segments[3].equals("CYLINDRICAL") || data_segments[3].equals("SPHERICAL")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (segs > 13) { String texture = ""; //$NON-NLS-1$ String glossmap = null; TexType type; try { v1.setX(Float.parseFloat(data_segments[4]) * 1000f); v1.setY(Float.parseFloat(data_segments[5]) * 1000f); v1.setZ(Float.parseFloat(data_segments[6]) * 1000f); v1.setW(1f); v2.setX(Float.parseFloat(data_segments[7]) * 1000f); v2.setY(Float.parseFloat(data_segments[8]) * 1000f); v2.setZ(Float.parseFloat(data_segments[9]) * 1000f); v2.setW(1f); v3.setX(Float.parseFloat(data_segments[10]) * 1000f); v3.setY(Float.parseFloat(data_segments[11]) * 1000f); v3.setZ(Float.parseFloat(data_segments[12]) * 1000f); v3.setW(1f); } catch (Exception e) { return null; } Matrix4f.transform(parent.getProductMatrix(), v1, v1); Matrix4f.transform(parent.getProductMatrix(), v2, v2); Matrix4f.transform(parent.getProductMatrix(), v3, v3); StringBuilder tex = new StringBuilder(); StringBuilder gloss = new StringBuilder(); final int len = line.length(); final int target; boolean whitespace1 = false; boolean whitespace2 = false; if (data_segments[3].equals("PLANAR")) { //$NON-NLS-1$ type = TexType.PLANAR; target = 14; } else if (data_segments[3].equals("CYLINDRICAL")) { //$NON-NLS-1$ if (segs > 14) { try { a = (float) (Float.parseFloat(data_segments[13]) / 360f * Math.PI); if (a <= 0f || a > Math.PI * 2f) return null; } catch (Exception e) { return null; } } else { return null; } type = TexType.CYLINDRICAL; target = 15; } else { if (segs > 15) { try { a = (float) (Float.parseFloat(data_segments[13]) / 360f * Math.PI); if (a <= 0f || a > Math.PI * 2f) return null; b = (float) (Float.parseFloat(data_segments[14]) / 360f * Math.PI); if (b <= 0f || b > Math.PI * 2f) return null; } catch (Exception e) { return null; } } else { return null; } type = TexType.SPHERICAL; target = 16; } int mode = 0; int counter = 0; for (int i = 0; i < len; i++) { String sub = line.substring(i, i + 1); switch (mode) { case 0: // Parse initial whitespace if (sub.matches("\\S")) { //$NON-NLS-1$ mode = 1; } case 1: // Parse non-whitespace (first letter) if (sub.matches("\\S")) { //$NON-NLS-1$ counter++; if (counter == target) { if (sub.equals("\"")) { //$NON-NLS-1$ mode = 4; sub = ""; //$NON-NLS-1$ } else { mode = 3; } } else { mode = 2; } } break; case 2: // Parse non-whitespace (rest) if (sub.matches("\\s")) { //$NON-NLS-1$ mode = 1; } break; } switch (mode) { case 3: // Parse texture till whitespace if (sub.matches("\\S")) { //$NON-NLS-1$ tex.append(sub); } else { whitespace1 = true; mode = 5; } break; case 4: // Parse texture till " if (sub.equals("\"")) { //$NON-NLS-1$ mode = 5; } else { tex.append(sub); } break; case 5: // Additional whitespace if (sub.matches("\\S")) { //$NON-NLS-1$ if (whitespace1) mode = 6; } else { whitespace1 = true; break; } case 6: // GLOSSMAP if (sub.equals("G"))mode = 7; //$NON-NLS-1$ break; case 7: // GLOSSMAP if (sub.equals("L"))mode = 8; //$NON-NLS-1$ break; case 8: // GLOSSMAP if (sub.equals("O"))mode = 9; //$NON-NLS-1$ break; case 9: // GLOSSMAP if (sub.equals("S"))mode = 10; //$NON-NLS-1$ break; case 10: // GLOSSMAP if (sub.equals("S"))mode = 11; //$NON-NLS-1$ break; case 11: // GLOSSMAP if (sub.equals("M"))mode = 12; //$NON-NLS-1$ break; case 12: // GLOSSMAP if (sub.equals("A"))mode = 13; //$NON-NLS-1$ break; case 13: // GLOSSMAP if (sub.equals("P"))mode = 14; //$NON-NLS-1$ break; case 14: // Additional whitespace between GLOSSMAP and // glossmap-path if (sub.matches("\\S")) { //$NON-NLS-1$ if (whitespace2) mode = 15; } else { whitespace2 = true; } break; } switch (mode) { case 15: if (sub.matches("\\S")) { //$NON-NLS-1$ if (sub.equals("\"")) { //$NON-NLS-1$ mode = 17; sub = ""; //$NON-NLS-1$ } else { mode = 16; } } break; } switch (mode) { case 16: // Parse texture till whitespace if (sub.matches("\\S")) { //$NON-NLS-1$ gloss.append(sub); } else { mode = 18; } break; case 17: // Parse texture till " if (sub.equals("\"")) { //$NON-NLS-1$ mode = 18; } else { gloss.append(sub); } break; } } texture = tex.toString(); glossmap = gloss.toString(); if (glossmap.isEmpty()) glossmap = null; return new GDataTEX(null, line, meta, new GTexture(type, texture, glossmap, 1, new Vector3f(v1.x, v1.y, v1.z), new Vector3f(v2.x, v2.y, v2.z), new Vector3f(v3.x, v3.y, v3.z), a, b)); } } } return null; } public static GData parseLine(String line, int depth, float r, float g, float b, float a, GData1 gData1, Matrix4f pMatrix, Set<String> alreadyParsed, DatFile df) { final String[] data_segments = WHITESPACE.split(line.trim()); return parseLine(data_segments, line, depth, r, g, b, a, gData1, pMatrix, alreadyParsed, df); } // What follows now is a very minimalistic DAT file parser (<500LOC) private static GColour cValue = new GColour(); private static final Vector3f start = new Vector3f(); private static final Vector3f end = new Vector3f(); private static final Vector3f vertexA = new Vector3f(); private static final Vector3f vertexB = new Vector3f(); private static final Vector3f vertexC = new Vector3f(); private static final Vector3f vertexD = new Vector3f(); private static final Vector3f controlI = new Vector3f(); private static final Vector3f controlII = new Vector3f(); public static GData parseLine(String[] data_segments, String line, int depth, float r, float g, float b, float a, GData1 parent, Matrix4f productMatrix, Set<String> alreadyParsed, DatFile datFile) { // Get the linetype int linetype = 0; char c; if (!(data_segments.length > 0 && data_segments[0].length() == 1 && Character.isDigit(c = data_segments[0].charAt(0)))) { return null; } linetype = Character.getNumericValue(c); // Parse the line according to its type switch (linetype) { case 0: return parse_Comment(line, data_segments, depth, r, g, b, a, parent, productMatrix, alreadyParsed, datFile); case 1: return parse_Reference(data_segments, depth, r, g, b, a, parent, productMatrix, alreadyParsed, datFile); case 2: return parse_Line(data_segments, r, g, b, a, parent); case 3: return parse_Triangle(data_segments, r, g, b, a, parent); case 4: return parse_Quad(data_segments, r, g, b, a, parent); case 5: return parse_Condline(data_segments, r, g, b, a, parent); } return null; } private static GColour validateColour(String arg, float r, float g, float b, float a) { int colourValue; try { colourValue = Integer.parseInt(arg); switch (colourValue) { case 16: cValue.set(16, r, g, b, a); break; case 24: cValue.set(24, View.line_Colour_r[0], View.line_Colour_g[0], View.line_Colour_b[0], 1f); break; default: if (View.hasLDConfigColour(colourValue)) { GColour colour = View.getLDConfigColour(colourValue); cValue.set(colour); } else { int A = colourValue - 256 >> 4; int B = colourValue - 256 & 0x0F; if (View.hasLDConfigColour(A) && View.hasLDConfigColour(B)) { GColour colourA = View.getLDConfigColour(A); GColour colourB = View.getLDConfigColour(B); GColour ditheredColour = new GColour( colourValue, (colourA.getR() + colourB.getR()) / 2f, (colourA.getG() + colourB.getG()) / 2f, (colourA.getB() + colourB.getB()) / 2f, 1f, new GCDithered()); cValue.set(ditheredColour); break; } return null; } break; } } catch (NumberFormatException nfe) { if (arg.length() == 9 && arg.substring(0, 3).equals("0x2")) { //$NON-NLS-1$ cValue.setA(1f); try { cValue.setR(Integer.parseInt(arg.substring(3, 5), 16) / 255f); cValue.setG(Integer.parseInt(arg.substring(5, 7), 16) / 255f); cValue.setB(Integer.parseInt(arg.substring(7, 9), 16) / 255f); } catch (NumberFormatException nfe2) { return null; } cValue.setColourNumber(-1); cValue.setType(null); } else { return null; } } return cValue; } private static GData parse_Comment(String line, String[] data_segments, int depth, float r, float g, float b, float a, GData1 parent, Matrix4f productMatrix, Set<String> alreadyParsed, DatFile datFile) { line = WHITESPACE.matcher(line).replaceAll(" ").trim(); //$NON-NLS-1$ if (line.startsWith("0 !: ")) { //$NON-NLS-1$ GData newLPEmetaTag = TexMapParser.parseGeometry(line, depth, r, g, b, a, parent, productMatrix, alreadyParsed, datFile); return newLPEmetaTag; } else if (line.startsWith("0 !TEXMAP ")) { //$NON-NLS-1$ GData newLPEmetaTag = TexMapParser.parseTEXMAP(data_segments, line, parent, datFile); return newLPEmetaTag; } else if (line.startsWith("0 BFC ")) { //$NON-NLS-1$ if (line.startsWith("INVERTNEXT", 6)) { //$NON-NLS-1$ return new GDataBFC(BFC.INVERTNEXT); } else if (line.startsWith("CERTIFY CCW", 6)) { //$NON-NLS-1$ return new GDataBFC(BFC.CCW_CLIP); } else if (line.startsWith("CERTIFY CW", 6)) { //$NON-NLS-1$ return new GDataBFC(BFC.CW_CLIP); } else if (line.startsWith("CERTIFY", 6)) { //$NON-NLS-1$ return new GDataBFC(BFC.CCW_CLIP); } else if (line.startsWith("NOCERTIFY", 6)) { //$NON-NLS-1$ return new GDataBFC(BFC.NOCERTIFY); } else if (line.startsWith("CCW", 6)) { //$NON-NLS-1$ return new GDataBFC(BFC.CCW); } else if (line.startsWith("CW", 6)) { //$NON-NLS-1$ return new GDataBFC(BFC.CW); } else if (line.startsWith("NOCLIP", 6)) { //$NON-NLS-1$ return new GDataBFC(BFC.NOCLIP); } else if (line.startsWith("CLIP CCW", 6)) { //$NON-NLS-1$ return new GDataBFC(BFC.CCW_CLIP); } else if (line.startsWith("CLIP CW", 6)) { //$NON-NLS-1$ return new GDataBFC(BFC.CW_CLIP); } else if (line.startsWith("CCW CLIP", 6)) { //$NON-NLS-1$ return new GDataBFC(BFC.CCW_CLIP); } else if (line.startsWith("CW CLIP", 6)) { //$NON-NLS-1$ return new GDataBFC(BFC.CW_CLIP); } else if (line.startsWith("CLIP", 6)) { //$NON-NLS-1$ return new GDataBFC(BFC.CLIP); } else { return null; } } else { return null; } } private static GData parse_Reference(String[] data_segments, int depth, float r, float g, float b, float a, GData1 parent, Matrix4f productMatrix, Set<String> alreadyParsed, DatFile datFile) { if (data_segments.length < 15) { return null; } else { GColour colour = validateColour(data_segments[1], r, g, b, a); if (colour == null) return null; Matrix4f tMatrix = new Matrix4f(); float det = 0; try { tMatrix.m30 = Float.parseFloat(data_segments[2]) * 1000f; tMatrix.m31 = Float.parseFloat(data_segments[3]) * 1000f; tMatrix.m32 = Float.parseFloat(data_segments[4]) * 1000f; tMatrix.m00 = Float.parseFloat(data_segments[5]); tMatrix.m10 = Float.parseFloat(data_segments[6]); tMatrix.m20 = Float.parseFloat(data_segments[7]); tMatrix.m01 = Float.parseFloat(data_segments[8]); tMatrix.m11 = Float.parseFloat(data_segments[9]); tMatrix.m21 = Float.parseFloat(data_segments[10]); tMatrix.m02 = Float.parseFloat(data_segments[11]); tMatrix.m12 = Float.parseFloat(data_segments[12]); tMatrix.m22 = Float.parseFloat(data_segments[13]); } catch (NumberFormatException nfe) { return null; } tMatrix.m33 = 1f; det = tMatrix.determinant(); if (Math.abs(det) < Threshold.singularity_determinant) return null; // [WARNING] Check file existance boolean fileExists = true; StringBuilder sb = new StringBuilder(); for (int s = 14; s < data_segments.length - 1; s++) { sb.append(data_segments[s]); sb.append(" "); //$NON-NLS-1$ } sb.append(data_segments[data_segments.length - 1]); String shortFilename = sb.toString(); shortFilename = shortFilename.toLowerCase(Locale.ENGLISH); try { shortFilename = shortFilename.replaceAll("s\\\\", "S" + File.separator).replaceAll("\\\\", File.separator); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } catch (Exception e) { // Workaround for windows OS / JVM BUG shortFilename = shortFilename.replace("s\\", "S" + File.separator).replace("\\", File.separator); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } if (alreadyParsed.contains(shortFilename)) { if (!View.DUMMY_REFERENCE.equals(parent)) parent.firstRef.setRecursive(true); return null; } else { alreadyParsed.add(shortFilename); } String shortFilename2 = shortFilename.startsWith("S" + File.separator) ? "s" + shortFilename.substring(1) : shortFilename; //$NON-NLS-1$ //$NON-NLS-2$ String shortFilename3 = shortFilename.startsWith("S" + File.separator) ? shortFilename.substring(2) : shortFilename; //$NON-NLS-1$ File fileToOpen = null; String[] prefix; if (datFile != null && !datFile.isProjectFile() && !View.DUMMY_DATFILE.equals(datFile)) { File dff = new File(datFile.getOldName()).getParentFile(); if (dff != null && dff.exists() && dff.isDirectory()) { prefix = new String[]{dff.getAbsolutePath(), Project.getProjectPath(), WorkbenchManager.getUserSettingState().getUnofficialFolderPath(), WorkbenchManager.getUserSettingState().getLdrawFolderPath()}; } else { prefix = new String[]{Project.getProjectPath(), WorkbenchManager.getUserSettingState().getUnofficialFolderPath(), WorkbenchManager.getUserSettingState().getLdrawFolderPath()}; } } else { prefix = new String[]{Project.getProjectPath(), WorkbenchManager.getUserSettingState().getUnofficialFolderPath(), WorkbenchManager.getUserSettingState().getLdrawFolderPath()}; } String[] middle = new String[]{"", File.separator + "PARTS", File.separator + "parts", File.separator + "P", File.separator + "p"}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ String[] suffix = new String[]{File.separator + shortFilename, File.separator + shortFilename2, File.separator + shortFilename3}; for (int a1 = 0; a1 < prefix.length; a1++) { String s1 = prefix[a1]; for (int a2 = 0; a2 < middle.length; a2++) { String s2 = middle[a2]; for (int a3 = 0; a3 < suffix.length; a3++) { String s3 = suffix[a3]; File f = new File(s1 + s2 + s3); fileExists = f.exists() && f.isFile(); if (fileExists) { fileToOpen = f; break; } } if (fileExists) break; } if (fileExists) break; } ArrayList<String> lines = null; String absoluteFilename = null; // MARK Virtual file check for project files... boolean isVirtual = false; for (DatFile df : Project.getUnsavedFiles()) { String fn = df.getNewName(); for (int a1 = 0; a1 < prefix.length; a1++) { String s1 = prefix[a1]; for (int a2 = 0; a2 < middle.length; a2++) { String s2 = middle[a2]; for (int a3 = 0; a3 < suffix.length; a3++) { String s3 = suffix[a3]; if (fn.equals(s1 + s2 + s3)) { lines = new ArrayList<String>(4096); lines.addAll(Arrays.asList(df.getText().split(StringHelper.getLineDelimiter()))); absoluteFilename = fn; isVirtual = true; break; } } if (isVirtual) break; } if (isVirtual) break; } if (isVirtual) break; } if (isVirtual) { Matrix4f destMatrix = new Matrix4f(); Matrix4f.mul(productMatrix, tMatrix, destMatrix); GDataCSG.forceRecompile(datFile); final GData1 result = new GData1(colour.getColourNumber(), colour.getR(), colour.getG(), colour.getB(), colour.getA(), tMatrix, lines, absoluteFilename, sb.toString(), depth, det < 0, destMatrix, parent.firstRef, alreadyParsed, parent, datFile); if (result != null && result.firstRef.isRecursive()) { return null; } alreadyParsed.remove(shortFilename); return result; } else if (!fileExists) { alreadyParsed.remove(shortFilename); return null; } else { absoluteFilename = fileToOpen.getAbsolutePath(); UTF8BufferedReader reader = null; String line = null; lines = new ArrayList<String>(4096); try { reader = new UTF8BufferedReader(absoluteFilename); while (true) { line = reader.readLine(); if (line == null) { break; } lines.add(line); } } catch (FileNotFoundException e1) { alreadyParsed.remove(shortFilename); return null; } catch (LDParsingException e1) { alreadyParsed.remove(shortFilename); return null; } catch (UnsupportedEncodingException e1) { alreadyParsed.remove(shortFilename); return null; } finally { try { if (reader != null) reader.close(); } catch (LDParsingException e1) { } } Matrix4f destMatrix = new Matrix4f(); Matrix4f.mul(productMatrix, tMatrix, destMatrix); GDataCSG.forceRecompile(datFile); final GData1 result = new GData1(colour.getColourNumber(), colour.getR(), colour.getG(), colour.getB(), colour.getA(), tMatrix, lines, absoluteFilename, sb.toString(), depth, det < 0, destMatrix, parent.firstRef, alreadyParsed, parent, datFile); alreadyParsed.remove(shortFilename); if (result != null && result.firstRef.isRecursive()) { return null; } return result; } } } private static GData parse_Line(String[] data_segments, float r, float g, float b, float a, GData1 parent) { if (data_segments.length != 8) { return null; } else { GColour colour = validateColour(data_segments[1], r, g, b, a); if (colour == null) return null; try { start.setX(Float.parseFloat(data_segments[2])); start.setY(Float.parseFloat(data_segments[3])); start.setZ(Float.parseFloat(data_segments[4])); end.setX(Float.parseFloat(data_segments[5])); end.setY(Float.parseFloat(data_segments[6])); end.setZ(Float.parseFloat(data_segments[7])); } catch (NumberFormatException nfe) { return null; } if (Vector3f.sub(start, end, null).length() < Threshold.identical_vertex_distance.floatValue()) { return null; } return new GData2(new Vertex(start.x * 1000f, start.y * 1000f, start.z * 1000f, false), new Vertex(end.x * 1000f, end.y * 1000f, end.z * 1000f, false), colour, parent); } } private static GData parse_Triangle(String[] data_segments, float r, float g, float b, float a, GData1 parent) { if (data_segments.length != 11) { return null; } else { GColour colour = validateColour(data_segments[1], r, g, b, a); if (colour == null) return null; try { vertexA.setX(Float.parseFloat(data_segments[2])); vertexA.setY(Float.parseFloat(data_segments[3])); vertexA.setZ(Float.parseFloat(data_segments[4])); vertexB.setX(Float.parseFloat(data_segments[5])); vertexB.setY(Float.parseFloat(data_segments[6])); vertexB.setZ(Float.parseFloat(data_segments[7])); vertexC.setX(Float.parseFloat(data_segments[8])); vertexC.setY(Float.parseFloat(data_segments[9])); } catch (NumberFormatException nfe) { return null; } try { vertexC.setZ(Float.parseFloat(data_segments[10])); } catch (NumberFormatException nfe) { return null; } return new GData3(new Vertex(vertexA.x * 1000f, vertexA.y * 1000f, vertexA.z * 1000f, false), new Vertex(vertexB.x * 1000f, vertexB.y * 1000f, vertexB.z * 1000f, false), new Vertex(vertexC.x * 1000f, vertexC.y * 1000f, vertexC.z * 1000f, false), parent, colour, true); } } private static GData parse_Quad(String[] data_segments, float r, float g, float b, float a, GData1 parent) { if (data_segments.length != 14) { return null; } else { GColour colour = validateColour(data_segments[1], r, g, b, a); if (colour == null) return null; try { vertexA.setX(Float.parseFloat(data_segments[2])); vertexA.setY(Float.parseFloat(data_segments[3])); vertexA.setZ(Float.parseFloat(data_segments[4])); vertexB.setX(Float.parseFloat(data_segments[5])); vertexB.setY(Float.parseFloat(data_segments[6])); vertexB.setZ(Float.parseFloat(data_segments[7])); vertexC.setX(Float.parseFloat(data_segments[8])); vertexC.setY(Float.parseFloat(data_segments[9])); vertexC.setZ(Float.parseFloat(data_segments[10])); vertexD.setX(Float.parseFloat(data_segments[11])); vertexD.setY(Float.parseFloat(data_segments[12])); vertexD.setZ(Float.parseFloat(data_segments[13])); } catch (NumberFormatException nfe) { return null; } return new GData4(new Vertex(vertexA.x * 1000f, vertexA.y * 1000f, vertexA.z * 1000f, false), new Vertex(vertexB.x * 1000f, vertexB.y * 1000f, vertexB.z * 1000f, false), new Vertex(vertexC.x * 1000f, vertexC.y * 1000f, vertexC.z * 1000f, false), new Vertex(vertexD.x * 1000f, vertexD.y * 1000f, vertexD.z * 1000f, false), parent, colour); } } private static GData parse_Condline(String[] data_segments, float r, float g, float b, float a, GData1 parent) { if (data_segments.length != 14) { return null; } else { GColour colour = validateColour(data_segments[1], r, g, b, a); if (colour == null) return null; try { start.setX(Float.parseFloat(data_segments[2])); start.setY(Float.parseFloat(data_segments[3])); start.setZ(Float.parseFloat(data_segments[4])); end.setX(Float.parseFloat(data_segments[5])); end.setY(Float.parseFloat(data_segments[6])); end.setZ(Float.parseFloat(data_segments[7])); controlI.setX(Float.parseFloat(data_segments[8])); controlI.setY(Float.parseFloat(data_segments[9])); controlI.setZ(Float.parseFloat(data_segments[10])); controlII.setX(Float.parseFloat(data_segments[11])); controlII.setY(Float.parseFloat(data_segments[12])); controlII.setZ(Float.parseFloat(data_segments[13])); } catch (NumberFormatException nfe) { return null; } final float epsilon = Threshold.identical_vertex_distance.floatValue(); if (Vector3f.sub(start, end, null).length() < epsilon || Vector3f.sub(controlI, controlII, null).length() < epsilon) { return null; } return new GData5(new Vertex(start.x * 1000f, start.y * 1000f, start.z * 1000f, false), new Vertex(end.x * 1000f, end.y * 1000f, end.z * 1000f, false), new Vertex(controlI.x * 1000f, controlI.y * 1000f, controlI.z * 1000f, false), new Vertex(controlII.x * 1000f, controlII.y * 1000f, controlII.z * 1000f, false), colour, parent); } } }
package org.objectweb.asm.util; import java.io.FileInputStream; import java.io.PrintWriter; import org.objectweb.asm.Attribute; import org.objectweb.asm.ClassReader; import org.objectweb.asm.CodeVisitor; import org.objectweb.asm.Constants; import org.objectweb.asm.Type; import org.objectweb.asm.util.attrs.ASMifiable; /** * A {@link PrintClassVisitor PrintClassVisitor} that prints the ASM code that * generates the classes it visits. This class visitor can be used to quickly * write ASM code to generate some given bytecode: * <ul> * <li>write the Java source code equivalent to the bytecode you want to * generate;</li> * <li>compile it with <tt>javac</tt>;</li> * <li>make a {@link ASMifierClassVisitor} visit this compiled * class (see the {@link #main main} method);</li> * <li>edit the generated source code, if necessary.</li> * </ul> * The source code printed when visiting the <tt>Hello</tt> class is the * following: * <p> * <blockquote> * <pre> * import org.objectweb.asm.*; * import java.io.FileOutputStream; * * public class Dump implements Constants { * * public static void main (String[] args) throws Exception { * * ClassWriter cw = new ClassWriter(false); * CodeVisitor cv; * * cw.visit(ACC_PUBLIC + ACC_SUPER, "Hello", "java/lang/Object", null, "Hello.java"); * * { * cv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null); * cv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); * cv.visitLdcInsn("hello"); * cv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); * cv.visitInsn(RETURN); * cv.visitMaxs(2, 1); * } * { * cv = cw.visitMethod(ACC_PUBLIC, "&lt;init&gt;", "()V", null, null); * cv.visitVarInsn(ALOAD, 0); * cv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "&lt;init&gt;", "()V"); * cv.visitInsn(RETURN); * cv.visitMaxs(1, 1); * } * cw.visitEnd(); * * FileOutputStream os = new FileOutputStream("Dumped.class"); * os.write(cw.toByteArray()); * os.close(); * } * } * </pre> * </blockquote> * where <tt>Hello</tt> is defined by: * <p> * <blockquote> * <pre> * public class Hello { * * public static void main (String[] args) { * System.out.println("hello"); * } * } * </pre> * </blockquote> * * @author Eric Bruneton, Eugene Kuleshov */ public class ASMifierClassVisitor extends PrintClassVisitor { private static final int ACCESS_CLASS = 262144; private static final int ACCESS_FIELD = 524288; private static final int ACCESS_INNER = 1048576; /** * Prints the ASM source code to generate the given class to the standard * output. * <p> * Usage: ASMifierClassVisitor [-debug] * &lt;fully qualified class name or class file name&gt; * * @param args the command line arguments. * * @throws Exception if the class cannot be found, or if an IO exception * occurs. */ public static void main (final String[] args) throws Exception { if (args.length < 1 || args.length > 2) { printUsage(); } int i = 0; boolean skipDebug = true; if (args[0].equals("-debug")) { i = 1; skipDebug = false; if (args.length != 2) { printUsage(); } } ClassReader cr; if (args[i].endsWith(".class")) { cr = new ClassReader(new FileInputStream(args[i])); } else { cr = new ClassReader(args[i]); } cr.accept(new ASMifierClassVisitor( new PrintWriter(System.out)), getDefaultAttributes(), skipDebug); } private static void printUsage () { System.err.println("Prints the ASM code to generate the given class."); System.err.println("Usage: ASMifierClassVisitor [-debug] " + "<fully qualified class name or class file name>"); System.exit(-1); } /** * Constructs a new {@link ASMifierClassVisitor} object. * * @param pw the print writer to be used to print the class. */ public ASMifierClassVisitor (final PrintWriter pw) { super(pw); } public void visit ( final int version, final int access, final String name, final String superName, final String[] interfaces, final String sourceFile) { int n = name.lastIndexOf( "/"); if( n>-1) { text.add("package asm."+name.substring( 0, n).replace( '/', '.')+";\n"); } text.add("import org.objectweb.asm.*;\n"); text.add("import org.objectweb.asm.attrs.*;\n"); text.add("import java.util.*;\n\n"); text.add("public class "+(n==-1 ? name : name.substring( n+1))+"Dump implements Constants {\n\n"); text.add("public static byte[] dump () throws Exception {\n\n"); text.add("ClassWriter cw = new ClassWriter(false);\n"); text.add("CodeVisitor cv;\n\n"); buf.setLength(0); buf.append("cw.visit("); switch(version) { case Constants.V1_1: buf.append("V1_1"); break; case Constants.V1_2: buf.append("V1_2"); break; case Constants.V1_3: buf.append("V1_3"); break; case Constants.V1_4: buf.append("V1_4"); break; case Constants.V1_5: buf.append("V1_5"); break; default: buf.append(version); break; } buf.append(", "); appendAccess(access | ACCESS_CLASS); buf.append(", "); appendConstant(buf, name); buf.append(", "); appendConstant(buf, superName); buf.append(", "); if (interfaces != null && interfaces.length > 0) { buf.append("new String[] {"); for (int i = 0; i < interfaces.length; ++i) { buf.append(i == 0 ? " " : ", "); appendConstant(buf, interfaces[i]); } buf.append(" }"); } else { buf.append("null"); } buf.append(", "); appendConstant(buf, sourceFile); buf.append(");\n\n"); text.add(buf.toString()); } public void visitInnerClass ( final String name, final String outerName, final String innerName, final int access) { buf.setLength(0); buf.append("cw.visitInnerClass("); appendConstant(buf, name); buf.append(", "); appendConstant(buf, outerName); buf.append(", "); appendConstant(buf, innerName); buf.append(", "); appendAccess(access | ACCESS_INNER); buf.append(");\n\n"); text.add(buf.toString()); } public void visitField ( final int access, final String name, final String desc, final Object value, final Attribute attrs) { buf.setLength(0); int n = 1; if (attrs != null) { buf.append("{\n"); buf.append("// FIELD ATTRIBUTES\n"); Attribute a = attrs; while (a != null) { if (a instanceof ASMifiable) { ((ASMifiable)a).asmify(buf, "fieldAttrs" + n, null); if (n > 1) { buf.append("fieldAttrs" + (n - 1) + " = fieldAttrs" + n + ";\n"); } n++; } else { buf.append("// WARNING! skipped non standard field attribute of type "); buf.append(a.type).append("\n"); } a = a.next; } } buf.append("cw.visitField("); appendAccess(access | ACCESS_FIELD); buf.append(", "); appendConstant(buf, name); buf.append(", "); appendConstant(buf, desc); buf.append(", "); appendConstant(buf, value); if (n==1) { buf.append(", null);\n\n"); } else { buf.append(", fieldAttrs1);\n"); buf.append("}\n\n"); } text.add(buf.toString()); } public CodeVisitor visitMethod ( final int access, final String name, final String desc, final String[] exceptions, final Attribute attrs) { buf.setLength(0); buf.append("{\n"); int n = 1; if (attrs != null) { buf.append("// METHOD ATTRIBUTES\n"); Attribute a = attrs; while (a != null) { if (a instanceof ASMifiable) { ((ASMifiable)a).asmify(buf, "methodAttrs" + n, null); if (n > 1) { buf.append("methodAttrs" + (n - 1) + ".next = methodAttrs" + n + ";\n"); } n++; } else { buf.append("// WARNING! skipped non standard method attribute of type "); buf.append(a.type).append("\n"); } a = a.next; } } buf.append("cv = cw.visitMethod("); appendAccess(access); buf.append(", "); appendConstant(buf, name); buf.append(", "); appendConstant(buf, desc); buf.append(", "); if (exceptions != null && exceptions.length > 0) { buf.append("new String[] {"); for (int i = 0; i < exceptions.length; ++i) { buf.append(i == 0 ? " " : ", "); appendConstant(buf, exceptions[i]); } buf.append(" }"); } else { buf.append("null"); } if (n==1) { buf.append(", null);\n"); } else { buf.append(", methodAttrs1);\n"); } text.add(buf.toString()); PrintCodeVisitor pcv = new ASMifierCodeVisitor(); text.add(pcv.getText()); text.add("}\n"); return pcv; } public void visitAttribute (final Attribute attr) { buf.setLength(0); if (attr instanceof ASMifiable) { buf.append("{\n"); buf.append("// CLASS ATRIBUTE\n"); ((ASMifiable)attr).asmify(buf, "attr", null); buf.append("cw.visitAttribute(attr);\n"); buf.append("}\n"); } else { buf.append("// WARNING! skipped a non standard class attribute of type \""); buf.append(attr.type).append("\"\n"); } text.add(buf.toString()); } public void visitEnd () { text.add("cw.visitEnd();\n\n"); // text.add("FileOutputStream os = new FileOutputStream(\"Dumped.class\");\n"); // text.add("os.write(cw.toByteArray());\n"); // text.add("os.close();\n"); text.add("return cw.toByteArray();\n"); text.add("}\n"); text.add("}\n"); super.visitEnd(); } /** * Appends a string representation of the given access modifiers to {@link * #buf buf}. * * @param access some access modifiers. */ void appendAccess (final int access) { boolean first = true; if ((access & Constants.ACC_PUBLIC) != 0) { buf.append("ACC_PUBLIC"); first = false; } if ((access & Constants.ACC_PRIVATE) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_PRIVATE"); first = false; } if ((access & Constants.ACC_PROTECTED) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_PROTECTED"); first = false; } if ((access & Constants.ACC_FINAL) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_FINAL"); first = false; } if ((access & Constants.ACC_STATIC) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_STATIC"); first = false; } if ((access & Constants.ACC_SYNCHRONIZED) != 0) { if (!first) { buf.append(" + "); } if ((access & ACCESS_CLASS) != 0) { buf.append("ACC_SUPER"); } else { buf.append("ACC_SYNCHRONIZED"); } first = false; } if ((access & Constants.ACC_VOLATILE) != 0 && (access & ACCESS_FIELD) != 0 ) { if (!first) { buf.append(" + "); } buf.append("ACC_VOLATILE"); first = false; } if ((access & Constants.ACC_BRIDGE) != 0 && (access & ACCESS_CLASS) == 0 && (access & ACCESS_FIELD) == 0) { if (!first) { buf.append(" + "); } buf.append("ACC_BRIDGE"); first = false; } if ((access & Constants.ACC_VARARGS) != 0 && (access & ACCESS_CLASS) == 0 && (access & ACCESS_FIELD) == 0) { if (!first) { buf.append(" + "); } buf.append("ACC_VARARGS"); first = false; } if ((access & Constants.ACC_TRANSIENT) != 0 && (access & ACCESS_FIELD) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_TRANSIENT"); first = false; } if ((access & Constants.ACC_NATIVE) != 0 && (access & ACCESS_CLASS) == 0 && (access & ACCESS_FIELD) == 0) { if (!first) { buf.append(" + "); } buf.append("ACC_NATIVE"); first = false; } if ((access & Constants.ACC_ENUM) != 0 && ((access & ACCESS_CLASS) != 0 || (access & ACCESS_FIELD) != 0 || (access & ACCESS_INNER) != 0)) { if (!first) { buf.append(" + "); } buf.append("ACC_ENUM"); first = false; } if ((access & Constants.ACC_ANNOTATION) != 0 && ((access & ACCESS_CLASS) != 0)) { if (!first) { buf.append(" + "); } buf.append("ACC_ANNOTATION"); first = false; } if ((access & Constants.ACC_ABSTRACT) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_ABSTRACT"); first = false; } if ((access & Constants.ACC_INTERFACE) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_INTERFACE"); first = false; } if ((access & Constants.ACC_STRICT) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_STRICT"); first = false; } if ((access & Constants.ACC_SYNTHETIC) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_SYNTHETIC"); first = false; } if ((access & Constants.ACC_DEPRECATED) != 0) { if (!first) { buf.append(" + "); } buf.append("ACC_DEPRECATED"); first = false; } if (first) { buf.append("0"); } } /** * Appends a string representation of the given constant to the given buffer. * * @param buf a string buffer. * @param cst an {@link java.lang.Integer Integer}, {@link java.lang.Float * Float}, {@link java.lang.Long Long}, {@link java.lang.Double Double} * or {@link String String} object. May be <tt>null</tt>. */ static void appendConstant (final StringBuffer buf, final Object cst) { if (cst == null) { buf.append("null"); } else if (cst instanceof String) { String s = (String)cst; buf.append("\""); for (int i = 0; i < s.length(); ++i) { char c = s.charAt(i); if (c == '\n') { buf.append("\\n"); } else if (c == '\r') { buf.append("\\r"); } else if (c == '\\') { buf.append("\\\\"); } else if (c == '"') { buf.append("\\\""); } else if( c<0x20 || c>0x7f) { buf.append( "\\u"); if( c<0x10) { buf.append( "000"); } else if( c<0x100) { buf.append( "00"); } else if( c<0x1000) { buf.append( "0"); } buf.append( Integer.toString( c, 16)); } else { buf.append(c); } } buf.append("\""); } else if (cst instanceof Type) { buf.append("Type.getType(\""); buf.append(((Type)cst).getDescriptor()); buf.append("\")"); } else if (cst instanceof Integer) { buf.append("new Integer(") .append(cst) .append(")"); } else if (cst instanceof Float) { buf.append("new Float(") .append(cst) .append("F)"); } else if (cst instanceof Long) { buf.append("new Long(") .append(cst) .append("L)"); } else if (cst instanceof Double) { buf.append("new Double(") .append(cst) .append(")"); } } }
package com.griddynamics.jagger.reporting.interval; public class CalculatedIntervalSizeProvider implements IntervalSizeProvider { private final int intervalsCount; public CalculatedIntervalSizeProvider(int intervalsCount) { this.intervalsCount = intervalsCount; } @Override public int getIntervalSize(long minTime, long maxTime) { return (int) Math.ceil((1d * maxTime - minTime) / intervalsCount); } }
package info.tregmine.database.db; import info.tregmine.Tregmine; import info.tregmine.database.*; import java.sql.Connection; import java.sql.SQLException; public class DBContext implements IContext { private Connection conn; private Tregmine plugin; public DBContext(Connection conn, Tregmine instance) { this.conn = conn; this.plugin = instance; } public Connection getConnection() { return conn; } @Override public void close() { if (conn != null) { try { conn.close(); } catch (SQLException e) { } } } @Override public IHomeDAO getHomeDAO() { return new DBHomeDAO(conn); } @Override public IInventoryDAO getInventoryDAO() { return new DBInventoryDAO(conn); } @Override public IItemDAO getItemDAO() { return new DBItemDAO(conn); } @Override public ILogDAO getLogDAO() { return new DBLogDAO(conn); } @Override public IMotdDAO getMotdDAO() { return new DBMotdDAO(conn); } @Override public IPlayerDAO getPlayerDAO() { return new DBPlayerDAO(conn, plugin); } @Override public IPlayerReportDAO getPlayerReportDAO() { return new DBPlayerReportDAO(conn); } @Override public ITradeDAO getTradeDAO() { return new DBTradeDAO(conn); } @Override public IWalletDAO getWalletDAO() { return new DBWalletDAO(conn); } @Override public IWarpDAO getWarpDAO() { return new DBWarpDAO(conn); } @Override public IZonesDAO getZonesDAO() { return new DBZonesDAO(conn); } @Override public IMentorLogDAO getMentorLogDAO() { return new DBMentorLogDAO(conn); } @Override public IFishyBlockDAO getFishyBlockDAO() { return new DBFishyBlockDAO(conn); } @Override public IBlessedBlockDAO getBlessedBlockDAO() { return new DBBlessedBlockDAO(conn); } @Override public IEnchantmentDAO getEnchantmentDAO() { return new DBEnchantmentDAO(conn); } @Override public IBankDAO getBankDAO() { return new DBBankDAO(conn); } @Override public IMiscDAO getMiscDAO() { return new DBMiscDAO(conn); } }
package org.opencms.workplace.editors; import org.opencms.db.CmsUserSettings; import org.opencms.file.CmsResource; import org.opencms.file.CmsResourceFilter; import org.opencms.i18n.CmsMessageContainer; import org.opencms.jsp.CmsJspActionElement; import org.opencms.main.CmsException; import org.opencms.main.CmsLog; import org.opencms.main.OpenCms; import org.opencms.security.CmsPermissionSet; import org.opencms.security.CmsRole; import org.opencms.security.CmsRoleViolationException; import org.opencms.workplace.CmsDialog; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; /** * Base class for all editors that turns of time warp deletion inherited from * <code>{@link org.opencms.workplace.CmsWorkplace}</code>.<p> * * @since 6.0.0 */ public class CmsEditorBase extends CmsDialog { /** The log object for this class. */ private static final Log LOG = CmsLog.getLog(CmsEditorBase.class); /** * Public constructor.<p> * * @param jsp an initialized JSP action element */ public CmsEditorBase(CmsJspActionElement jsp) { super(jsp); } @Override protected boolean checkResourcePermissions( CmsPermissionSet required, boolean neededForFolder, CmsMessageContainer errorMessage) { boolean hasPermissions = false; try { CmsResource res; if (neededForFolder) { res = getCms().readResource(CmsResource.getParentFolder(getParamResource()), CmsResourceFilter.ALL); } else { res = getCms().readResource(getParamResource(), CmsResourceFilter.ALL); } hasPermissions = getCms().hasPermissions(res, required, false, CmsResourceFilter.ALL) && (OpenCms.getRoleManager().hasRoleForResource( getCms(), CmsRole.ELEMENT_AUTHOR, getCms().getSitePath(res)) || OpenCms.getRoleManager().hasRoleForResource( getCms(), CmsRole.PROJECT_MANAGER, getCms().getSitePath(res)) || OpenCms.getRoleManager().hasRoleForResource( getCms(), CmsRole.ACCOUNT_MANAGER, getCms().getSitePath(res))); } catch (CmsException e) { // should usually never happen if (LOG.isInfoEnabled()) { LOG.info(e); } } if (!hasPermissions) { // store the error message in the users session getSettings().setErrorMessage(errorMessage); } return hasPermissions; } /** * Checks that the current user is a workplace user.<p> * * @throws CmsRoleViolationException if the user does not have the required role */ @Override protected void checkRole() throws CmsRoleViolationException { OpenCms.getRoleManager().checkRole(getCms(), CmsRole.EDITOR); } /** * @see org.opencms.workplace.CmsWorkplace#initTimeWarp(org.opencms.db.CmsUserSettings, javax.servlet.http.HttpSession) */ @Override protected void initTimeWarp(CmsUserSettings settings, HttpSession session) { // overridden to avoid deletion of the configured time warp: // this is triggered by editors and in auto time warping a direct edit // must not delete a potential auto warped request time } }
package inpro.incremental.unit; import inpro.annotation.Label; import inpro.incremental.transaction.ComputeHMMFeatureVector; import inpro.synthesis.MaryAdapter4internal; import inpro.synthesis.hts.FullPFeatureFrame; import inpro.synthesis.hts.FullPStream; import inpro.synthesis.hts.VocodingFramePostProcessor; import inpro.synthesis.hts.PHTSParameterGeneration; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import java.util.Locale; import marytts.features.FeatureVector; import marytts.htsengine.HMMData; import marytts.htsengine.HTSModel; import org.apache.log4j.Logger; public class SysSegmentIU extends SegmentIU { private static Logger logger = Logger.getLogger(SysSegmentIU.class); Label originalLabel; public HMMData hmmdata = null; public FeatureVector fv = null; public HTSModel legacyHTSmodel = null; HTSModel htsModel; List<FullPFeatureFrame> hmmSynthesisFeatures; public double pitchShiftInCent = 0.0; private VocodingFramePostProcessor vocodingFramePostProcessor = null; /** the state of delivery that this unit is in */ Progress progress = Progress.UPCOMING; /** the number of frames that this segment has already been going on */ int realizedDurationInSynFrames = 0; boolean awaitContinuation; // used to mark that a continuation will follow, even though no fSLL exists yet. public SysSegmentIU(Label l, HTSModel htsModel, FeatureVector fv, HMMData hmmdata, List<FullPFeatureFrame> featureFrames) { super(l); this.fv = fv; this.hmmdata = hmmdata; this.hmmSynthesisFeatures = featureFrames; if (htsModel != null) this.setHTSModel(htsModel); } public SysSegmentIU(Label l) { this(l, null, null, null, null); } @Override public StringBuilder toMbrolaLine() { StringBuilder sb = l.toMbrola(); /* TODO: regenerate pitch marks from hmmSynthesisFrames * for (PitchMark pm : pitchMarks) { sb.append(" "); sb.append(pm.toString()); } */ sb.append("\n"); return sb; } public void setHmmSynthesisFrames(List<FullPFeatureFrame> hmmSynthesisFeatures) { this.hmmSynthesisFeatures = hmmSynthesisFeatures; assert Math.abs(hmmSynthesisFeatures.size() - duration() * 200) < 0.001 : "" + hmmSynthesisFeatures.size() + " != " + (duration() * 200) + " in " + toString(); } /** the duration of this segment in multiples of 5 ms */ public int durationInSynFrames() { return (int) Math.round(duration() * FullPStream.FRAMES_PER_SECOND / Double.valueOf(System.getProperty("inpro.tts.tempoScaling", "1.0"))); } public double originalDuration() { if (originalLabel != null) return originalLabel.getDuration(); else return duration(); } /** adds fSLL, and allows continuation of synthesis */ @Override public synchronized void addNextSameLevelLink(IU iu) { super.addNextSameLevelLink(iu); awaitContinuation = false; notifyAll(); } /** * tell this segment that it will be followed by more input later on * @return whether a continuation is possible (i.e., the segment hasn't been completed yet */ public synchronized boolean setAwaitContinuation(boolean b) { awaitContinuation = b; notifyAll(); return !isCompleted(); } // awaits the awaitContinuation field to be cleared private synchronized void awaitContinuation() { while (awaitContinuation) { try { wait(); } catch (InterruptedException e) {} } } /** helper, append HMM if possible, return emission length */ private static int appendSllHtsModel(List<HTSModel> hmms, IU sll) { int length = 0; if (sll != null && sll instanceof SysSegmentIU) { HTSModel hmm = ((SysSegmentIU) sll).legacyHTSmodel; hmms.add(hmm); length = hmm.getTotalDur(); } return length; } private static PHTSParameterGeneration paramGen = null; HTSModel getHTSModel() { if (htsModel != null) return htsModel; htsModel = generateHTSModel(); if (htsModel != null) { // IncrementalCARTTest.same(htsModel, legacyHTSmodel); return htsModel; } else return legacyHTSmodel; } HTSModel generateHTSModel() { FeatureVector fv = ComputeHMMFeatureVector.featuresForSegmentIU(this); double prevErr = getSameLevelLink() != null & getSameLevelLink() instanceof SysSegmentIU ? ((SysSegmentIU) getSameLevelLink()).getHTSModel().getDurError() : 0f; HTSModel htsModel = hmmdata.getCartTreeSet().generateHTSModel(hmmdata, hmmdata.getFeatureDefinition(), fv, prevErr); return htsModel; } // synthesizes private void generateParameterFrames() { assert this.legacyHTSmodel != null; HTSModel htsModel = getHTSModel(); List<HTSModel> localHMMs = new ArrayList<HTSModel>(); /** iterates over left/right context IUs */ SysSegmentIU contextIU = this; /** size of left context; increasing this may improve synthesis performance at the cost of computational effort */ int maxPredecessors = 7; // initialize contextIU to the very first IU in the list while (contextIU.getSameLevelLink() != null && maxPredecessors > 0) { contextIU = (SysSegmentIU) contextIU.getSameLevelLink(); maxPredecessors } // now traverse the predecessor IUs and add their models to the list int start = 0; while (contextIU != this) { start += appendSllHtsModel(localHMMs, contextIU); contextIU = (SysSegmentIU) contextIU.getNextSameLevelLink(); } localHMMs.add(htsModel); int length = htsModel.getTotalDur(); awaitContinuation(); /** deal with the right context units; increasing this may improve synthesis quality at the cost of computaitonal effort */ int maxSuccessors = 3; contextIU = (SysSegmentIU) getNextSameLevelLink(); while (contextIU != null && maxSuccessors > 0) { appendSllHtsModel(localHMMs, contextIU); contextIU = (SysSegmentIU) getNextSameLevelLink(); maxSuccessors } // make sure we have a paramGenerator if (paramGen == null) { paramGen = MaryAdapter4internal.getNewParamGen(); } FullPStream pstream = paramGen.buildFullPStreamFor(localHMMs); hmmSynthesisFeatures = new ArrayList<FullPFeatureFrame>(length); for (int i = start; i < start + length; i++) hmmSynthesisFeatures.add(pstream.getFullFrame(i)); //assert htsModel.getNumVoiced() == pitchMarks.size(); } public FullPFeatureFrame getHMMSynthesisFrame(int req) { if (hmmSynthesisFeatures == null) { generateParameterFrames(); } assert req >= 0; setProgress(Progress.ONGOING); assert req < durationInSynFrames() || req == 0; // req = Math.max(req, durationInSynFrames() - 1); int dur = durationInSynFrames(); // the duration in frames (= the number of frames that should be there) int fra = hmmSynthesisFeatures.size(); // the number of frames available // just repeat/drop frames as necessary if the amount of frames available is not right int frameNumber = (int) (req * (fra / (double) dur)); FullPFeatureFrame frame = hmmSynthesisFeatures.get(frameNumber); if (req == dur - 1) { // last frame setProgress(Progress.COMPLETED); // logger.debug("completed " + deepToString()); logger.debug("completed " + toMbrolaLine()); } realizedDurationInSynFrames++; frame.shiftlf0Par(pitchShiftInCent); // check whether we've been requested to wait for our continuation if (realizedDurationInSynFrames == durationInSynFrames()) awaitContinuation(); if (vocodingFramePostProcessor != null) return vocodingFramePostProcessor.postProcess(frame); else return frame; } private void setProgress(Progress p) { if (p != this.progress) { this.progress = p; notifyListeners(); if (p == Progress.COMPLETED && getNextSameLevelLink() != null) { getNextSameLevelLink().notifyListeners(); } } } /** * stretch the current segment by a given factor. * NOTE: as time is discrete (in 5ms steps), the stretching factor that is actually applied * may differ from the requested factor. * @param factor larger than 1 to lengthen, smaller than 1 to shorten; must be larger than 0 * @return the actual duration that has been applied */ public double stretch(double factor) { assert factor > 0f; double newDuration = duration() * factor; return setNewDuration(newDuration); } public double stretchFromOriginal(double factor) { assert factor > 0f; double newDuration = originalDuration() * factor; return setNewDuration(newDuration); } public void setVocodingFramePostProcessor(VocodingFramePostProcessor postProcessor) { vocodingFramePostProcessor = postProcessor; } /** * change the synthesis frames' pitch curve to attain the given pitch in the final pitch * in a smooth manner * @param finalPitch the log pitch to be reached in the final synthesis frame */ public void attainPitch(double finalPitch) { ListIterator<FullPFeatureFrame> revFrames = hmmSynthesisFeatures.listIterator(hmmSynthesisFeatures.size()); // finalPitch = Math.log(finalPitch); double difference = finalPitch - revFrames.previous().getlf0Par(); double adjustmentPerFrame = difference / hmmSynthesisFeatures.size(); System.err.println("attaining pitch in " + toString() + " by " + difference); revFrames.next(); // adjust frames in reverse order (in case this segment is already being synthesized) for (; revFrames.hasPrevious(); ) { FullPFeatureFrame frame = revFrames.previous(); frame.setlf0Par(frame.getlf0Par() - difference); difference -= adjustmentPerFrame; } } /** * set a new duration of this segment; if this segment is already ongoing, the * resulting duration cannot be shortend to less than what has already been going on (obviously, we can't revert the past) * @return the actual new duration (multiple of 5ms) */ public synchronized double setNewDuration(double d) { assert d >= 0; d = Math.max(d, realizedDurationInSynFrames / 200.f); if (originalLabel == null) originalLabel = this.l; Label oldLabel = this.l; // change duration to conform to 5ms limit double newDuration = Math.round(d * 200.f) / 200.f; shiftBy(newDuration - duration(), true); // correct this' label to start where it used to start (instead of the shifted version) this.l = new Label(oldLabel.getStart(), this.l.getEnd(), this.l.getLabel()); return newDuration; } /** shift the start and end times of this (and possibly all following SysSegmentIUs */ public void shiftBy(double offset, boolean recurse) { super.shiftBy(offset, recurse); } @Override public Progress getProgress() { return progress; } /** SysSegmentIUs may have a granularity finer than 10 ms (5ms) */ @Override public String toLabelLine() { return String.format(Locale.US, "%.3f\t%.3f\t%s", startTime(), endTime(), toPayLoad()); } public void setHTSModel(HTSModel hmm) { legacyHTSmodel = hmm; } /** copy all data necessary for synthesis -- i.e. the htsModel and pitchmarks */ public void copySynData(SysSegmentIU newSeg) { assert payloadEquals(newSeg); this.l = newSeg.l; setHTSModel(newSeg.legacyHTSmodel); } }
package edu.duke.cabig.c3pr.web.registration.tabs; import edu.duke.cabig.c3pr.web.registration.StudySubjectWrapper; public class RegistrationHistoryChartTab<C extends StudySubjectWrapper> extends RegistrationTab<C> { public RegistrationHistoryChartTab() { super("Study Subject Timeline", "Study Subject Timeline", "registration/reg_history_timeline"); } }
package com.exedio.copernica; import net.sourceforge.jwebunit.TestContext; import net.sourceforge.jwebunit.WebTestCase; public class AbstractWebTest extends WebTestCase { public AbstractWebTest(String name) { super(name); } public void setUp() throws Exception { super.setUp(); final TestContext ctx = getTestContext(); ctx.setBaseUrl("http://127.0.0.1:8080/copetest-hsqldb/"); ctx.setAuthorization("admin", "nimda"); beginAt("admin.jsp"); submit("CREATE"); } public void tearDown() throws Exception { beginAt("admin.jsp"); submit("DROP"); super.tearDown(); } }
package io.flutter.run.test; import com.intellij.icons.AllIcons; import com.intellij.psi.PsiElement; import com.jetbrains.lang.dart.psi.DartCallExpression; import com.jetbrains.lang.dart.psi.DartFile; import com.jetbrains.lang.dart.psi.DartStringLiteralExpression; import io.flutter.FlutterUtils; import io.flutter.dart.DartSyntax; import io.flutter.run.FlutterRunConfigurationProducer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.Arrays; import java.util.List; public class TestConfigUtils { enum TestType { GROUP(AllIcons.RunConfigurations.TestState.Run_run, "group"), MAIN(AllIcons.RunConfigurations.TestState.Run_run) { @NotNull String getTooltip(@NotNull PsiElement element) { return "Run Tests"; } }, SINGLE(AllIcons.RunConfigurations.TestState.Run, "test" //TODO(pq): add to enable support for widget tests (pending fixing location issues). //, "testWidgets" ); @NotNull private final Icon myIcon; private final List<String> myTestFunctionNames; TestType(@NotNull Icon icon, String... testFunctionNames) { myIcon = icon; myTestFunctionNames = Arrays.asList(testFunctionNames); } @NotNull Icon getIcon() { return myIcon; } boolean matchesFunction(@NotNull PsiElement element) { return myTestFunctionNames.stream().anyMatch(name -> DartSyntax.isCallToFunctionNamed(element, name)); } @NotNull String getTooltip(@NotNull PsiElement element) { final String testName = findTestName(element); if (testName != null && !testName.isEmpty()) { return "Run '" + testName + "'"; } return "Run Test"; } @Nullable public DartCallExpression findCorrespondingCall(@NotNull PsiElement element) { for (String name : myTestFunctionNames) { final DartCallExpression call = DartSyntax.findEnclosingFunctionCall(element, name); if (call != null) { return call; } } return null; } @Nullable public static DartCallExpression findTestCall(@NotNull PsiElement element) { for (TestType type : TestType.values()) { final DartCallExpression call = type.findCorrespondingCall(element); if (call != null) return call; } return null; } } @Nullable public static TestType asTestCall(@NotNull PsiElement element) { final DartFile file = FlutterRunConfigurationProducer.getDartFile(element); if (file != null && FlutterUtils.isInTestDir(file)) { // Named tests. for (TestType type : TestType.values()) { if (type.matchesFunction(element)) return type; } // Main. if (DartSyntax.isFunctionDeclarationNamed(element, "main")) return TestType.MAIN; } return null; } /** * Returns the name of the test containing this element, or null if it can't be calculated. */ @Nullable public static String findTestName(@Nullable PsiElement elt) { if (elt == null) return null; final DartCallExpression call = TestType.findTestCall(elt); if (call == null) return null; final DartStringLiteralExpression lit = DartSyntax.getArgument(call, 0, DartStringLiteralExpression.class); if (lit == null) return null; return DartSyntax.unquote(lit); } }
package com.ibm.watson.developer_cloud.compare_comply.v1; import com.ibm.watson.developer_cloud.compare_comply.v1.model.AddFeedbackOptions; import com.ibm.watson.developer_cloud.compare_comply.v1.model.BatchStatus; import com.ibm.watson.developer_cloud.compare_comply.v1.model.Batches; import com.ibm.watson.developer_cloud.compare_comply.v1.model.ClassifyElementsOptions; import com.ibm.watson.developer_cloud.compare_comply.v1.model.ClassifyReturn; import com.ibm.watson.developer_cloud.compare_comply.v1.model.CompareDocumentsOptions; import com.ibm.watson.developer_cloud.compare_comply.v1.model.CompareReturn; import com.ibm.watson.developer_cloud.compare_comply.v1.model.ConvertToHtmlOptions; import com.ibm.watson.developer_cloud.compare_comply.v1.model.CreateBatchOptions; import com.ibm.watson.developer_cloud.compare_comply.v1.model.DeleteFeedbackOptions; import com.ibm.watson.developer_cloud.compare_comply.v1.model.ExtractTablesOptions; import com.ibm.watson.developer_cloud.compare_comply.v1.model.FeedbackDataInput; import com.ibm.watson.developer_cloud.compare_comply.v1.model.FeedbackList; import com.ibm.watson.developer_cloud.compare_comply.v1.model.FeedbackReturn; import com.ibm.watson.developer_cloud.compare_comply.v1.model.GetBatchOptions; import com.ibm.watson.developer_cloud.compare_comply.v1.model.GetFeedback; import com.ibm.watson.developer_cloud.compare_comply.v1.model.GetFeedbackOptions; import com.ibm.watson.developer_cloud.compare_comply.v1.model.HTMLReturn; import com.ibm.watson.developer_cloud.compare_comply.v1.model.Location; import com.ibm.watson.developer_cloud.compare_comply.v1.model.OriginalLabelsIn; import com.ibm.watson.developer_cloud.compare_comply.v1.model.ShortDoc; import com.ibm.watson.developer_cloud.compare_comply.v1.model.TableReturn; import com.ibm.watson.developer_cloud.compare_comply.v1.model.UpdateBatchOptions; import com.ibm.watson.developer_cloud.compare_comply.v1.model.UpdatedLabelsIn; import com.ibm.watson.developer_cloud.http.HttpMediaType; import com.ibm.watson.developer_cloud.util.RetryRunner; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.io.File; import java.io.FileNotFoundException; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * Integration tests for Compare and Comply. */ @RunWith(RetryRunner.class) public class CompareComplyServiceIT extends CompareComplyServiceTest { private static final String RESOURCE = "src/test/resources/compare_comply/"; private static final File CONTRACT_A = new File(RESOURCE + "contract-a.pdf"); private static final File CONTRACT_B = new File(RESOURCE + "contract-b.pdf"); private static final File TABLE_FILE = new File(RESOURCE + "test-table.pdf"); private static final File INPUT_CREDENTIALS_FILE = new File(RESOURCE + "cloud-object-storage-credentials-input.json"); private static final File OUTPUT_CREDENTIALS_FILE = new File(RESOURCE + "cloud-object-storage-credentials-output.json"); private CompareComply service; @Override @Before public void setUp() throws Exception { super.setUp(); this.service = getService(); } @Test public void testConvertToHtml() throws FileNotFoundException { ConvertToHtmlOptions convertToHtmlOptions = new ConvertToHtmlOptions.Builder() .file(CONTRACT_A) .fileContentType(HttpMediaType.APPLICATION_PDF) .build(); HTMLReturn response = service.convertToHtml(convertToHtmlOptions).execute(); System.out.println(response); } @Test public void testClassifyElements() throws FileNotFoundException { ClassifyElementsOptions classifyElementsOptions = new ClassifyElementsOptions.Builder() .file(CONTRACT_A) .build(); ClassifyReturn response = service.classifyElements(classifyElementsOptions).execute(); System.out.println(response); } @Test public void testExtractTables() throws FileNotFoundException { ExtractTablesOptions extractTablesOptions = new ExtractTablesOptions.Builder() .file(TABLE_FILE) .build(); TableReturn response = service.extractTables(extractTablesOptions).execute(); System.out.println(response); } @Test public void testCompareDocuments() throws FileNotFoundException { CompareDocumentsOptions compareDocumentsOptions = new CompareDocumentsOptions.Builder() .file1(CONTRACT_A) .file1ContentType(HttpMediaType.APPLICATION_PDF) .file2(CONTRACT_B) .file2ContentType(HttpMediaType.APPLICATION_PDF) .build(); CompareReturn response = service.compareDocuments(compareDocumentsOptions).execute(); System.out.println(response); } @Test public void testFeedbackOperations() { String userId = "lp_java"; String comment = "could be better"; String text = "This is some text from a contract about something."; ShortDoc shortDoc = new ShortDoc(); Location location = new Location(); location.setBegin(0L); location.setEnd(1L); OriginalLabelsIn originalLabelsIn = new OriginalLabelsIn(); UpdatedLabelsIn updatedLabelsIn = new UpdatedLabelsIn(); FeedbackDataInput feedbackDataInput = new FeedbackDataInput(); feedbackDataInput.setDocument(shortDoc); feedbackDataInput.setLocation(location); feedbackDataInput.setText(text); feedbackDataInput.setOriginalLabels(originalLabelsIn); feedbackDataInput.setUpdatedLabels(updatedLabelsIn); feedbackDataInput.setFeedbackType("element_classification"); AddFeedbackOptions addFeedbackOptions = new AddFeedbackOptions.Builder() .userId(userId) .comment(comment) .feedbackData(feedbackDataInput) .build(); FeedbackReturn feedbackReturn = service.addFeedback(addFeedbackOptions).execute(); String feedbackId = feedbackReturn.getFeedbackId(); GetFeedbackOptions getFeedbackOptions = new GetFeedbackOptions.Builder() .feedbackId(feedbackId) .build(); GetFeedback getFeedback = service .getFeedback(getFeedbackOptions) .addHeader("x-watson-metadata", "customer_id=sdk-test-customer-id") .execute(); assertEquals(comment, getFeedback.getComment()); DeleteFeedbackOptions deleteFeedbackOptions = new DeleteFeedbackOptions.Builder() .feedbackId(feedbackId) .build(); service.deleteFeedback(deleteFeedbackOptions).execute(); FeedbackList feedbackList = service.listFeedback().execute(); List<GetFeedback> allFeedback = feedbackList.getFeedback(); boolean successfullyDeleted = true; for (GetFeedback feedback : allFeedback) { if (feedback.getFeedbackId().equals(feedbackId)) { successfullyDeleted = false; break; } } assertTrue(successfullyDeleted); } @Test public void testBatchOperations() throws FileNotFoundException { String bucketLocation = "us-south"; String inputBucketName = "compare-comply-integration-test-bucket-input"; String outputBucketName = "compare-comply-integration-test-bucket-output"; CreateBatchOptions createBatchOptions = new CreateBatchOptions.Builder() .function(CreateBatchOptions.Function.ELEMENT_CLASSIFICATION) .inputBucketLocation(bucketLocation) .inputBucketName(inputBucketName) .inputCredentialsFile(INPUT_CREDENTIALS_FILE) .outputBucketLocation(bucketLocation) .outputBucketName(outputBucketName) .outputCredentialsFile(OUTPUT_CREDENTIALS_FILE) .build(); BatchStatus createBatchResponse = service.createBatch(createBatchOptions).execute(); String batchId = createBatchResponse.getBatchId(); GetBatchOptions getBatchOptions = new GetBatchOptions.Builder() .batchId(batchId) .build(); BatchStatus getBatchResponse = service.getBatch(getBatchOptions).execute(); assertNotNull(getBatchResponse); UpdateBatchOptions updateBatchOptions = new UpdateBatchOptions.Builder() .batchId(batchId) .action(UpdateBatchOptions.Action.RESCAN) .build(); BatchStatus updateBatchResponse = service.updateBatch(updateBatchOptions).execute(); assertTrue(updateBatchResponse.getCreated().before(updateBatchResponse.getUpdated())); Batches listBatchesResponse = service.listBatches().execute(); List<BatchStatus> batches = listBatchesResponse.getBatches(); boolean batchFound = false; for (BatchStatus batch : batches) { if (batch.getBatchId().equals(batchId)) { batchFound = true; break; } } assertTrue(batchFound); } }
package arjdbc.h2; import java.sql.Connection; import java.sql.SQLException; import org.jruby.Ruby; import org.jruby.RubyClass; import org.jruby.runtime.ObjectAllocator; import org.jruby.runtime.builtin.IRubyObject; /** * * @author nicksieger */ //@org.jruby.anno.JRubyClass(name = "ActiveRecord::ConnectionAdapters::JdbcConnection") public class H2RubyJdbcConnection extends arjdbc.jdbc.RubyJdbcConnection { private static final long serialVersionUID = -2652911264521657428L; public H2RubyJdbcConnection(Ruby runtime, RubyClass metaClass) { super(runtime, metaClass); } public static RubyClass createH2JdbcConnectionClass(Ruby runtime, RubyClass jdbcConnection) { RubyClass clazz = getConnectionAdapters(runtime). defineClassUnder("H2JdbcConnection", jdbcConnection, ALLOCATOR); clazz.defineAnnotatedMethods(H2RubyJdbcConnection.class); return clazz; } public static RubyClass load(final Ruby runtime) { RubyClass jdbcConnection = getJdbcConnectionClass(runtime); return createH2JdbcConnectionClass(runtime, jdbcConnection); } protected static ObjectAllocator ALLOCATOR = new ObjectAllocator() { public IRubyObject allocate(Ruby runtime, RubyClass klass) { return new H2RubyJdbcConnection(runtime, klass); } }; /** * H2 supports schemas. */ @Override protected boolean databaseSupportsSchemas() { return true; } @Override protected String caseConvertIdentifierForJdbc(final Connection connection, final String value) { if ( value == null ) return null; return value.toUpperCase(); } }
package org.apache.log4j; import java.io.IOException; import java.io.Writer; import java.util.HashMap; import org.apache.log4j.pattern.PatternConverter; import org.apache.log4j.pattern.PatternParser; import org.apache.log4j.spi.LoggingEvent; // Contributors: Nelson Minar <nelson@monkey.org> // Anders Kristensen <akristensen@dynamicsoft.com> /** * <p>A flexible layout configurable with pattern string. The goal of this class * is to {@link #format format} a {@link LoggingEvent} and return the results * in a {#link StringBuffer}. The format of the result depensd on the * <em>conversion pattern</em>. * <p> * * <p>The conversion pattern is closely related to the conversion * pattern of the printf function in C. A conversion pattern is * composed of literal text and format control expressions called * <em>conversion specifiers</em>. * * <p><i>Note that you are free to insert any literal text within the * conversion pattern.</i> * </p> <p>Each conversion specifier starts with a percent sign (%) and is followed by optional <em>format modifiers</em> and a <em>conversion character</em>. The conversion character specifies the type of data, e.g. category, priority, date, thread name. The format modifiers control such things as field width, padding, left and right justification. The following is a simple example. <p>Let the conversion pattern be <b>"%-5p [%t]: %m%n"</b> and assume that the log4j environment was set to use a PatternLayout. Then the statements <pre> Category root = Category.getRoot(); root.debug("Message 1"); root.warn("Message 2"); </pre> would yield the output <pre> DEBUG [main]: Message 1 WARN [main]: Message 2 </pre> <p>Note that there is no explicit separator between text and conversion specifiers. The pattern parser knows when it has reached the end of a conversion specifier when it reads a conversion character. In the example above the conversion specifier <b>%-5p</b> means the priority of the logging event should be left justified to a width of five characters. The recognized conversion characters are <p> <table border="1" CELLPADDING="8"> <th>Conversion Character</th> <th>Effect</th> <tr> <td align=center><b>c</b></td> <td>Used to output the category of the logging event. The category conversion specifier can be optionally followed by <em>precision specifier</em>, that is a decimal constant in brackets. <p>If a precision specifier is given, then only the corresponding number of right most components of the category name will be printed. By default the category name is printed in full. <p>For example, for the category name "a.b.c" the pattern <b>%c{2}</b> will output "b.c". </td> </tr> <tr> <td align=center><b>C</b></td> <td>Used to output the fully qualified class name of the caller issuing the logging request. This conversion specifier can be optionally followed by <em>precision specifier</em>, that is a decimal constant in brackets. <p>If a precision specifier is given, then only the corresponding number of right most components of the class name will be printed. By default the class name is output in fully qualified form. <p>For example, for the class name "org.apache.xyz.SomeClass", the pattern <b>%C{1}</b> will output "SomeClass". <p><b>WARNING</b> Generating the caller class information is slow. Thus, it's use should be avoided unless execution speed is not an issue. </td> </tr> <tr> <td align=center><b>d</b></td> <td>Used to output the date of the logging event. The date conversion specifier may be followed by a <em>date format specifier</em> enclosed between braces. For example, <b>%d{HH:mm:ss,SSS}</b> or <b>%d{dd&nbsp;MMM&nbsp;yyyy&nbsp;HH:mm:ss,SSS}</b>. If no date format specifier is given then ISO8601 format is assumed. <p>The date format specifier admits the same syntax as the time pattern string of the {@link java.text.SimpleDateFormat}. Although part of the standard JDK, the performance of <code>SimpleDateFormat</code> is quite poor. <p>For better results it is recommended to use the log4j date formatters. These can be specified using one of the strings "ABSOLUTE", "DATE" and "ISO8601" for specifying {@link org.apache.log4j.helpers.AbsoluteTimeDateFormat AbsoluteTimeDateFormat}, {@link org.apache.log4j.helpers.DateTimeDateFormat DateTimeDateFormat} and respectively {@link org.apache.log4j.helpers.ISO8601DateFormat ISO8601DateFormat}. For example, <b>%d{ISO8601}</b> or <b>%d{ABSOLUTE}</b>. <p>These dedicated date formatters perform significantly better than {@link java.text.SimpleDateFormat}. </td> </tr> <tr> <td align=center><b>F</b></td> <td>Used to output the file name where the logging request was issued. <p><b>WARNING</b> Generating caller location information is extremely slow. It's use should be avoided unless execution speed is not an issue. </tr> <tr> <td align=center><b>l</b></td> <td>Used to output location information of the caller which generated the logging event. <p>The location information depends on the JVM implementation but usually consists of the fully qualified name of the calling method followed by the callers source the file name and line number between parentheses. <p>The location information can be very useful. However, it's generation is <em>extremely</em> slow. It's use should be avoided unless execution speed is not an issue. </td> </tr> <tr> <td align=center><b>L</b></td> <td>Used to output the line number from where the logging request was issued. <p><b>WARNING</b> Generating caller location information is extremely slow. It's use should be avoided unless execution speed is not an issue. </tr> <tr> <td align=center><b>m</b></td> <td>Used to output the application supplied message associated with the logging event.</td> </tr> <tr> <td align=center><b>M</b></td> <td>Used to output the method name where the logging request was issued. <p><b>WARNING</b> Generating caller location information is extremely slow. It's use should be avoided unless execution speed is not an issue. </tr> <tr> <td align=center><b>n</b></td> <td>Outputs the platform dependent line separator character or characters. <p>This conversion character offers practically the same performance as using non-portable line separator strings such as "\n", or "\r\n". Thus, it is the preferred way of specifying a line separator. </tr> <tr> <td align=center><b>p</b></td> <td>Used to output the priority of the logging event.</td> </tr> <tr> <td align=center><b>r</b></td> <td>Used to output the number of milliseconds elapsed since the start of the application until the creation of the logging event.</td> </tr> <tr> <td align=center><b>t</b></td> <td>Used to output the name of the thread that generated the logging event.</td> </tr> <tr> <td align=center><b>x</b></td> <td>Used to output the NDC (nested diagnostic context) associated with the thread that generated the logging event. </td> </tr> <tr> <td align=center><b>X</b></td> <td> <p>Used to output the MDC (mapped diagnostic context) associated with the thread that generated the logging event. The <b>X</b> conversion character can be followed by the key for the map placed between braces, as in <b>%X{clientNumber}</b> where <code>clientNumber</code> is the key. The value in the MDC corresponding to the key will be output. If no additional sub-option is specified, then the entire contents of the MDC key value pair set is output using a format {{key1,val1},{key2,val2}}</p> <p>See {@link MDC} class for more details. </p> </td> </tr> <tr> <td align=center><b>Y</b></td> <td> <p>Used to output the Properties associated with the logging event. The <b>Y</b> conversion character can be followed by the key for the map placed between braces, as in <b>%Y{log4japp}</b> where <code>log4japp</code> is the key. The value in the Properties bundle corresponding to the key will be output. If no additional sub-option is specified, then the entire contents of the Properties key value pair set is output using a format {{key1,val1},{key2,val2}}</p> </td> </tr> <tr> <td align=center><b>%</b></td> <td>The sequence %% outputs a single percent sign. </td> </tr> </table> <p>By default the relevant information is output as is. However, with the aid of format modifiers it is possible to change the minimum field width, the maximum field width and justification. <p>The optional format modifier is placed between the percent sign and the conversion character. <p>The first optional format modifier is the <em>left justification flag</em> which is just the minus (-) character. Then comes the optional <em>minimum field width</em> modifier. This is a decimal constant that represents the minimum number of characters to output. If the data item requires fewer characters, it is padded on either the left or the right until the minimum width is reached. The default is to pad on the left (right justify) but you can specify right padding with the left justification flag. The padding character is space. If the data item is larger than the minimum field width, the field is expanded to accommodate the data. The value is never truncated. <p>This behavior can be changed using the <em>maximum field width</em> modifier which is designated by a period followed by a decimal constant. If the data item is longer than the maximum field, then the extra characters are removed from the <em>beginning</em> of the data item and not from the end. For example, it the maximum field width is eight and the data item is ten characters long, then the first two characters of the data item are dropped. This behavior deviates from the printf function in C where truncation is done from the end. <p>Below are various format modifier examples for the category conversion specifier. <p> <TABLE BORDER=1 CELLPADDING=8> <th>Format modifier <th>left justify <th>minimum width <th>maximum width <th>comment <tr> <td align=center>%20c</td> <td align=center>false</td> <td align=center>20</td> <td align=center>none</td> <td>Left pad with spaces if the category name is less than 20 characters long. <tr> <td align=center>%-20c</td> <td align=center>true</td> <td align=center>20</td> <td align=center>none</td> <td>Right pad with spaces if the category name is less than 20 characters long. <tr> <td align=center>%.30c</td> <td align=center>NA</td> <td align=center>none</td> <td align=center>30</td> <td>Truncate from the beginning if the category name is longer than 30 characters. <tr> <td align=center>%20.30c</td> <td align=center>false</td> <td align=center>20</td> <td align=center>30</td> <td>Left pad with spaces if the category name is shorter than 20 characters. However, if category name is longer than 30 characters, then truncate from the beginning. <tr> <td align=center>%-20.30c</td> <td align=center>true</td> <td align=center>20</td> <td align=center>30</td> <td>Right pad with spaces if the category name is shorter than 20 characters. However, if category name is longer than 30 characters, then truncate from the beginning. </table> <p>Below are some examples of conversion patterns. <dl> <p><dt><b>%r [%t] %-5p %c %x - %m\n</b> <p><dd>This is essentially the TTCC layout. <p><dt><b>%-6r [%15.15t] %-5p %30.30c %x - %m\n</b> <p><dd>Similar to the TTCC layout except that the relative time is right padded if less than 6 digits, thread name is right padded if less than 15 characters and truncated if longer and the category name is left padded if shorter than 30 characters and truncated if longer. </dl> <p>The above text is largely inspired from Peter A. Darnell and Philip E. Margolis' highly recommended book "C -- a Software Engineering Approach", ISBN 0-387-97389-3. @author <a href="mailto:cakalijp@Maritz.com">James P. Cakalic</a> @author Ceki G&uuml;lc&uuml; @since 0.8.2 */ public class PatternLayout extends Layout { /** Default pattern string for log output. Currently set to the string <b>"%m%n"</b> which just prints the application supplied message. */ public static final String DEFAULT_CONVERSION_PATTERN = "%m%n"; /** A conversion pattern equivalent to the TTCCCLayout. Current value is <b>%r [%t] %p %c %x - %m%n</b>. */ public static final String TTCC_CONVERSION_PATTERN = "%r [%t] %p %c %x - %m%n"; private String conversionPattern; private PatternConverter head; private HashMap ruleRegistry = null; /** Constructs a PatternLayout using the DEFAULT_LAYOUT_PATTERN. The default pattern just produces the application supplied message. */ public PatternLayout() { this(DEFAULT_CONVERSION_PATTERN); } /** Constructs a PatternLayout using the supplied conversion pattern. */ public PatternLayout(String pattern) { this.conversionPattern = pattern; activateOptions(); } /** * * Add a new conversion word and associate it with a * {@link org.apache.log4j.pattern.PatternConverter PatternConverter} class. * * @param conversionWord New conversion word to accept in conversion patterns * @param converterClass The class name associated with the conversion word * @since 1.3 */ public void addConversionRule(String conversionWord, String converterClass) { if(ruleRegistry == null) { ruleRegistry = new HashMap(5); } ruleRegistry.put(conversionWord, converterClass); } /** * Returns the rule registry specific for this PatternLayout instance. * @since 1.3 */ public HashMap getRuleRegistry() { return ruleRegistry; } /** Set the <b>ConversionPattern</b> option. This is the string which controls formatting and consists of a mix of literal content and conversion specifiers. */ public void setConversionPattern(String conversionPattern) { this.conversionPattern = conversionPattern; } /** Returns the value of the <b>ConversionPattern</b> option. */ public String getConversionPattern() { return conversionPattern; } /** Activates the conversion pattern. Do not forget to call this method after you change the parameters of the PatternLayout instance. */ public void activateOptions() { PatternParser patternParser = new PatternParser(conversionPattern); patternParser.setConverterRegistry(ruleRegistry); head = patternParser.parse(); } /** The PatternLayout does not handle the throwable contained within {@link LoggingEvent LoggingEvents}. Thus, it returns <code>true</code>. @since 0.8.4 */ public boolean ignoresThrowable() { return true; } /** Produces a formatted string as specified by the conversion pattern. */ public void format(Writer output, LoggingEvent event) throws IOException { PatternConverter c = head; while (c != null) { c.format(output, event); c = c.next; } } }
package org.epics.vtype.io; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import org.epics.util.array.CircularBufferDouble; import org.epics.util.array.ListDouble; import org.epics.util.array.ListInt; import org.epics.util.array.ListNumber; import org.epics.util.text.StringUtil; import org.epics.util.time.Timestamp; import org.epics.util.time.TimestampFormat; import org.epics.vtype.Alarm; import org.epics.vtype.Time; import org.epics.vtype.VEnum; import org.epics.vtype.VEnumArray; import org.epics.vtype.VNumber; import org.epics.vtype.VNumberArray; import org.epics.vtype.VString; import org.epics.vtype.VStringArray; import org.epics.vtype.VTable; import org.epics.vtype.VType; import org.epics.vtype.ValueFactory; import org.epics.vtype.ValueUtil; /** * * @author carcassi */ public class CSVIO { // TODO: we should take these from a default place private static TimestampFormat timeFormat = new TimestampFormat( "yyyy/MM/dd HH:mm:ss.N Z"); //$NON-NLS-1$ public void export(Object value, Writer writer) { if (!canExport(value)) { throw new IllegalArgumentException("Type " + value.getClass().getSimpleName() + " is not supported by this data export."); } try { Time time = ValueUtil.timeOf(value); if (time != null && time.getTimestamp() != null) { writer.append("\"") .append(timeFormat.format(time.getTimestamp())) .append("\" "); } Alarm alarm = ValueUtil.alarmOf(value); if (alarm != null) { writer.append(alarm.getAlarmSeverity().name()) .append(" ") .append(alarm.getAlarmName()); } if (value instanceof VNumber) { writer.append(" ") .append(Double.toString(((VNumber) value).getValue().doubleValue())); } if (value instanceof VString) { writer.append(" \"") .append(((VString) value).getValue()) .append("\""); } if (value instanceof VEnum) { writer.append(" \"") .append(((VEnum) value).getValue()) .append("\""); } if (value instanceof VNumberArray) { ListNumber data = ((VNumberArray) value).getData(); for (int i = 0; i < data.size(); i++) { writer.append(" ") .append(Double.toString(data.getDouble(i))); } } if (value instanceof VStringArray) { List<String> data = ((VStringArray) value).getData(); for (int i = 0; i < data.size(); i++) { writer.append(" \"") .append(data.get(i)) .append("\""); } } if (value instanceof VEnumArray) { List<String> data = ((VEnumArray) value).getData(); for (int i = 0; i < data.size(); i++) { writer.append(" \"") .append(data.get(i)) .append("\""); } } if (value instanceof VTable) { VTable table = (VTable) value; boolean first = true; for (int i = 0; i < table.getColumnCount(); i++) { if (first) { first = false; } else { writer.append(" "); } writer.append("\"") .append(table.getColumnName(i)) .append("\""); } writer.append("\n"); for (int row = 0; row < table.getRowCount(); row++) { first = true; for (int column = 0; column < table.getColumnCount(); column++) { if (first) { first = false; } else { writer.append(" "); } writer.append(toString(table, row, column)); } writer.append("\n"); } } } catch (IOException e) { throw new RuntimeException("Write failed", e); } } public VTable importVTable(Reader reader) { try { BufferedReader br = new BufferedReader(reader); // Parse column names String titleLine = br.readLine(); List<String> columnNames = new ArrayList<>(); for (Object token : StringUtil.parseCSVLine(titleLine, "\\s*")) { if (token instanceof String) { columnNames.add((String) token); } else { throw new IllegalArgumentException("First line must be column names (quoted strings separated by spaces)"); } } String line; List<Object> columnData = new ArrayList<>(Collections.nCopies(columnNames.size(), null)); List<Class<?>> columnTypes = new ArrayList<>(); columnTypes.addAll(Collections.nCopies(columnNames.size(), (Class<Object>) null)); while ((line = br.readLine()) != null) { List<Object> tokens = StringUtil.parseCSVLine(line, "\\s*"); if (tokens.size() != columnNames.size()) { throw new IllegalArgumentException("All rows need to have the same number of elements"); } for (int i = 0; i < tokens.size(); i++) { Object token = tokens.get(i); // Token is a String if (token instanceof String) { // Add list for the column if (columnData.get(i) == null) { columnData.set(i, new ArrayList<String>()); columnTypes.set(i, String.class); } // If type does not match, end if (!(columnData.get(i) instanceof List)) { throw new IllegalArgumentException("Column " + i + " is not made of homogeneous elements (all strings or all numbers)"); } // Add element @SuppressWarnings("unchecked") List<String> data = (List<String>) columnData.get(i); data.add((String) token); } // Token is a Double if (token instanceof Double) { // Add list for the column if (columnData.get(i) == null) { columnData.set(i, new CircularBufferDouble(1000000)); columnTypes.set(i, double.class); } // If type does not match, end if (!(columnData.get(i) instanceof CircularBufferDouble)) { throw new IllegalArgumentException("Column " + i + " is not made of homogeneous elements (all strings or all numbers)"); } // Add element @SuppressWarnings("unchecked") CircularBufferDouble data = (CircularBufferDouble) columnData.get(i); data.addDouble((Double) token); } } } return ValueFactory.newVTable(columnTypes, columnNames, columnData); } catch (IOException ex) { throw new RuntimeException("Couldn't process data", ex); } } private String toString(VTable table, int row, int column) { Class<?> clazz = table.getColumnType(column); if (clazz.equals(String.class)) { return "\"" + ((List) table.getColumnData(column)).get(row) + "\""; } if (clazz.equals(Double.TYPE)) { return Double.toString(((ListDouble) table.getColumnData(column)).getDouble(row)); } if (clazz.equals(Integer.TYPE)) { return Integer.toString(((ListInt) table.getColumnData(column)).getInt(row)); } if (clazz.equals(Timestamp.class)) { @SuppressWarnings("unchecked") List<?> timestamp = (List<?>) table.getColumnData(column); return "\"" + timeFormat.format(timestamp.get(row)) + "\""; } throw new UnsupportedOperationException("Can't export columns of type " + clazz.getSimpleName()); } public boolean canExport(Object data) { if (data instanceof VNumber) { return true; } if (data instanceof VString) { return true; } if (data instanceof VEnum) { return true; } if (data instanceof VNumberArray) { return true; } if (data instanceof VStringArray) { return true; } if (data instanceof VEnumArray) { return true; } if (data instanceof VTable) { return true; } return false; } }
package org.apereo.cas.services; import org.apereo.cas.authentication.principal.Service; import org.apereo.cas.support.events.service.CasRegisteredServiceDeletedEvent; import org.apereo.cas.support.events.service.CasRegisteredServiceExpiredEvent; import org.apereo.cas.support.events.service.CasRegisteredServicePreDeleteEvent; import org.apereo.cas.support.events.service.CasRegisteredServicePreSaveEvent; import org.apereo.cas.support.events.service.CasRegisteredServiceSavedEvent; import org.apereo.cas.support.events.service.CasRegisteredServicesDeletedEvent; import org.apereo.cas.support.events.service.CasRegisteredServicesLoadedEvent; import com.github.benmanes.caffeine.cache.Cache; import lombok.AccessLevel; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.apache.commons.lang3.StringUtils; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import java.util.ArrayList; import java.util.Collection; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; /** * This is {@link AbstractServicesManager}. * * @author Misagh Moayyed * @since 5.2.0 */ @Slf4j @RequiredArgsConstructor(access = AccessLevel.PROTECTED) @Getter public abstract class AbstractServicesManager implements ServicesManager { private final ServiceRegistry serviceRegistry; private final transient ApplicationEventPublisher eventPublisher; private final Set<String> environments; private final Cache<Long, RegisteredService> services; @Override public RegisteredService save(final RegisteredService registeredService) { return save(registeredService, true); } @Override public synchronized RegisteredService save(final RegisteredService registeredService, final boolean publishEvent) { publishEvent(new CasRegisteredServicePreSaveEvent(this, registeredService)); val r = this.serviceRegistry.save(registeredService); this.services.put(r.getId(), r); saveInternal(registeredService); if (publishEvent) { publishEvent(new CasRegisteredServiceSavedEvent(this, r)); } return r; } @Override public synchronized void deleteAll() { this.services.asMap().forEach((k, v) -> delete(v)); this.services.invalidateAll(); publishEvent(new CasRegisteredServicesDeletedEvent(this)); } @Override public synchronized RegisteredService delete(final long id) { val service = findServiceBy(id); return delete(service); } @Override public synchronized RegisteredService delete(final RegisteredService service) { if (service != null) { publishEvent(new CasRegisteredServicePreDeleteEvent(this, service)); this.serviceRegistry.delete(service); this.services.invalidate(service.getId()); deleteInternal(service); publishEvent(new CasRegisteredServiceDeletedEvent(this, service)); } return service; } @Override public RegisteredService findServiceBy(final String serviceId) { if (StringUtils.isBlank(serviceId)) { return null; } var service = getCandidateServicesToMatch(serviceId) .filter(r -> r.matches(serviceId)) .findFirst() .orElse(null); if (service == null) { LOGGER.trace("The service that matches the serviceId [{}] is not found in the cache, trying to find it from [{}]", serviceId, serviceRegistry.getName()); service = serviceRegistry.findServiceBy(serviceId); if (service != null) { services.put(service.getId(), service); LOGGER.trace("The service is found in [{}] and populated to the cache [{}] ", serviceRegistry.getName(), service); } } if (service != null) { service.initialize(); } return validateRegisteredService(service); } @Override public RegisteredService findServiceBy(final Service service) { return Optional.ofNullable(service) .map(svc -> findServiceBy(svc.getId())) .orElse(null); } @Override public Collection<RegisteredService> findServiceBy(final Predicate<RegisteredService> predicate) { if (predicate == null) { return new ArrayList<>(0); } val results = serviceRegistry.findServicePredicate(predicate). stream(). sorted(). peek(RegisteredService::initialize). collect(Collectors.toMap(r -> { return r.getId(); }, Function.identity(), (r, s) -> s)); services.putAll(results); return results.values(); } @Override public <T extends RegisteredService> T findServiceBy(final Service serviceId, final Class<T> clazz) { return findServiceBy(serviceId.getId(), clazz); } @Override public <T extends RegisteredService> T findServiceBy(final String serviceId, final Class<T> clazz) { if (StringUtils.isBlank(serviceId)) { return null; } val service = findServiceBy(serviceId); if (service != null && service.getClass().equals(clazz)) { return (T) service; } return null; } @Override public RegisteredService findServiceBy(final long id) { val result = this.services.get(id, k -> this.serviceRegistry.findServiceById(id)); return validateRegisteredService(result); } @Override public <T extends RegisteredService> T findServiceBy(final long id, final Class<T> clazz) { var service = getService(null, id); if (service != null && service.getClass().equals(clazz)) { return (T) service; } else { LOGGER.trace("The service with id [{}] and type [{}] is not found in the cache; trying to find it from [{}]", id, clazz, serviceRegistry.getName()); service = services.get(id, k -> this.serviceRegistry.findServiceById(id, clazz)); } return (T) validateRegisteredService(service); } @Override public RegisteredService findServiceByName(final String name) { if (StringUtils.isBlank(name)) { return null; } var service = getService(name, 0); if (service == null) { LOGGER.trace("The service with name [{}] is not found in the cache; trying to find it from [{}]", name, serviceRegistry.getName()); service = serviceRegistry.findServiceByExactServiceName(name); if (service != null) { services.put(service.getId(), service); LOGGER.trace("The service is found in [{}] and populated to the cache [{}] ", serviceRegistry.getName(), service); } } if (service != null) { service.initialize(); } return validateRegisteredService(service); } @Override public <T extends RegisteredService> T findServiceByName(final String name, final Class<T> clazz) { if (StringUtils.isBlank(name)) { return null; } var service = getService(name, 0); if (service != null && service.getClass().equals(clazz)) { return (T) service; } else { LOGGER.trace("The service with name [{}] and type [{}] is not found in the cache; trying to find it from [{}]", name, clazz, serviceRegistry.getName()); service = this.serviceRegistry.findServiceByExactServiceName(name, clazz); if (service != null) { services.put(service.getId(), service); LOGGER.trace("The service is found in [{}] and populated to the cache [{}] ", serviceRegistry.getName(), service); } } return (T) validateRegisteredService(service); } @Override public RegisteredService findServiceByExactServiceId(final String serviceId){ if (StringUtils.isBlank(serviceId)) { return null; } var service = getCandidateServicesToMatch(serviceId) .filter(r -> r.getServiceId().equals(serviceId)) .findAny() .orElse(null); if (service == null) { LOGGER.trace("The service with service id [{}] is not found in the cache; trying to find it from [{}]", serviceId, serviceRegistry.getName()); service = serviceRegistry.findServiceByExactServiceId(serviceId); if (service != null) { services.put(service.getId(), service); LOGGER.trace("The service is found in [{}] and populated to the cache [{}] ", serviceRegistry.getName(), service); } } if (service != null) { service.initialize(); } return validateRegisteredService(service); } @Override public Collection<RegisteredService> getAllServices() { return this.services.asMap().values(). stream(). filter(this::validateAndFilterServiceByEnvironment). filter(getRegisteredServicesFilteringPredicate()). sorted(). peek(RegisteredService::initialize). collect(Collectors.toList()); } @Override public Stream<? extends RegisteredService> getAllServicesStream() { return this.serviceRegistry.getServicesStream(); } @Override public Collection<RegisteredService> load() { LOGGER.trace("Loading services from [{}]", serviceRegistry.getName()); this.services.invalidateAll(); this.services.putAll(this.serviceRegistry.load() .stream() .collect(Collectors.toMap(r -> { LOGGER.trace("Adding registered service [{}] with name [{}] and internal identifier [{}]", r.getServiceId(), r.getName(), r.getId()); return r.getId(); }, Function.identity(), (r, s) -> s))); loadInternal(); publishEvent(new CasRegisteredServicesLoadedEvent(this, getAllServices())); evaluateExpiredServiceDefinitions(); LOGGER.info("Loaded [{}] service(s) from [{}].", this.services.asMap().size(), this.serviceRegistry.getName()); return services.asMap().values(); } @Override public long count() { return this.serviceRegistry.size(); } private static Predicate<RegisteredService> getRegisteredServicesFilteringPredicate( final Predicate<RegisteredService>... p) { val predicates = Stream.of(p).collect(Collectors.toCollection(ArrayList::new)); return predicates.stream().reduce(x -> true, Predicate::and); } private void evaluateExpiredServiceDefinitions() { this.services.asMap().values() .stream() .filter(RegisteredServiceAccessStrategyUtils.getRegisteredServiceExpirationPolicyPredicate().negate()) .filter(Objects::nonNull) .forEach(this::processExpiredRegisteredService); } private RegisteredService validateRegisteredService(final RegisteredService registeredService) { val result = checkServiceExpirationPolicyIfAny(registeredService); if (validateAndFilterServiceByEnvironment(result)) { return result; } return null; } private RegisteredService checkServiceExpirationPolicyIfAny(final RegisteredService registeredService) { if (registeredService == null || RegisteredServiceAccessStrategyUtils.ensureServiceIsNotExpired( registeredService)) { return registeredService; } return processExpiredRegisteredService(registeredService); } private RegisteredService processExpiredRegisteredService(final RegisteredService registeredService) { val policy = registeredService.getExpirationPolicy(); LOGGER.warn("Registered service [{}] has expired on [{}]", registeredService.getServiceId(), policy.getExpirationDate()); if (policy.isNotifyWhenExpired()) { LOGGER.debug("Contacts for registered service [{}] will be notified of service expiry", registeredService.getServiceId()); publishEvent(new CasRegisteredServiceExpiredEvent(this, registeredService, false)); } if (policy.isDeleteWhenExpired()) { LOGGER.debug("Deleting expired registered service [{}] from registry.", registeredService.getServiceId()); if (policy.isNotifyWhenDeleted()) { LOGGER.debug("Contacts for registered service [{}] will be notified of service expiry and removal", registeredService.getServiceId()); publishEvent(new CasRegisteredServiceExpiredEvent(this, registeredService, true)); } delete(registeredService); return null; } return registeredService; } /** * Gets candidate services to match the service id. * * @param serviceId the service id * @return the candidate services to match */ protected abstract Stream<RegisteredService> getCandidateServicesToMatch(String serviceId); /** * Delete internal. * * @param service the service */ protected void deleteInternal(final RegisteredService service) { } /** * Save internal. * * @param service the service */ protected void saveInternal(final RegisteredService service) { } /** * Load internal. */ protected void loadInternal() { } private void publishEvent(final ApplicationEvent event) { if (this.eventPublisher != null) { this.eventPublisher.publishEvent(event); } } private boolean validateAndFilterServiceByEnvironment(final RegisteredService service) { if (this.environments.isEmpty()) { LOGGER.trace("No environments are defined by which services could be filtered"); return true; } if (service == null) { LOGGER.trace("No service definition was provided"); return true; } if (service.getEnvironments() == null || service.getEnvironments().isEmpty()) { LOGGER.trace("No environments are assigned to service [{}]", service.getName()); return true; } return service.getEnvironments() .stream() .anyMatch(this.environments::contains); } private RegisteredService getService(final String name, final long id) { return services.asMap().values().stream().filter(r -> name != null ? r.getServiceId().equals(name) : r.getId() == id).findFirst().orElse(null); } }
package de.dakror.vloxlands.generate.biome; import com.badlogic.gdx.math.MathUtils; import de.dakror.vloxlands.game.voxel.Voxel; import de.dakror.vloxlands.game.world.Island; import de.dakror.vloxlands.generate.Beziers; import de.dakror.vloxlands.generate.WorldGenerator; /** * @author Dakror */ public class ModerateBiome extends Biome { protected int treeMin = 5; protected int treeMax = 10; protected int boulderMin = 5; protected int boulderMax = 10; protected float spikeFactor = 1; @Override public void generate(WorldGenerator worldGen, Island island, int radius) { int j = (int) (3 + 3 * MathUtils.random() + radius / 8f); generateBezier(island, Beziers.TOPLAYER, Island.SIZE / 2, Island.SIZE / 2, radius, Island.SIZE / 4 * 3, j, new byte[] { Voxel.get("DIRT").getId() }, true); worldGen.step(); byte[] sRatio = createRatio(new byte[] { Voxel.get("STONE").getId(), Voxel.get("DIRT").getId() }, new int[] { 5, 1 }); generateSpikes(island, (int) (radius * spikeFactor), Island.SIZE / 4 * 3, radius, j, sRatio); worldGen.step(); generateTrees(island, treeMin, treeMax); generateBoulders(island, Island.SIZE / 4 * 3, radius, boulderMin, boulderMax, 3, 6, 4, 7, new byte[] { Voxel.get("STONE").getId() }); worldGen.step(); generateOreVeins(island); generateCrystals(island); worldGen.step(); } }
package io.crnk.gen.typescript.transform; import java.math.BigDecimal; import java.math.BigInteger; import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.util.HashMap; import java.util.UUID; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.crnk.gen.typescript.model.TSAny; import io.crnk.gen.typescript.model.TSElement; import io.crnk.gen.typescript.model.TSPrimitiveType; import io.crnk.gen.typescript.model.TSType; import io.crnk.meta.model.MetaElement; import io.crnk.meta.model.MetaPrimitiveType; public class TSMetaPrimitiveTypeTransformation implements TSMetaTransformation { private HashMap<Class<?>, TSType> primitiveMapping; public TSMetaPrimitiveTypeTransformation() { primitiveMapping = new HashMap<>(); primitiveMapping.put(ObjectNode.class, TSAny.INSTANCE); primitiveMapping.put(ArrayNode.class, TSAny.INSTANCE); primitiveMapping.put(JsonNode.class, TSAny.INSTANCE); primitiveMapping.put(Object.class, TSAny.INSTANCE); primitiveMapping.put(String.class, TSPrimitiveType.STRING); primitiveMapping.put(Boolean.class, TSPrimitiveType.BOOLEAN); primitiveMapping.put(boolean.class, TSPrimitiveType.BOOLEAN); primitiveMapping.put(long.class, TSPrimitiveType.NUMBER); primitiveMapping.put(Long.class, TSPrimitiveType.NUMBER); primitiveMapping.put(float.class, TSPrimitiveType.NUMBER); primitiveMapping.put(Float.class, TSPrimitiveType.NUMBER); primitiveMapping.put(double.class, TSPrimitiveType.NUMBER); primitiveMapping.put(Double.class, TSPrimitiveType.NUMBER); primitiveMapping.put(int.class, TSPrimitiveType.NUMBER); primitiveMapping.put(Integer.class, TSPrimitiveType.NUMBER); primitiveMapping.put(long.class, TSPrimitiveType.NUMBER); primitiveMapping.put(Long.class, TSPrimitiveType.NUMBER); primitiveMapping.put(byte.class, TSPrimitiveType.NUMBER); primitiveMapping.put(Byte.class, TSPrimitiveType.NUMBER); primitiveMapping.put(BigDecimal.class, TSPrimitiveType.NUMBER); primitiveMapping.put(BigInteger.class, TSPrimitiveType.NUMBER); primitiveMapping.put(LocalDate.class, TSPrimitiveType.STRING); primitiveMapping.put(LocalDate.class, TSPrimitiveType.STRING); primitiveMapping.put(LocalDateTime.class, TSPrimitiveType.STRING); primitiveMapping.put(LocalDateTime.class, TSPrimitiveType.STRING); primitiveMapping.put(OffsetDateTime.class, TSPrimitiveType.STRING); primitiveMapping.put(OffsetDateTime.class, TSPrimitiveType.STRING); primitiveMapping.put(UUID.class, TSPrimitiveType.STRING); primitiveMapping.put(Duration.class, TSPrimitiveType.STRING); primitiveMapping.put(byte[].class, TSPrimitiveType.STRING); } @Override public void postTransform(TSElement element, TSMetaTransformationContext context) { } @Override public boolean accepts(MetaElement element) { return element instanceof MetaPrimitiveType; } @Override public TSElement transform(MetaElement element, TSMetaTransformationContext context, TSMetaTransformationOptions options) { Class<?> implClass = ((MetaPrimitiveType) element).getImplementationClass(); if (primitiveMapping.containsKey(implClass)) { return primitiveMapping.get(implClass); } throw new IllegalStateException("unexpected element: " + element + " of type " + implClass.getName()); } @Override public boolean isRoot(MetaElement element) { return false; } }
package de.cubeisland.engine.reflect; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import de.cubeisland.engine.reflect.codec.Codec; import de.cubeisland.engine.reflect.exception.InvalidReflectedObjectException; import de.cubeisland.engine.reflect.exception.MissingCodecException; import de.cubeisland.engine.reflect.util.SectionFactory; /** * This abstract class represents a reflected object to be serialized using a Codec C. */ public abstract class Reflected<CodecT extends Codec, SerialType> implements Section { private final transient Class<CodecT> defaultCodec = getCodecClass(getClass()); private transient Reflector reflector; private transient SerialType serialType; private transient Reflected defaults = this; private transient ReflectedConverterManager manager = new ReflectedConverterManager(this); /** * Saves the fields that got inherited from the parent-reflected */ private transient Set<Field> inheritedFields; /** * Initializes the Reflected with a Reflector * <p>This needs to be called before using any save or load method * * @param reflector the Reflector */ public final void init(Reflector reflector) { this.reflector = reflector; initializeSections(this, getCodec().getConverterManager().getConverterByClass(SectionConverter.class)); this.onInit(); } private void initializeSections(Section section, SectionConverter sectionConverter) { try { for (Field field : sectionConverter.getReflectedFields(section.getClass())) { if (Section.class.isAssignableFrom(field.getType()) && field.get(section) == null) { @SuppressWarnings("unchecked") Class<? extends Section> sectionClass = (Class<? extends Section>)field.getType(); Section createdSection = SectionFactory.newSectionInstance(sectionClass, null); field.set(section, createdSection); this.initializeSections(createdSection, sectionConverter); } } } catch (IllegalAccessException ignored) {} } /** * Returns the reflector used for this reflected * * @return the reflector */ public Reflector getReflector() { return reflector; } /** * Returns the default Reflected * <p>If not a child Reflected the default is <code>this</code> * * @return the default Reflected */ public final Reflected getDefault() { return this.defaults; } /** * Sets the default Reflected * * @param reflected the Reflected */ public final void setDefault(Reflected reflected) { if (reflected == null) { this.defaults = this; this.inheritedFields = null; return; } if (!getClass().equals(reflected.getClass())) { throw new IllegalArgumentException("Parent and child-reflected have to be the same type of reflected!"); } this.defaults = reflected; this.inheritedFields = new HashSet<Field>(); } /** * Returns true if ConversionExceptions should be rethrown immediately * <p>this does not affect ConversionException thrown when converting fields into nodes * <p>override to change * * @return whether to rethrow ConversionExceptions or log them instead */ public boolean useStrictExceptionPolicy() { return true; } /** * Marks a field as being inherited from the default Reflected and thus not being saved * <p>if this Reflected is not a child Reflected nothing happens * * @param field the inherited field */ protected final void addInheritedField(Field field) { if (inheritedFields == null) { return; } this.inheritedFields.add(field); } /** * Marks a field as not being inherited from the default Reflected and thus saved into file * <p>if this Reflected is not a child Reflected nothing happens * * @param field the not inherited field */ protected final void removeInheritedField(Field field) { if (inheritedFields == null) { return; } this.inheritedFields.remove(field); } /** * Returns whether the given field was inherited from an other Reflected * <p>Returns always false when this is not a child Reflected * * @param field the field to check * * @return true if the field got inherited */ protected final boolean isInheritedField(Field field) { return inheritedFields != null && inheritedFields.contains(field); } /** * Loads and saves a child Reflected from given SerialType with this Reflected as default * * @param source the source SerialType * @param <T> the ReflectedType * * @return the loaded child Reflected */ @SuppressWarnings("unchecked") public <T extends Reflected> T loadChild(SerialType source) { Reflected<CodecT, SerialType> childReflected = reflector.create(this.getClass()); childReflected.setTarget(source); childReflected.setDefault(this); try { childReflected.reload(true); return (T)childReflected; } catch (InvalidReflectedObjectException ex) { throw ex; } catch (Exception ex) { throw new IllegalStateException("Unknown Exception while loading Child-Reflected!", ex); } } /** * Tries to get the CodecClazz of a Reflected implementation. * * @param clazz the clazz of the reflected * * @return the Codec */ @SuppressWarnings("unchecked") private Class<CodecT> getCodecClass(Class clazz) { Type genericSuperclass = clazz; try { while (genericSuperclass instanceof Class) { genericSuperclass = ((Class)genericSuperclass).getGenericSuperclass(); if (Reflected.class.equals(genericSuperclass)) { // superclass is this class -> No Codec set as GenericType Missing Codec! return null; } // check if genericSuperclass is ParametrizedType if (genericSuperclass instanceof ParameterizedType) { // get First gType Type gType = ((ParameterizedType)genericSuperclass).getActualTypeArguments()[0]; // check if it is codec if (gType instanceof Class && Codec.class.isAssignableFrom((Class<?>)gType)) { return (Class<CodecT>)gType; } genericSuperclass = ((ParameterizedType)genericSuperclass).getRawType(); } } throw new IllegalStateException("Unable to get Codec! " + genericSuperclass + " is not a class!"); } catch (IllegalStateException ex) { throw ex; } catch (Exception ex) { throw new IllegalStateException("Something went wrong", ex); } } /** * Saves the Reflected default SerialType */ public final void save() { this.save(this.serialType); } /** * Saves this Reflected into the target * * @param target the target to save to */ public abstract void save(SerialType target); /** * Reloads the Reflected from the default SerialType * <p>This will only work if the SerialType got set previously */ public final void reload() { this.reload(false); } /** * Reloads the Reflected from the default SerialType * <p>This will only work if the SerialType got set previously * * @param save true if the Reflected should be saved after loading * * @return false when the reflected did not get loaded */ public final boolean reload(boolean save) throws InvalidReflectedObjectException { boolean result = false; if (!this.loadFrom(this.serialType) && save) { result = true; } if (save) { this.updateInheritance(); // save the default values this.save(); } return result; } /** * Loads the Reflected using the given SerialType * <p>This will NOT set the SerialType of this Reflected * * @param source the SerialType to load from * * @return true if the Reflected was loaded from the given source */ public abstract boolean loadFrom(SerialType source); /** * Returns the Codec * * @return the Codec defined in the GenericType of the reflected * * @throws MissingCodecException when no codec was set via genericType */ public final CodecT getCodec() throws MissingCodecException { if (defaultCodec == null) { throw new MissingCodecException( "Reflected has no Codec set! A reflected object needs to have a codec defined in its GenericType"); } return this.reflector.getCodecManager().getCodec(this.defaultCodec); } /** * Returns the SerialType this reflected will be saved to and loaded from by default * * @return the path of this reflected */ public final SerialType getTarget() { return this.serialType; } /** * Sets the SerialType to load from * * @param type the SerialType the reflected will load from and save to by default */ public final void setTarget(SerialType type) { if (type == null) { throw new IllegalArgumentException("The SerialType must not be null!"); } this.serialType = type; } /** * Gets called right before loading */ public void onLoad() { // implement onLoad } /** * This method gets called right after the reflected got loaded. */ public void onLoaded(SerialType loadedFrom) { // implement onLoaded } /** * This method gets called right after the reflected get saved. */ public void onSaved(SerialType savedTo) { // implement onSaved } /** * Gets called after {@link #init(Reflector)} was called */ public void onInit() { // implement onInit } /** * Gets called right before saving */ public void onSave() { // implement onSave } /** * Updates the inheritance of Fields * <p>This does nothing if the Reflected has no other default set */ public final void updateInheritance() { if (this.defaults == null || this.defaults == this) { return; } this.inheritedFields = new HashSet<Field>(); SectionConverter sectionConverter = this.getCodec().getConverterManager().getConverterByClass(SectionConverter.class); try { this.updateInheritance(this, defaults, sectionConverter); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } } /** * Updates the inheritance of the Sections * * @param section the Section * @param defaults the default Section * @param converter the SectionConverter */ private void updateInheritance(Section section, Section defaults, SectionConverter converter) throws IllegalAccessException { for (Field field : converter.getReflectedFields(section.getClass())) { Type type = field.getGenericType(); Object value = field.get(section); Object defaultValue = field.get(defaults); if (value == null && defaultValue == null) { this.addInheritedField(field); return; } if (value != null && defaultValue != null) { if (value.equals(defaultValue)) { this.addInheritedField(field); } else if (value instanceof Section && defaultValue instanceof Section) { this.updateInheritance((Section)value, (Section)defaultValue, converter); } else if (type instanceof ParameterizedType) { updateSectionMapInheritance(converter, (ParameterizedType)type, value, defaultValue); } } } } private void updateSectionMapInheritance(SectionConverter sectionConverter, ParameterizedType pType, Object value, Object defaultValue) throws IllegalAccessException { if (Map.class.isAssignableFrom((Class<?>)pType.getRawType()) && Section.class.isAssignableFrom( (Class<?>)pType.getActualTypeArguments()[1])) { @SuppressWarnings("unchecked") Map<?, Section> valueMap = (Map<?, Section>)value; @SuppressWarnings("unchecked") Map<?, Section> defaultValueMap = (Map<?, Section>)defaultValue; for (Entry<?, Section> entry : valueMap.entrySet()) { this.updateInheritance(entry.getValue(), defaultValueMap.get(entry.getKey()), sectionConverter); } } } /** * Returns the ConverterManager * * @return the ConverterManager */ public final ReflectedConverterManager getConverterManager() { return manager; } /** * Returns true if this Reflected has an other default Reflected than itself */ public final boolean isChild() { return this.getDefault() != this; } }
package org.jboss.dmr.client; import com.google.gwt.core.client.EntryPoint; /** * @author Heiko Braun * @date 3/16/11 */ public class Bootstrap implements EntryPoint { @Override public void onModuleLoad() { System.out.println("Loaded DMR module"); } }
package edu.vu.isis.ammo.dash; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.RemoteException; import android.preference.PreferenceManager; import android.provider.BaseColumns; import edu.vu.isis.ammo.INetPrefKeys; import edu.vu.isis.ammo.IntentNames; import edu.vu.isis.ammo.api.AmmoPreference; import edu.vu.isis.ammo.api.AmmoRequest; import edu.vu.isis.ammo.api.IAmmoRequest; import edu.vu.isis.ammo.api.type.Limit; import edu.vu.isis.ammo.api.type.Query; import edu.vu.isis.ammo.dash.preferences.DashPreferences; import edu.vu.isis.ammo.dash.provider.IncidentSchema.EventTableSchema; import edu.vu.isis.ammo.dash.provider.IncidentSchema.MediaTableSchema; import edu.vu.isis.ammo.dash.provider.IncidentSchemaBase; import edu.vu.isis.ammo.dash.provider.IncidentSchemaBase.EventTableSchemaBase; import edu.vu.isis.ammo.dash.provider.IncidentSchemaBase.MediaTableSchemaBase; /** * Does this obviate the need for * SubscriptionViewer.java::makeDashSubscriptions()? At issue is the first * subscription. * * This broadcast receiver catches certain intents broadcast by AmmoCore * announcing when connectivity has changed. Once the intents are caught, * certain tasks are performed like updating subscriptions and pull new content * from the Gateway. * */ public class AnnounceReceiver extends BroadcastReceiver { private static final Logger logger = LoggerFactory.getLogger("class.AnnounceReceiver"); static final String CORE_OPERATOR_ID = "CORE_OPERATOR_ID"; static final String CORE_SUBSCRIPTION_DONE = "CORE_SUBSCRIPTION_DONE"; private AmmoRequest.Builder ad; /** * when a login intent is detected change the subscription. */ @Override public void onReceive(Context context, Intent intent) { this.ad = AmmoRequest.newBuilder(context, this); final String action = intent.getAction(); WorkflowLogger.log("Announce Receiver - got an intent with action: " + action); if (IntentNames.AMMO_READY.endsWith(action)) { logger.info("Announce Receiver: Got an Intent"); this.makeDashSubscriptions(context); } if (IntentNames.AMMO_CONNECTED.endsWith(action)) { logger.info("Announce Receiver: Got an Intent AMMO_CONNECTED"); this.pullRecentReports(context); } // this.ad.releaseInstance(); } public void makeDashSubscriptions(Context context) { final String userId = AmmoPreference .getInstance(context) .getString(INetPrefKeys.CORE_OPERATOR_ID, INetPrefKeys.DEFAULT_CORE_OPERATOR_ID); WorkflowLogger.log("Announce Receiver - making Dash subscriptions"); try { this.ad.provider(EventTableSchemaBase.CONTENT_URI).topic(EventTableSchemaBase.CONTENT_TOPIC).subscribe(); this.ad.provider(MediaTableSchemaBase.CONTENT_URI).topic(MediaTableSchemaBase.CONTENT_TOPIC).subscribe(); this.ad.provider(EventTableSchemaBase.CONTENT_URI).topic(EventTableSchemaBase.CONTENT_TOPIC + "/" + IDash.MIME_TYPE_EXTENSION_TIGR_UID + "/" + userId).subscribe(); this.ad.provider(MediaTableSchemaBase.CONTENT_URI).topic(MediaTableSchemaBase.CONTENT_TOPIC + "/" + IDash.MIME_TYPE_EXTENSION_TIGR_UID + "/" + userId).subscribe(); } catch (RemoteException ex) { logger.error("could not connect to ammo", ex); } } public void pullRecentReports(Context context) { WorkflowLogger.log("Announce Receiver - pulling recent reports"); this.pullIncidentContent(context, EventTableSchemaBase.CONTENT_URI, EventTableSchemaBase.CONTENT_TOPIC, BaseColumns._ID, EventTableSchemaBase._RECEIVED_DATE); this.pullIncidentContent(context, MediaTableSchemaBase.CONTENT_URI, MediaTableSchemaBase.CONTENT_TOPIC, BaseColumns._ID, MediaTableSchemaBase._RECEIVED_DATE); } private void pullIncidentContent(Context context, Uri contentUri, String contentTopic, String idField, String receivedDateField) { final ContentResolver cr = context.getContentResolver(); final String[] projection = { idField, receivedDateField }; final String selection = new StringBuilder(). append('"'). append(IncidentSchemaBase.EventTableSchemaBase._DISPOSITION). append('"'). append(" LIKE "). append('\''). append(IncidentSchemaBase.Disposition.REMOTE). append('%'). append('\'').toString(); final String order = receivedDateField + " DESC"; final Cursor cur = cr.query(contentUri, projection, selection, null, order); // Negative value indicates relative time. final long relativeTime; // If the query failed or the there are no items in the database, set // the relative time to -2000. if (cur == null || cur.getCount() == 0) { relativeTime = 0; } else { // Otherwise, subtract the received date cur.moveToFirst(); long currentTime = System.currentTimeMillis(); long timestamp = cur.getLong(cur.getColumnIndex(receivedDateField)); if (timestamp < 1) { relativeTime = 1; } else { relativeTime = timestamp - currentTime; } } final String query; if (relativeTime >= 0) { query = ",,-1,,"; } else { query = ",," + String.valueOf((relativeTime / 1000) - 1) + ",,"; } // Get our dash limit count from shared preferences. final String limitStr = PreferenceManager .getDefaultSharedPreferences(context) .getString(DashPreferences.PREF_DASH_LIMIT, DashPreferences.DEFAULT_PREF_DASH_LIMIT); final int dashLimitCount = Integer.valueOf(limitStr).intValue(); try { final IAmmoRequest pull = ad.provider(contentUri).topic(contentTopic).limit(new Limit(dashLimitCount)) // .expire( new new TimeStamp(Calendar.HOUR, 1, 0.0) .select(new Query(query)).retrieve(); WorkflowLogger.log("AnnounceReceiver - pulling incident content with pull request: " + pull.toString() + " query: " + query); logger.trace("the query {} {}", pull, query); } catch (RemoteException ex) { logger.warn("ammo not available"); if (cur != null) cur.close(); return; } WorkflowLogger.log("AnnounceReceiver - pull succeeded with uri: " + contentUri); logger.debug("pull succeeded with uri: " + contentUri.toString()); if (cur != null) { cur.close(); } } }
package org.deeplearning4j.optimize.listeners; import org.deeplearning4j.nn.api.Model; import org.deeplearning4j.optimize.api.IterationListener; import org.nd4j.linalg.primitives.Pair; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; /** * CollectScoresIterationListener simply stores the model scores internally (along with the iteration) every 1 or N * iterations (this is configurable). These scores can then be obtained or exported. * * @author Alex Black */ public class CollectScoresIterationListener implements IterationListener { private int frequency; private int iterationCount = 0; private List<Pair<Integer, Double>> scoreVsIter = new ArrayList<>(); /** * Constructor for collecting scores with default saving frequency of 1 */ public CollectScoresIterationListener() { this(1); } /** * Constructor for collecting scores with the specified frequency. * @param frequency Frequency with which to collect/save scores */ public CollectScoresIterationListener(int frequency) { if (frequency <= 0) frequency = 1; this.frequency = frequency; } @Override public void iterationDone(Model model, int iteration, int epoch) { if (++iterationCount % frequency == 0) { double score = model.score(); scoreVsIter.add(new Pair<>(iterationCount, score)); } } public List<Pair<Integer, Double>> getScoreVsIter() { return scoreVsIter; } /** * Export the scores in tab-delimited (one per line) UTF-8 format. */ public void exportScores(OutputStream outputStream) throws IOException { exportScores(outputStream, "\t"); } /** * Export the scores in delimited (one per line) UTF-8 format with the specified delimiter * * @param outputStream Stream to write to * @param delimiter Delimiter to use */ public void exportScores(OutputStream outputStream, String delimiter) throws IOException { StringBuilder sb = new StringBuilder(); sb.append("Iteration").append(delimiter).append("Score"); for (Pair<Integer, Double> p : scoreVsIter) { sb.append("\n").append(p.getFirst()).append(delimiter).append(p.getSecond()); } outputStream.write(sb.toString().getBytes("UTF-8")); } /** * Export the scores to the specified file in delimited (one per line) UTF-8 format, tab delimited * * @param file File to write to */ public void exportScores(File file) throws IOException { exportScores(file, "\t"); } /** * Export the scores to the specified file in delimited (one per line) UTF-8 format, using the specified delimiter * * @param file File to write to * @param delimiter Delimiter to use for writing scores */ public void exportScores(File file, String delimiter) throws IOException { try (FileOutputStream fos = new FileOutputStream(file)) { exportScores(fos, delimiter); } } }
package org.xillium.core; import java.io.*; import java.lang.management.ManagementFactory; import java.util.*; import java.util.jar.*; import java.util.logging.*; import java.util.regex.*; import javax.management.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.commons.fileupload.*; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.util.Streams; //import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.core.io.InputStreamResource; import org.springframework.context.ApplicationContext; import org.springframework.context.support.GenericApplicationContext; import org.springframework.web.context.support.*; import org.xillium.base.etc.Arrays; import org.xillium.base.beans.*; import org.xillium.data.*; import org.xillium.core.conf.*; import org.xillium.core.management.*; import org.xillium.core.intrinsic.*; import org.xillium.core.util.ModuleSorter; /** * Platform Service Dispatcher. * * This servlet dispatches inbound HTTP calls to registered services based on request URI. A valid request URI is in the form of * <pre> * /[context]/[module]/[service]?[params]=... * </pre> * When a request URI matches the above pattern, this servlet looks up a Service instance registered under the name 'module/service'. * <p/> * The fabric of operation, administration, and maintenance (foam) * <ul> * <li><code>/[context]/x!/[service]</code><p/> * <ul> * <li>list</li> * <li>desc - parameter description</li> * </ul> * </li> * </ul> */ @SuppressWarnings("serial") public class HttpServiceDispatcher extends HttpServlet { private static final String DOMAIN_NAME = "Xillium-Domain-Name"; private static final String MODULE_NAME = "Xillium-Module-Name"; private static final String MODULE_BASE = "Xillium-Module-Base"; private static final String VALIDATION_DIC = "validation-dictionary.xml"; private static final String SERVICE_CONFIG = "service-configuration.xml"; private static final String STORAGE_PREFIX = "storage-"; // still a special case as it depends on the Persistence bean private static final String XILLIUM_PREFIX = "xillium-"; private static final Pattern URI_REGEX = Pattern.compile("/[^/?]+/([^/?]+/[^/?]+)"); // '/context/module/service' private static final File TEMPORARY = null; private static final Logger _logger = Logger.getLogger(HttpServiceDispatcher.class.getName()); private final Stack<ObjectName> _manageables = new Stack<ObjectName>(); private final Stack<List<PlatformLifeCycleAware>> _plca = new Stack<List<PlatformLifeCycleAware>>(); private final Map<String, Service> _services = new HashMap<String, Service>(); private final org.xillium.data.validation.Dictionary _dict = new org.xillium.data.validation.Dictionary(); // Wired in spring application context private Persistence _persistence; public HttpServiceDispatcher() { _logger.log(Level.INFO, "START HTTP service dispatcher " + getClass().getName()); _logger.log(Level.INFO, "java.util.logging.config.class=" + System.getProperty("java.util.logging.config.class")); } /** * Initializes the servlet, loading and initializing xillium modules. */ public void init() throws ServletException { ApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); _dict.addTypeSet(org.xillium.data.validation.StandardDataTypes.class); if (wac.containsBean("persistence")) { // persistence may not be there if persistent storage is not required _persistence = (Persistence)wac.getBean("persistence"); } // if intrinsic services are wanted Map<String, String> descriptions = new HashMap<String, String>(); ModuleSorter.Sorted sorted = sortServiceModules(); // scan special modules, configuring and initializing PlatformLifeCycleAware objects as each module is loaded wac = scanServiceModules(sorted.specials(), wac, descriptions, null); // scan regular modules, collecting all PlatformLifeCycleAware objects List<PlatformLifeCycleAware> plcas = new ArrayList<PlatformLifeCycleAware>(); scanServiceModules(sorted.regulars(), wac, descriptions, plcas); _logger.info("configure PlatformLifeCycleAware objects in regular modules"); for (PlatformLifeCycleAware plca: plcas) { _logger.info("Configuring REGULAR PlatformLifeCycleAware " + plca.getClass().getName()); plca.configure(); } _logger.info("initialize PlatformLifeCycleAware objects in regular modules"); for (PlatformLifeCycleAware plca: plcas) { _logger.info("Initalizing REGULAR PlatformLifeCycleAware " + plca.getClass().getName()); plca.initialize(); } _plca.push(plcas); _services.put("x!/desc", new DescService(descriptions)); _services.put("x!/list", new ListService(_services)); } public void destroy() { _logger.info("Terminating service dispatcher"); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); while (!_manageables.empty()) { ObjectName on = _manageables.pop(); _logger.info("unregistering MBean " + on); try { mbs.unregisterMBean(on); } catch (Exception x) { _logger.log(Level.WARNING, on.toString()); } } while (!_plca.empty()) { List<PlatformLifeCycleAware> plcas = _plca.pop(); // terminate PlatformLifeCycleAware objects in this level for (PlatformLifeCycleAware plca: plcas) { plca.terminate(); } } // finally, manually deregisters JDBC driver, which prevents Tomcat 7 from complaining about memory leaks Enumeration<java.sql.Driver> drivers = java.sql.DriverManager.getDrivers(); while (drivers.hasMoreElements()) { java.sql.Driver driver = drivers.nextElement(); try { java.sql.DriverManager.deregisterDriver(driver); _logger.info("Deregistering jdbc driver: " + driver); } catch (java.sql.SQLException x) { _logger.log(Level.WARNING, "Error deregistering driver " + driver, x); } } } /** * Dispatcher entry point */ protected void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { Service service; String id; _logger.fine("Request URI = " + req.getRequestURI()); Matcher m = URI_REGEX.matcher(req.getRequestURI()); if (m.matches()) { id = m.group(1); _logger.fine("Request service id = " + id); service = _services.get(id); if (service == null) { _logger.warning("Request not recognized: " + req.getRequestURI()); res.sendError(404); return; } } else { _logger.warning("Request not recognized: " + req.getRequestURI()); res.sendError(404); return; } List<File> upload = new ArrayList<File>(); DataBinder binder = new DataBinder(); try { if (ServletFileUpload.isMultipartContent(req)) { try { FileItemIterator it = new ServletFileUpload().getItemIterator(req); while (it.hasNext()) { FileItemStream item = it.next(); String name = item.getFieldName(); InputStream stream = item.openStream(); if (item.isFormField()) { binder.put(name, Streams.asString(stream)); } else { // File field with file name in item.getName() String original = item.getName(); int dot = original.lastIndexOf('.'); // store the file in a temporary place File file = File.createTempFile("xillium", dot > 0 ? original.substring(dot) : null, TEMPORARY); OutputStream out = new FileOutputStream(file); byte[] buffer = new byte[1024*1024]; int length; while ((length = stream.read(buffer)) >= 0) out.write(buffer, 0, length); out.close(); binder.put(name, original); binder.put(name + ":path", file.getAbsolutePath()); upload.add(file); } } } catch (FileUploadException x) { throw new RuntimeException("Failed to parse multipart content", x); } } else { Enumeration<String> en = req.getParameterNames(); while (en.hasMoreElements()) { String name = en.nextElement(); String[] values = req.getParameterValues(name); if (values.length == 1) { binder.put(name, values[0]); } else { StringBuilder sb = new StringBuilder(); for (int i = 0; i < values.length; ++i) { sb.append('{').append(values[i]).append('}'); } binder.put(name, sb.toString()); } } } // auto-parameters binder.put(Service.REQUEST_CLIENT_ADDR, req.getRemoteAddr()); binder.put(Service.REQUEST_CLIENT_PORT, String.valueOf(req.getRemotePort())); binder.put(Service.REQUEST_SERVER_PORT, String.valueOf(req.getServerPort())); binder.put(Service.REQUEST_HTTP_METHOD, req.getMethod()); if (id.endsWith(".html")) { // TODO provide a default, error reporting page template } // TODO: pre-service filter if (service instanceof Service.Secured) { _logger.fine("Trying to authorize invocation of a secured service"); ((Service.Secured)service).authorize(id, binder, _persistence); } binder = service.run(binder, _dict, _persistence); try { Runnable task = (Runnable)binder.getNamedObject(Service.SERVICE_POST_ACTION); if (task != null) { task.run(); } } catch (Throwable t) { _logger.warning("In post-service processing caught " + t.getClass() + ": " + t.getMessage()); } } catch (Throwable x) { String message = Throwables.getFirstMessage(x); if (message == null || message.length() == 0) { message = "***"+Throwables.getRootCause(x).getClass().getSimpleName(); } binder.put(Service.FAILURE_MESSAGE, message); _logger.warning("Exception caught in dispatcher: " + message); _logger.log(Level.INFO, "Exception stack trace:", x); CharArrayWriter sw = new CharArrayWriter(); x.printStackTrace(new PrintWriter(sw)); binder.put(Service.FAILURE_STACK, sw.toString()); } finally { // TODO: post-service filter if (service instanceof Service.Extended) { _logger.fine("Invoking extended operations"); try { ((Service.Extended)service).complete(binder); } catch (Throwable t) { _logger.log(Level.WARNING, "Extended service: complete() failed", t); } } res.setHeader("Access-Control-Allow-Headers", "origin,x-prototype-version,x-requested-with,accept"); res.setHeader("Access-Control-Allow-Origin", "*"); try { String page = binder.get(Service.SERVICE_PAGE_TARGET); binder.clearAutoValues(); if (page == null) { res.setHeader("Content-Type", "application/json;charset=UTF-8"); String json = binder.get(Service.SERVICE_JSON_TUNNEL); if (json == null) { JSONBuilder jb = new JSONBuilder(binder.estimateMaximumBytes()).append('{'); jb.quote("params").append(":{ "); Iterator<String> it = binder.keySet().iterator(); while (it.hasNext()) { String key = it.next(); String val = binder.get(key); if (val == null) { jb.quote(key).append(":null"); } else if (val.startsWith("json:")) { jb.quote(key).append(':').append(val.substring(5)); } else { jb.serialize(key, val); } jb.append(','); } jb.replaceLast('}').append(','); jb.quote("tables").append(":{ "); Set<String> rsets = binder.getResultSetNames(); it = rsets.iterator(); while (it.hasNext()) { String name = it.next(); jb.quote(name).append(":"); binder.getResultSet(name).toJSON(jb); jb.append(','); } jb.replaceLast('}'); jb.append('}'); json = jb.toString(); } res.getWriter().append(json).flush(); } else { _logger.info("\t=> " + getServletContext().getResource(page)); req.setAttribute(Service.SERVICE_DATA_BINDER, binder); getServletContext().getRequestDispatcher(page).include(req, res); } } finally { for (File tmp: upload) { try { tmp.delete(); } catch (Exception x) {} } } } } private ModuleSorter.Sorted sortServiceModules() throws ServletException { ModuleSorter sorter = new ModuleSorter(); ServletContext context = getServletContext(); try { Set<String> jars = context.getResourcePaths("/WEB-INF/lib/"); _logger.info("There are " + jars.size() + " resource paths"); for (String jar : jars) { try { //_logger.info("... " + jar); JarInputStream jis = new JarInputStream(context.getResourceAsStream(jar)); try { String name = jis.getManifest().getMainAttributes().getValue(MODULE_NAME); if (name != null) { sorter.add(new ModuleSorter.Entry(name, jis.getManifest().getMainAttributes().getValue(MODULE_BASE), jar)); } } finally { jis.close(); } } catch (IOException x) { // ignore this jar _logger.log(Level.WARNING, "Error during jar inspection, ignored", x); } } } catch (Exception x) { throw new ServletException("Failed to sort service modules", x); } return sorter.sort(); } private ApplicationContext scanServiceModules(Iterator<ModuleSorter.Entry> it, ApplicationContext wac, Map<String, String> descs, List<PlatformLifeCycleAware> plcas) throws ServletException { ServletContext context = getServletContext(); boolean isSpecial = plcas == null; if (isSpecial) { plcas = new ArrayList<PlatformLifeCycleAware>(); } try { BurnedInArgumentsObjectFactory factory = new BurnedInArgumentsObjectFactory(ValidationConfiguration.class, _dict); XMLBeanAssembler assembler = new XMLBeanAssembler(factory); while (it.hasNext()) { ModuleSorter.Entry module = it.next(); try { JarInputStream jis = new JarInputStream(context.getResourceAsStream(module.path)); try { String domain = jis.getManifest().getMainAttributes().getValue(DOMAIN_NAME); _logger.fine("Scanning module " + module.name + ", special=" + isSpecial); if (_persistence != null) { factory.setBurnedIn(StorageConfiguration.class, _persistence.getStatementMap(), module.name); } JarEntry entry; while ((entry = jis.getNextJarEntry()) != null) { String name = entry.getName(); if (name == null) continue; if (SERVICE_CONFIG.equals(name)) { _logger.info("ServiceConfiguration:" + module.path + ":" + name); if (isSpecial) { wac = loadServiceModule(wac, domain, module.name, new ByteArrayInputStream(Arrays.read(jis)), descs, plcas); } else { loadServiceModule(wac, domain, module.name, new ByteArrayInputStream(Arrays.read(jis)), descs, plcas); } } else if (_persistence != null && name.startsWith(STORAGE_PREFIX) && name.endsWith(".xml")) { _logger.info("StorageConfiguration:" + module.path + ":" + name); assembler.build(new ByteArrayInputStream(Arrays.read(jis))); } else if (VALIDATION_DIC.equals(name)) { _logger.info("ValidationDictionary:" + module.path + ":" + name); assembler.build(new ByteArrayInputStream(Arrays.read(jis))); } else if (name.startsWith(XILLIUM_PREFIX) && name.endsWith(".xml")) { _logger.info("ApplicationResources:" + module.path + ":" + name); assembler.build(new ByteArrayInputStream(Arrays.read(jis))); } } } finally { jis.close(); } if (isSpecial) { for (PlatformLifeCycleAware plca: plcas) { _logger.info("Configuring SPECIAL PlatformLifeCycleAware " + plca.getClass().getName()); plca.configure(); } for (PlatformLifeCycleAware plca: plcas) { _logger.info("Initalizing SPECIAL PlatformLifeCycleAware " + plca.getClass().getName()); plca.initialize(); } //plcas.clear(); _plca.push(plcas); plcas = new ArrayList<PlatformLifeCycleAware>(); } } catch (IOException x) { // ignore this jar _logger.log(Level.WARNING, "Error during jar inspection, ignored", x); } } } catch (Exception x) { throw new ServletException("Failed to construct an XMLBeanAssembler", x); } _logger.info("Done with service modules scanning (" + (isSpecial ? "SPECIAL" : "REGULAR") + ')'); return wac; } @SuppressWarnings("unchecked") private ApplicationContext loadServiceModule(ApplicationContext wac, String domain, String name, InputStream stream, Map<String, String> desc, List<PlatformLifeCycleAware> plcas) { GenericApplicationContext gac = new GenericApplicationContext(wac); XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(gac); reader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_XSD); reader.loadBeanDefinitions(new InputStreamResource(stream)); gac.refresh(); _logger.info("Loading service modules from ApplicationContext " + gac.getId()); for (String id: gac.getBeanNamesForType(Service.class)) { String fullname = name + '/' + id; try { Class<? extends DataObject> request = ((DynamicService)gac.getBean(id)).getRequestType(); _logger.info("Service '" + fullname + "' request description captured: " + request.getName()); desc.put(fullname, "json:" + DataObject.Util.describe((Class<? extends DataObject>)request)); } catch (ClassCastException x) { try { Class<?> request = Class.forName(gac.getBeanDefinition(id).getBeanClassName()+"$Request"); if (DataObject.class.isAssignableFrom(request)) { _logger.info("Service '" + fullname + "' request description captured: " + request.getName()); desc.put(fullname, "json:" + DataObject.Util.describe((Class<? extends DataObject>)request)); } else { _logger.warning("Service '" + fullname + "' defines a Request type that is not a DataObject"); desc.put(fullname, "json:{}"); } } catch (Exception t) { _logger.warning("Service '" + fullname + "' does not expose its request structure" + t.getClass()); desc.put(fullname, "json:{}"); } } _logger.info("Service '" + fullname + "' class=" + gac.getBean(id).getClass().getName()); _services.put(fullname, (Service)gac.getBean(id)); } for (String id: gac.getBeanNamesForType(PlatformLifeCycleAware.class)) { plcas.add((PlatformLifeCycleAware)gac.getBean(id)); } // Manageable object registration: objects are registered under "bean-id/context-path" String contextPath = getServletContext().getContextPath(); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); for (String id: gac.getBeanNamesForType(Manageable.class)) { try { _logger.info("Registering MBean '" + id + "', domain=" + domain); ObjectName on = new ObjectName(domain == null ? "org.xillium.core.management" : domain, "type", id + contextPath); Manageable manageable = (Manageable)gac.getBean(id); manageable.assignObjectName(on); mbs.registerMBean(manageable, on); _manageables.push(on); } catch (Exception x) { _logger.log(Level.WARNING, "MBean '" + id + "' failed to register", x); } } _logger.info("Done with service modules in ApplicationContext " + gac.getId()); return gac; } }
package org.mwg.core.utility; import org.junit.Assert; import org.junit.Test; import org.mwg.core.CoreConstants; import org.mwg.struct.Buffer; import org.mwg.struct.BufferIterator; import java.util.Arrays; public class BufferBuilderTest { private byte[] data = new byte[]{1, 2, 3, 4, 5}; private byte[] data2 = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17}; private void testWriteAll(org.mwg.struct.Buffer buffer) { //write not initialized buffer buffer.writeAll(data); byte[] res = buffer.data(); Assert.assertEquals(data.length, res.length); for (int i = 0; i < res.length; i++) { Assert.assertEquals(data[i], res[i]); } //write more data than the capacity buffer.writeAll(data2); res = buffer.data(); Assert.assertEquals(data.length + data2.length, res.length); for (int i = 0; i < data.length; i++) { Assert.assertEquals(data[i], res[i]); } for (int i = 0; i < data2.length; i++) { Assert.assertEquals("error for index " + i, data2[i], res[i + data.length]); } //write less data than the capacity buffer.writeAll(data); res = buffer.data(); Assert.assertEquals(data.length + data2.length + data.length, res.length); for (int i = 0; i < data.length; i++) { Assert.assertEquals(data[i], res[i]); } for (int i = 0; i < data2.length; i++) { Assert.assertEquals("error for index " + i, data2[i], res[i + data.length]); } for (int i = 0; i < data.length; i++) { Assert.assertEquals("error for index " + i, data[i], res[i + data.length + data2.length]); } } private void testIterator(org.mwg.struct.Buffer buffer) { buffer.writeAll("123".getBytes()); buffer.write(CoreConstants.BUFFER_SEP); buffer.writeAll("567".getBytes()); buffer.write(CoreConstants.BUFFER_SEP); buffer.writeAll("89".getBytes()); BufferIterator it = buffer.iterator(); Assert.assertEquals(it.hasNext(), true); Buffer view1 = it.next(); Assert.assertNotNull(view1); Assert.assertEquals(view1.size(), 3); byte[] view1flat = view1.data(); view1flat[0] = "123".getBytes()[0]; view1flat[1] = "123".getBytes()[1]; view1flat[2] = "123".getBytes()[2]; Assert.assertEquals(it.hasNext(), true); Buffer view2 = it.next(); Assert.assertNotNull(view2); Assert.assertEquals(view2.size(), 3); byte[] view2flat = view2.data(); view2flat[0] = "567".getBytes()[0]; view2flat[1] = "567".getBytes()[1]; view2flat[2] = "567".getBytes()[2]; Assert.assertEquals(it.hasNext(), true); Buffer view3 = it.next(); Assert.assertNotNull(view3); Assert.assertEquals(view3.size(), 2); byte[] view3flat = view3.data(); view3flat[0] = "89".getBytes()[0]; view3flat[1] = "89".getBytes()[1]; Assert.assertEquals(it.hasNext(), false); } private void testIteratorNull(org.mwg.struct.Buffer buffer) { buffer.write(CoreConstants.BUFFER_SEP); buffer.write(CoreConstants.BUFFER_SEP); BufferIterator it = buffer.iterator(); Assert.assertTrue(it.hasNext()); Buffer view = it.next(); Assert.assertNotNull(view); Assert.assertEquals(view.size(), 0); Buffer view2 = it.next(); Assert.assertNotNull(view2); Assert.assertEquals(view2.size(), 0); Buffer view3 = it.next(); Assert.assertNotNull(view3); Assert.assertEquals(view3.size(), 0); Buffer view4 = it.next(); Assert.assertNull(view4); } @Test public void testWriteAllHeap() { org.mwg.struct.Buffer buffer = BufferBuilder.newHeapBuffer(); testWriteAll(buffer); } @Test public void testWriteAllOffHeap() { org.mwg.struct.Buffer buffer = BufferBuilder.newOffHeapBuffer(); testWriteAll(buffer); } @Test public void testIteratorHeap() { org.mwg.struct.Buffer buffer = BufferBuilder.newHeapBuffer(); testIterator(buffer); buffer.free(); buffer = BufferBuilder.newHeapBuffer(); testIteratorNull(buffer); buffer.free(); } @Test public void testIteratorOffHeap() { org.mwg.struct.Buffer buffer = BufferBuilder.newOffHeapBuffer(); testIterator(buffer); buffer.free(); buffer = BufferBuilder.newOffHeapBuffer(); testIteratorNull(buffer); buffer.free(); } //@Test public void testIteratorHeap2(){ byte[] bytes = new byte[]{12,11,CoreConstants.BUFFER_SEP,87,CoreConstants.BUFFER_SEP,87,45}; Buffer buffer = BufferBuilder.newHeapBuffer(); buffer.writeAll(bytes); BufferIterator it = buffer.iterator(); Assert.assertArrayEquals(new byte[]{12,11},it.next().data()); Assert.assertArrayEquals(new byte[]{87},it.next().data()); Assert.assertArrayEquals(new byte[]{12,45},it.next().data()); Assert.assertEquals(false,it.hasNext()); } //@Test public void testDiffBetweenEmptyViewAndOneElementView() { byte[] bytes = new byte[] {14,15,CoreConstants.BUFFER_SEP,127,CoreConstants.BUFFER_SEP,CoreConstants.BUFFER_SEP}; Buffer buffer = BufferBuilder.newHeapBuffer(); buffer.writeAll(bytes); BufferIterator it = buffer.iterator(); while (it.hasNext()) { System.out.println(Arrays.toString(it.next().data())); } } }
package com.liferay.lms; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import java.util.Calendar; import java.util.List; import javax.portlet.PortletException; import javax.portlet.ResourceRequest; import javax.portlet.ResourceResponse; import javax.servlet.http.HttpServletRequest; import org.jfree.chart.ChartFactory; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.AxisLocation; import org.jfree.chart.axis.CategoryAxis; import org.jfree.chart.axis.CategoryLabelPositions; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.labels.StandardCategoryToolTipGenerator; import org.jfree.chart.plot.CategoryPlot; import org.jfree.chart.plot.DatasetRenderingOrder; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.renderer.category.LineAndShapeRenderer; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; import com.liferay.lms.model.Course; import com.liferay.lms.model.LearningActivity; import com.liferay.lms.model.LearningActivityResult; import com.liferay.lms.model.Module; import com.liferay.lms.model.ModuleResult; import com.liferay.lms.service.ClpSerializer; import com.liferay.lms.service.CourseLocalServiceUtil; import com.liferay.lms.service.LearningActivityResultLocalServiceUtil; import com.liferay.lms.service.LearningActivityServiceUtil; import com.liferay.lms.service.ModuleLocalServiceUtil; import com.liferay.lms.service.ModuleResultLocalServiceUtil; import com.liferay.portal.kernel.bean.PortletBeanLocatorUtil; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.language.LanguageUtil; import com.liferay.portal.kernel.servlet.ServletResponseUtil; import com.liferay.portal.kernel.servlet.SessionErrors; import com.liferay.portal.kernel.util.ContentTypes; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.kernel.util.StringUtil; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.kernel.util.WebKeys; import com.liferay.portal.theme.ThemeDisplay; import com.liferay.portal.util.PortalUtil; import com.liferay.util.bridges.mvc.MVCPortlet; import com.lowagie.text.BadElementException; import com.lowagie.text.Chunk; import com.lowagie.text.Document; import com.lowagie.text.Element; import com.lowagie.text.Font; import com.lowagie.text.FontFactory; import com.lowagie.text.HeaderFooter; import com.lowagie.text.Image; import com.lowagie.text.PageSize; import com.lowagie.text.Paragraph; import com.lowagie.text.Rectangle; import com.lowagie.text.pdf.DefaultFontMapper; import com.lowagie.text.pdf.PdfCell; import com.lowagie.text.pdf.PdfContentByte; import com.lowagie.text.pdf.PdfPCell; import com.lowagie.text.pdf.PdfPTable; import com.lowagie.text.pdf.PdfTemplate; import com.lowagie.text.pdf.PdfWriter; /** * Portlet implementation class UserProgress */ public class UserProgress extends MVCPortlet { private final String fileName = "IEC.pdf"; private final Color rojo = new Color(190,50,28); private final Color negro = new Color(0,0,0); private final Color blanco = new Color(255,255,255); private final Color gris = new Color(222,222,222); GradientPaint gradientGray = new GradientPaint(0.0F, 0.0F, Color.GRAY, 0.0F, 0.0F, new Color(208, 208, 208)); GradientPaint gradientBlue = new GradientPaint(0.0F, 0.0F, Color.BLUE, 0.0F, 0.0F, new Color(3, 8, 111)); GradientPaint gradientRed = new GradientPaint(0.0F, 0.0F, Color.RED, 0.0F, 0.0F, new Color(3, 8, 111)); private final int cols = 4; private Font fontTitle = new Font(); private Font fontNormal = new Font(); private Font fontHeaders = new Font(); private Font fontTitleModule = new Font(); private final boolean NONE_PAGINATOR = false; private final int TITLE_CHAR_LIMIT = 50; public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse) throws IOException, PortletException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest .getAttribute(WebKeys.THEME_DISPLAY); loadFonts(); write_IEC_Pdf(baos,themeDisplay,PortalUtil.getHttpServletRequest(resourceRequest)); ServletResponseUtil.sendFile(PortalUtil.getHttpServletRequest(resourceRequest), PortalUtil.getHttpServletResponse(resourceResponse), fileName, baos.toByteArray(), ContentTypes.APPLICATION_PDF); } catch (Exception e) { e.printStackTrace(); SessionErrors.add(resourceRequest, "export.pdf.userstats.error"); } finally{ baos.close(); } } private void write_IEC_Pdf(OutputStream outputStream, ThemeDisplay themeDisplay, HttpServletRequest request) throws Exception { Course course = CourseLocalServiceUtil.getCourseByGroupCreatedId(themeDisplay.getScopeGroupId()); String titleReport = LanguageUtil.get(themeDisplay.getLocale(), "userprogress.export.pdf.title"); Document document = new Document(PageSize.A4.rotate()); PdfWriter writer = PdfWriter.getInstance(document, outputStream); // Header String courseTitle = course.getTitle(themeDisplay.getLocale()); courseTitle = courseTitle != null && courseTitle.length() > TITLE_CHAR_LIMIT ? courseTitle.substring(0, TITLE_CHAR_LIMIT) + "..." : courseTitle; Chunk reportTitle = new Chunk(titleReport + ": " + courseTitle); reportTitle.setFont(fontTitle); reportTitle.setBackground(rojo, 4, 4, 475, 5); // extraLeft, extraBottom, extraRight, extraTop Paragraph paragraph = new Paragraph(reportTitle); paragraph.setAlignment(Element.ALIGN_JUSTIFIED); paragraph.setSpacingAfter(5); PdfPTable tbHeader = new PdfPTable(1); tbHeader.setWidthPercentage(100); // PdfPCell cellHeaderImg = new PdfPCell(getLogoImg(request, themeDisplay)); // cellHeaderImg.setBorder(PdfCell.NO_BORDER); // cellHeaderImg.setHorizontalAlignment(Element.ALIGN_LEFT); // tbHeader.addCell(cellHeaderImg); PdfPCell cellHeaderTxt = new PdfPCell(paragraph); cellHeaderTxt.setBorder(PdfCell.NO_BORDER); cellHeaderTxt.setHorizontalAlignment(Element.ALIGN_LEFT); tbHeader.addCell(cellHeaderTxt); Paragraph paragraphHeader = new Paragraph(); paragraphHeader.add(tbHeader); HeaderFooter header=new HeaderFooter(paragraphHeader,NONE_PAGINATOR); header.setBorder(Rectangle.NO_BORDER); header.setAlignment(Element.ALIGN_LEFT); document.setHeader(header); document.open(); // Datos del curso PdfPTable table = new PdfPTable(cols); table.setWidthPercentage(100); table.setSpacingBefore(10f); List<Module> modules = ModuleLocalServiceUtil.findAllInGroup(themeDisplay.getScopeGroupId()); // Modulos for(Module theModule:modules) { PdfPCell cellTitleModule = new PdfPCell(new Paragraph(theModule.getTitle(themeDisplay.getLocale()), fontTitleModule)); cellTitleModule.setColspan(cols); cellTitleModule.setBorder(PdfCell.NO_BORDER); cellTitleModule.setHorizontalAlignment(Element.ALIGN_LEFT); cellTitleModule.setPaddingTop(10); cellTitleModule.setPaddingBottom(10); table.addCell(cellTitleModule); addCellTable(LanguageUtil.get(themeDisplay.getLocale(), "userprogress.export.pdf.header1"), fontHeaders, blanco, table); addCellTable(LanguageUtil.get(themeDisplay.getLocale(), "userprogress.export.pdf.header2"), fontHeaders, blanco, table); addCellTable(LanguageUtil.get(themeDisplay.getLocale(), "userprogress.export.pdf.header3"), fontHeaders, blanco, table); addCellTable(LanguageUtil.get(themeDisplay.getLocale(), "userprogress.export.pdf.header4"), fontHeaders, blanco, table); PdfPCell cellLine = new PdfPCell(); cellLine.setBorder(Rectangle.BOTTOM); cellLine.setColspan(cols); table.addCell(cellLine); List<LearningActivity> activities=LearningActivityServiceUtil.getLearningActivitiesOfModule(theModule.getModuleId()); long row = 0; // Actividades for(LearningActivity activity: activities) { Color color = (row%2 == 0) ? gris : blanco; String score= "-"; String status="userprogress.export.pdf.act.status.not.started"; if(LearningActivityResultLocalServiceUtil.existsLearningActivityResult(activity.getActId(), themeDisplay.getUserId())){ status="userprogress.export.pdf.status.started"; LearningActivityResult learningActivityResult=LearningActivityResultLocalServiceUtil.getByActIdAndUserId(activity.getActId(), themeDisplay.getUserId()); score=(learningActivityResult!=null)?LearningActivityResultLocalServiceUtil.translateResult(themeDisplay.getLocale(), learningActivityResult.getResult(), activity.getGroupId()):""; if(learningActivityResult.getEndDate()!=null) { status="not-passed"; } if(learningActivityResult.isPassed()) { status="passed"; } } Calendar calActual = Calendar.getInstance(themeDisplay.getUser().getTimeZone(), themeDisplay.getUser().getLocale()); Calendar calActiviy = Calendar.getInstance(themeDisplay.getUser().getTimeZone(), themeDisplay.getUser().getLocale()); calActiviy.setTime(activity.getEnddate()); StringBuilder time = new StringBuilder(); long difMiliseconds = calActiviy.getTimeInMillis() - calActual.getTimeInMillis(); if(difMiliseconds > 0) { long dias = Math.abs(difMiliseconds/(3600000*24)); long restoHoras = difMiliseconds%(3600000*24); long horas = Math.abs(restoHoras/3600000); long restoMinutos = restoHoras%3600000; long minutos = Math.abs(restoMinutos/(60 * 1000)); time.append(dias + StringPool.SPACE + LanguageUtil.get(themeDisplay.getLocale(), "userprogress.export.pdf.days")); time.append(StringPool.SPACE + horas + StringPool.SPACE + LanguageUtil.get(themeDisplay.getLocale(), "userprogress.export.pdf.hours")); time.append(StringPool.SPACE + minutos + StringPool.SPACE + LanguageUtil.get(themeDisplay.getLocale(), "userprogress.export.pdf.minuts")); } else { time.append(LanguageUtil.get(themeDisplay.getLocale(), "userprogress.export.pdf.status.elapsed")); } // Titulo addCellTable(activity.getTitle(themeDisplay.getLocale()), fontNormal, color, table); // Estado addCellTable(LanguageUtil.get(themeDisplay.getLocale(), status.toString()) , fontNormal, color, table); // Resultado addCellTable((score.trim().equalsIgnoreCase("-")) ? score: score + "/100", fontNormal, color, table); // Tiempo Restante addCellTable(time.toString(), fontNormal, color, table); row++; } } document.add(table); // Grafica document.newPage(); document.add(Chunk.NEWLINE); PdfContentByte cb = writer.getDirectContent(); float width = 475; float height = PageSize.A4.getHeight() / 3; PdfTemplate template = cb.createTemplate(width, height); Graphics2D graphics2d = template.createGraphics(width, height, new DefaultFontMapper()); Rectangle2D r2d2 = new Rectangle2D.Double(0, 0, width, height); getIecChart(themeDisplay).draw(graphics2d, r2d2); graphics2d.dispose(); cb.addTemplate(template, 200, 100); document.close(); } private void addCellTable(String text, Font font, Color backGroundColor, PdfPTable table) { PdfPCell cell = new PdfPCell(new Paragraph(text, font)); cell.setBackgroundColor(backGroundColor); cell.setBorder(PdfCell.NO_BORDER); cell.setVerticalAlignment(PdfCell.ALIGN_MIDDLE); table.addCell(cell); } private JFreeChart getIecChart(ThemeDisplay themeDisplay) throws SystemException { final CategoryDataset porcentajeModulos = getDataSetPercentajes(themeDisplay); String chartTitle = LanguageUtil.get(themeDisplay.getLocale(), "userprogress.export.pdf.title"); String chartLabelLegend = LanguageUtil.get(themeDisplay.getLocale(), "userprogress.export.pdf.chart.legend.label"); String chartLabellLeft = LanguageUtil.get(themeDisplay.getLocale(), "userprogress.export.pdf.chart.label.left"); final JFreeChart chart = ChartFactory.createBarChart( chartTitle, // title chartLabelLegend, // domain axis label chartLabellLeft, // range axis label porcentajeModulos, // data PlotOrientation.VERTICAL, true, // legend true, // tooltips false // url ); chart.setBackgroundPaint(Color.white); final CategoryPlot plot = chart.getCategoryPlot(); plot.setBackgroundPaint(new Color(222,222,222)); plot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_RIGHT); plot.getRangeAxis(0).setRange(0, 100); final CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45); plot.getRenderer().setSeriesPaint(0, gradientGray); final CategoryDataset horasRestantes = getDataSetTimeLeft(themeDisplay); plot.setDataset(1, horasRestantes); plot.mapDatasetToRangeAxis(1, 1); final ValueAxis axis2 = new NumberAxis(LanguageUtil.get(themeDisplay.getLocale(), "userprogress.export.pdf.chart.label.right")); plot.setRangeAxis(1, axis2); final LineAndShapeRenderer renderer2 = new LineAndShapeRenderer(); renderer2.setBaseLinesVisible(false); renderer2.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator()); plot.setRenderer(1, renderer2); plot.getRenderer(1).setSeriesPaint(0, gradientBlue); // Mostrar el primer dataset por debajo del resto de dataset plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); return chart; } private DefaultCategoryDataset getDataSetPercentajes(ThemeDisplay themeDisplay) throws SystemException{ final DefaultCategoryDataset dataset = new DefaultCategoryDataset( ); List<Module> modules=ModuleLocalServiceUtil.findAllInGroup(themeDisplay.getScopeGroupId()); if(Validator.isNotNull(modules) && modules.size() > 0){ String label = LanguageUtil.get(themeDisplay.getLocale(), "userprogress.export.pdf.chart.label.left"); for (Module module : modules) { ModuleResult moduleResult=ModuleResultLocalServiceUtil.getByModuleAndUser(module.getModuleId(),themeDisplay.getUserId()); double porcentaje = (moduleResult != null && moduleResult.getResult() > 0) ? moduleResult.getResult() : 0; dataset.addValue(porcentaje, label, module.getTitle(themeDisplay.getLocale())); } } return dataset; } private DefaultCategoryDataset getDataSetTimeLeft(ThemeDisplay themeDisplay) throws SystemException{ final DefaultCategoryDataset dataset = new DefaultCategoryDataset( ); List<Module> modules=ModuleLocalServiceUtil.findAllInGroup(themeDisplay.getScopeGroupId()); if(Validator.isNotNull(modules) && modules.size() > 0){ String label = LanguageUtil.get(themeDisplay.getLocale(), "userprogress.export.pdf.chart.label.right"); Calendar calActual = Calendar.getInstance(themeDisplay.getUser().getTimeZone(), themeDisplay.getUser().getLocale()); Calendar calModule = Calendar.getInstance(themeDisplay.getUser().getTimeZone(), themeDisplay.getUser().getLocale()); for (Module module : modules) { calModule.setTime(module.getEndDate()); long difMiliseconds = calModule.getTimeInMillis() - calActual.getTimeInMillis(); long dias = 0; if(difMiliseconds > 0) { dias = Math.abs(difMiliseconds/(3600000*24)); } dataset.addValue(dias, label, module.getTitle(themeDisplay.getLocale())); } } return dataset; } private void loadFonts() { ClassLoader classLoader = (ClassLoader) PortletBeanLocatorUtil.locate(ClpSerializer.getServletContextName(),"portletClassLoader"); String pathNunitoDir = classLoader.getResource("default-fonts").toString() + "nunito" + System.getProperty("file.separator") + "ttf" + System.getProperty("file.separator"); FontFactory.register(pathNunitoDir + "Nunito-Bold.ttf", "nunito-bold"); FontFactory.register(pathNunitoDir + "Nunito-Light.ttf", "nunito-light"); FontFactory.register(pathNunitoDir + "Nunito-Regular.ttf", "nunito-regular"); fontTitle.setFamily("nunito"); fontTitle.setSize(14); fontTitle.setColor(blanco); fontTitle.setStyle(Font.BOLD); fontNormal.setFamily("nunito"); fontNormal.setSize(12); fontNormal.setColor(negro); fontHeaders.setFamily("nunito"); fontHeaders.setSize(11); fontHeaders.setColor(negro); fontHeaders.setStyle(Font.BOLD); fontTitleModule.setFamily("nunito"); fontTitleModule.setSize(12); fontTitleModule.setColor(rojo); } // private Image getLogoImg(HttpServletRequest request, ThemeDisplay themeDisplay){ // // Imagen corporativa // Image image = null; // try { // image = Image.getInstance( request.getRequestURL().toString().replace(request.getRequestURI(),"") + themeDisplay.getCompanyLogo()); // image.setAlignment(Image.LEFT); // image.scaleToFit(800,34); // //image.scalePercent(100); // } catch (MalformedURLException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } catch (BadElementException e) { // e.printStackTrace(); // return image; }
package com.xpn.xwiki.it.selenium.framework; import junit.framework.Assert; /** * Implementation of skin-related actions for the Colibri skin. * * @version $Id$ */ public class ColibriSkinExecutor extends AlbatrossSkinExecutor { public ColibriSkinExecutor(AbstractXWikiTestCase test) { super(test); } /** * {@inheritDoc} */ @Override public boolean isAuthenticated() { return getTest().isElementPresent("tmUser"); } /** * {@inheritDoc} */ @Override public void loginAsAdmin() { // First verify if the logged in user is not already the Administrator. That'll save us execution time. if (!getTest().isElementPresent("//div[@id='tmUser']/a[contains(@href, '/xwiki/bin/view/XWiki/Admin')]")) { login("Admin", "admin", false); } } /** * {@inheritDoc} */ @Override public void login(String username, String password, boolean rememberme) { getTest().open("Main", "WebHome"); if (isAuthenticated()) { logout(); } clickLogin(); getTest().setFieldValue("j_username", username); getTest().setFieldValue("j_password", password); if (rememberme) { getTest().checkField("rememberme"); } getTest().submit(); Assert.assertTrue("User has not been authenticated", isAuthenticated()); } /** * {@inheritDoc} */ @Override public void logout() { Assert.assertTrue("User wasn't authenticated.", isAuthenticated()); getTest().clickLinkWithLocator("//div[@id='tmLogout']/a"); Assert.assertFalse("The user is still authenticated after a logout.", isAuthenticated()); } /** * {@inheritDoc} */ @Override public void clickLogin() { getTest().clickLinkWithLocator("//div[@id='tmLogin']/a"); assertIsLoginPage(); } /** * {@inheritDoc} */ @Override public void clickRegister() { getTest().clickLinkWithLocator("//div[@id='tmRegister']/a"); assertIsRegisterPage(); } }
package org.eclipse.birt.report.engine.nLayout.area.impl; import java.awt.Color; import java.util.ArrayList; import java.util.List; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.report.engine.api.InstanceID; import org.eclipse.birt.report.engine.content.IBandContent; import org.eclipse.birt.report.engine.content.ICellContent; import org.eclipse.birt.report.engine.content.IColumn; import org.eclipse.birt.report.engine.content.IContent; import org.eclipse.birt.report.engine.content.ILabelContent; import org.eclipse.birt.report.engine.content.IRowContent; import org.eclipse.birt.report.engine.content.IStyle; import org.eclipse.birt.report.engine.content.ITableContent; import org.eclipse.birt.report.engine.content.impl.ReportContent; import org.eclipse.birt.report.engine.css.dom.StyleDeclaration; import org.eclipse.birt.report.engine.css.engine.StyleConstants; import org.eclipse.birt.report.engine.executor.ExecutionContext; import org.eclipse.birt.report.engine.ir.DimensionType; import org.eclipse.birt.report.engine.ir.EngineIRConstants; import org.eclipse.birt.report.engine.ir.GridItemDesign; import org.eclipse.birt.report.engine.layout.pdf.util.PropertyUtil; import org.eclipse.birt.report.engine.nLayout.LayoutContext; import org.eclipse.birt.report.engine.nLayout.area.IArea; import org.eclipse.birt.report.engine.nLayout.area.style.BackgroundImageInfo; import org.eclipse.birt.report.engine.nLayout.area.style.BoxStyle; import org.eclipse.birt.report.engine.presentation.UnresolvedRowHint; import org.eclipse.birt.report.engine.util.ResourceLocatorWrapper; public class TableArea extends RepeatableArea { protected transient TableLayoutInfo layoutInfo; protected transient TableLayout layout; protected RowArea unresolvedRow; protected int startCol; protected int endCol; public TableArea( ContainerArea parent, LayoutContext context, IContent content ) { super( parent, context, content ); } TableArea( TableArea table ) { super( table ); layout = table.layout; } public boolean contains( RowArea row ) { return children.contains( row ); } public void addRow( RowArea row ) { if ( layout != null ) { layout.addRow( row, context.isFixedLayout( ) ); } } public int getColumnCount( ) { if ( content != null ) { return ( (ITableContent) content ).getColumnCount( ); } return 0; } protected boolean needRepeat( ) { ITableContent table = (ITableContent) content; if ( table != null && table.isHeaderRepeat( ) ) { return true; } return false; } public TableArea cloneArea( ) { return new TableArea( this ); } public int getXPos( int columnID ) { if ( layoutInfo != null ) { return layoutInfo.getXPosition( columnID ); } return 0; } public boolean isGridDesign( ) { if ( content != null ) { Object gen = content.getGenerateBy( ); return gen instanceof GridItemDesign; } return false; } protected void buildProperties( IContent content, LayoutContext context ) { IStyle style = content.getStyle( ); if ( style != null && !style.isEmpty( ) ) { boxStyle = new BoxStyle( ); IStyle cs = content.getComputedStyle( ); Color color = PropertyUtil.getColor( cs .getProperty( IStyle.STYLE_BACKGROUND_COLOR ) ); if ( color != null ) { boxStyle.setBackgroundColor( color ); } String url = style.getBackgroundImage( ); if ( url != null ) { ResourceLocatorWrapper rl = null; ExecutionContext exeContext = ( (ReportContent) content .getReportContent( ) ).getExecutionContext( ); if ( exeContext != null ) { rl = exeContext.getResourceLocator( ); } BackgroundImageInfo backgroundImage = new BackgroundImageInfo( getImageUrl( url ), style.getProperty( IStyle.STYLE_BACKGROUND_REPEAT ), 0, 0, 0, 0, rl ); boxStyle.setBackgroundImage( backgroundImage ); } localProperties = new LocalProperties( ); int maw = parent.getMaxAvaWidth( ); localProperties.setMarginBottom( getDimensionValue( cs .getProperty( IStyle.STYLE_MARGIN_BOTTOM ), maw ) ); localProperties.setMarginLeft( getDimensionValue( cs .getProperty( IStyle.STYLE_MARGIN_LEFT ), maw ) ); localProperties.setMarginTop( getDimensionValue( cs .getProperty( IStyle.STYLE_MARGIN_TOP ), maw ) ); localProperties.setMarginRight( getDimensionValue( cs .getProperty( IStyle.STYLE_MARGIN_RIGHT ), maw ) ); if ( !isInlineStacking ) { pageBreakAfter = cs.getProperty( IStyle.STYLE_PAGE_BREAK_AFTER ); pageBreakInside = cs .getProperty( IStyle.STYLE_PAGE_BREAK_INSIDE ); pageBreakBefore = cs .getProperty( IStyle.STYLE_PAGE_BREAK_BEFORE ); } } else { hasStyle = false; boxStyle = BoxStyle.DEFAULT; localProperties = LocalProperties.DEFAULT; } bookmark = content.getBookmark( ); action = content.getHyperlinkAction( ); } public void initialize( ) throws BirtException { calculateSpecifiedWidth( content ); buildProperties( content, context ); layoutInfo = resolveTableFixedLayout( content, context ); width = layoutInfo.getTableWidth( ); maxAvaWidth = layoutInfo.getTableWidth( ); ITableContent tableContent = (ITableContent) content; int start = 0; int end = tableContent.getColumnCount( ) - 1; layout = new TableLayout( tableContent, layoutInfo, start, end ); parent.add( this ); // No longer using addDummyColumnForRTL // TODO addDummyColumnForRTL addCaption( ( (ITableContent) content ).getCaption( ) ); } protected void addCaption( String caption ) throws BirtException { if ( caption == null || "".equals( caption ) ) //$NON-NLS-1$ { return; } ReportContent report = (ReportContent) content.getReportContent( ); IRowContent row = report.createRowContent( ); row.setParent( content ); ICellContent cell = report.createCellContent( ); cell.setColSpan( getColumnCount( ) ); cell.setColumn( 0 ); StyleDeclaration cstyle = new StyleDeclaration( report.getCSSEngine( ) ); cstyle.setProperty( IStyle.STYLE_BORDER_TOP_STYLE, IStyle.HIDDEN_VALUE ); cstyle .setProperty( IStyle.STYLE_BORDER_LEFT_STYLE, IStyle.HIDDEN_VALUE ); cstyle.setProperty( IStyle.STYLE_BORDER_RIGHT_STYLE, IStyle.HIDDEN_VALUE ); cell.setInlineStyle( cstyle ); cell.setParent( row ); ILabelContent captionLabel = report.createLabelContent( ); captionLabel.setParent( cell ); captionLabel.setText( caption ); StyleDeclaration style = new StyleDeclaration( report.getCSSEngine( ) ); style.setProperty( IStyle.STYLE_TEXT_ALIGN, IStyle.CENTER_VALUE ); captionLabel.setInlineStyle( style ); RowArea captionRow = new RowArea( this, context, row ); captionRow.isDummy = true; captionRow.setParent( this ); captionRow.setWidth( width ); captionRow.initialize( ); CellArea captionCell = new CellArea( captionRow, context, cell ); captionCell.setWidth( width ); captionCell.setMaxAvaWidth( width ); captionCell.initialize( ); captionCell.isDummy = true; captionCell.setRowSpan( 1 ); captionRow.children.add( captionCell ); BlockTextArea captionText = new BlockTextArea( captionCell, context, captionLabel ); captionText.isDummy = true; captionText.layout( ); int h = captionText.getAllocatedHeight( ); captionCell.setContentHeight( h ); captionRow.setHeight( captionCell.getAllocatedHeight( ) ); captionRow.finished = true; add( captionRow ); if ( repeatList == null ) { repeatList = new ArrayList( ); } repeatList.add( captionRow ); update( captionRow ); } protected boolean isInHeaderBand( ) { if ( children.size( ) > 0 ) { ContainerArea child = (ContainerArea) children .get( children.size( ) - 1 ); IContent childContent = child.getContent( ); if ( childContent != null ) { if ( childContent.getContentType( ) == IContent.TABLE_GROUP_CONTENT ) { return false; } IContent band = (IContent) childContent.getParent( ); if ( band instanceof IBandContent ) { int type = ( (IBandContent) band ).getBandType( ); if ( type != IBandContent.BAND_HEADER ) { return false; } } } } return true; } public SplitResult split( int height, boolean force ) throws BirtException { SplitResult result = super.split( height, force ); if ( result.getResult( ) != null ) { TableArea tableResult = (TableArea) result.getResult( ); unresolvedRow = tableResult.getLastRow( ); int h = tableResult.layout.resolveAll( unresolvedRow ); if ( h > 0 ) { tableResult.setHeight( tableResult.getHeight( ) + h ); } tableResult.resolveBottomBorder( ); //layout.setUnresolvedRow( unresolvedRow ); if ( context.isFixedLayout( ) ) { FixedLayoutPageHintGenerator pageHintGenerator = context .getPageHintGenerator( ); if ( pageHintGenerator != null && unresolvedRow != null ) { InstanceID unresolvedTableIID = unresolvedRow .getTableArea( ).getContent( ).getInstanceID( ); // this iid can be null, because the table may be generated // from HTML2Content. // in this case, they are ignored by unresloved row hint. // Currently, large HTML text is not supported to be split. if ( unresolvedTableIID != null ) { pageHintGenerator.addUnresolvedRowHint( unresolvedTableIID.toUniqueString( ), convertRowToHint( unresolvedRow ) ); } } } } relayoutChildren( ); return result; } private UnresolvedRowHint convertRowToHint( RowArea row ) { IRowContent rowContent = (IRowContent) row.getContent( ); ITableContent table = rowContent.getTable( ); InstanceID tableId = table.getInstanceID( ); InstanceID rowId = rowContent.getInstanceID( ); UnresolvedRowHint hint = new UnresolvedRowHint( tableId .toUniqueString( ), rowId.toUniqueString( ) ); if ( row.cells != null ) { for ( int i = 0; i < row.cells.length; i++ ) { AbstractArea area = (AbstractArea) row.cells[i]; String style = null; if ( area instanceof DummyCell ) { CellArea cell = ( (DummyCell) area ).getCell( ); ICellContent cellContent = (ICellContent) cell.getContent( ); if ( cellContent != null ) { style = cellContent.getStyle( ).getCssText( ); } hint.addUnresolvedCell( style, cell.columnID, ( (DummyCell) area ).colSpan, ( (DummyCell) area ).rowSpan ); } else if ( area instanceof CellArea ) { CellArea cell = (CellArea) area; ICellContent cellContent = (ICellContent) cell.getContent( ); if ( cellContent != null ) { style = cellContent.getStyle( ).getCssText( ); } // hint.addUnresolvedCell( style, cell.columnID, cell.colSpan, // cell.rowSpan ); hint.addUnresolvedCell( style, cellContent.getColumn( ), cellContent.getColSpan( ), cellContent.getRowSpan( ) ); } } } return hint; } protected RowArea getLastRow( ContainerArea container ) { int count = container.getChildrenCount( ); for ( int i = count - 1; i >= 0; i { IArea child = container.getChild( i ); if ( child instanceof RowArea ) { return (RowArea) child; } else if ( child instanceof ContainerArea ) { RowArea lastRow = getLastRow( (ContainerArea) child ); if ( lastRow != null ) { return lastRow; } } else { return null; } } return null; } protected RowArea getLastRow( ) { return getLastRow( this ); } public void resolveBottomBorder( ) { RowArea lastRow = getLastRow( ); if ( lastRow != null ) { if ( lastRow.cells != null ) { int bw = 0; for ( int i = 0; i < lastRow.cells.length; i++ ) { if ( lastRow.cells[i] != null ) { bw = Math.max( bw, layout .resolveBottomBorder( lastRow.cells[i] ) ); i = i + lastRow.cells[i].getColSpan( ) - 1; } } if ( bw > 0 ) { lastRow.setHeight( bw + lastRow.getHeight( ) ); for ( int i = 0; i < lastRow.cells.length; i++ ) { if ( lastRow.cells[i] != null ) { if ( lastRow.cells[i] instanceof DummyCell ) { // FIXME CellArea c = ( (DummyCell) lastRow.cells[i] ) .getCell( ); } else { lastRow.cells[i].setHeight( lastRow.cells[i] .getHeight( ) + bw ); } i = i + lastRow.cells[i].getColSpan( ) - 1; } } } } // FIMXE update group/table height; } } protected String getNextRowId( RowArea row ) { RowArea nextRow = layout.getNextRow( row ); if ( nextRow != null ) { InstanceID id = nextRow.getContent( ).getInstanceID( ); if ( id != null ) { return id.toUniqueString( ); } } return null; } protected boolean setUnresolvedRow = false; protected void setUnresolvedRow( ) { if ( !setUnresolvedRow ) { layout.setUnresolvedRow( unresolvedRow ); setUnresolvedRow = true; } } public void relayoutChildren( ) throws BirtException { String nextRowId = null; if ( unresolvedRow != null ) { nextRowId = this.getNextRowId( unresolvedRow ); } layout.clear( ); setUnresolvedRow = false; /*** * 1. collect all rows * 2. use nextRowId to collect all rows little than the rowId * 3. udpate the rowSpan in collection 2 * 4. add all rows to layout */ List<RowArea> rows = new ArrayList<RowArea>( ); collectRows( this, layout, rows ); int rowCount = getRowCountNeedResolved( rows, nextRowId ); boolean resolved = false; if ( rowCount > 0 && unresolvedRow != null ) { for ( int i = 0; i < rowCount; i++ ) { resolved = resolveRowSpan( rows.get( i ), unresolvedRow, rowCount - i ) || resolved; } } addRows( this, layout, nextRowId ); if(!resolved) { setUnresolvedRow( ); } } protected boolean resolveRowSpan(RowArea row, RowArea unresolvedRow, int rowCount) { boolean resolved = false; for ( int i = startCol; i <= endCol; i++ ) { CellArea cell = row.getCell( i ); CellArea uCell = unresolvedRow.getCell( i ); if ( cell != null && uCell != null ) { IContent cellContent = cell.getContent( ); IContent uCellContent = cell.getContent( ); if ( cellContent == uCellContent ) { int rowSpan = 0; if ( unresolvedRow.finished ) { rowSpan = uCell.getRowSpan( ) + rowCount - 1; } else { rowSpan = uCell.getRowSpan( ) + rowCount; } if ( rowSpan < cell.getRowSpan( ) && rowSpan >= 1 ) { cell.setRowSpan( rowSpan ); resolved = true; setUnresolvedRow = true; } } i = i + cell.getColSpan( ); } } return resolved; } protected int getRowCountNeedResolved( List<RowArea> rows, String rowId ) { for ( int i = 0; i < rows.size( ); i++ ) { RowArea row = rows.get( i ); InstanceID id = row.getContent( ).getInstanceID( ); if ( rowId != null && id != null && rowId.equals( id.toUniqueString( ) ) ) { return i ; } } return rows.size( ); } protected void collectRows(ContainerArea container, TableLayout layout, List<RowArea> rows) { if ( container instanceof RowArea ) { RowArea row = (RowArea) container; if ( row.finished ) { rows.add( row ); } } else { int size = container.getChildrenCount( ); for ( int i = 0; i < size; i++ ) { ContainerArea child = (ContainerArea) container.getChild( i ); collectRows( child, layout, rows ); } } } protected void addRows( ContainerArea container, TableLayout layout, String rowId) throws BirtException { if ( container instanceof RowArea ) { RowArea row = (RowArea) container; InstanceID id = row.getContent( ).getInstanceID( ); if ( rowId != null && id != null && rowId.equals( id.toUniqueString( ) ) ) { setUnresolvedRow( ); } if ( row.needResolveBorder ) { int size = row.getChildrenCount( ); for ( int i = 0; i < size; i++ ) { CellArea cell = (CellArea) row.getChild( i ); int ch = cell.getContentHeight( ); cell.boxStyle.clearBorder( ); layout.resolveBorderConflict( cell, true ); cell.setContentHeight( ch ); } row.needResolveBorder = false; } if ( row.finished ) { if ( row.getChildrenCount( ) != row.cells.length ) { for ( int i = 0; i < row.cells.length; i++ ) { if ( row.cells[i] instanceof DummyCell ) { row.cells[i] = null; } } } layout.addRow( row, context.isFixedLayout( ) ); } } else { int size = container.getChildrenCount( ); for ( int i = 0; i < size; i++ ) { ContainerArea child = (ContainerArea) container.getChild( i ); addRows( child, layout, rowId ); child.updateChildrenPosition( ); } container.updateChildrenPosition( ); } } public void close( ) throws BirtException { /* * 1. resolve all unresolved cell 2. resolve table bottom border 3. * update height of Root area 4. update the status of TableAreaLayout */ int borderHeight = 0; if ( layout != null ) { int height = layout.resolveAll( getLastRow( ) ); if ( 0 != height ) { currentBP = currentBP + height; } borderHeight = layout.resolveBottomBorder( ); layout.remove( this ); } setHeight( currentBP + getOffsetY( ) + borderHeight ); updateBackgroundImage( ); if ( parent != null ) { IContent parentContent = parent.getContent( ); if ( parentContent != null && parentContent.isRTL( ) ) // bidi_hcg { flipPositionForRtl( ); } boolean pb = checkPageBreak( ); if ( pb ) { int height = layout.resolveAll( getLastRow( ) ); if ( 0 != height ) { currentBP = currentBP + height; } borderHeight = layout.resolveBottomBorder( ); layout.remove( this ); } parent.update( this ); } finished = true; } public int getCellWidth( int startColumn, int endColumn ) { if ( layoutInfo != null ) { return layoutInfo.getCellWidth( startColumn, endColumn ); } return 0; } public void resolveBorderConflict( CellArea cellArea, boolean isFirst ) { if ( layout != null ) { layout.resolveBorderConflict( cellArea, isFirst ); } } private TableLayoutInfo resolveTableFixedLayout( IContent content, LayoutContext context ) { assert ( parent != null ); int parentMaxWidth = parent.getMaxAvaWidth( ); int marginWidth = localProperties.getMarginLeft( ) + localProperties.getMarginRight( ); return new TableLayoutInfo( (ITableContent) content, context, new ColumnWidthResolver( (ITableContent) content ) .resolveFixedLayout( parentMaxWidth - marginWidth ) ); } private class ColumnWidthResolver { ITableContent table; public ColumnWidthResolver( ITableContent table ) { this.table = table; } /** * Calculates the column width for the table. the return value should be * each column width in point. * * @param columns * The column width specified in report design. * @param tableWidth * The suggested table width. If isTableWidthDefined is true, * this value is user defined table width; otherwise, it is * the max possible width for the table. * @param isTableWidthDefined * The flag to indicate whether the table width has been * defined explicitly. * @return each column width in point. */ protected int[] formalize( DimensionType[] columns, int tableWidth, boolean isTableWidthDefined ) { ArrayList percentageList = new ArrayList( ); ArrayList unsetList = new ArrayList( ); ArrayList preFixedList = new ArrayList( ); int[] resolvedColumnWidth = new int[columns.length]; double total = 0.0f; int fixedLength = 0; for ( int i = 0; i < columns.length; i++ ) { if ( columns[i] == null ) { unsetList.add( Integer.valueOf( i ) ); } else if ( EngineIRConstants.UNITS_PERCENTAGE.equals( columns[i] .getUnits( ) ) ) { percentageList.add( Integer.valueOf( i ) ); total += columns[i].getMeasure( ); } else if ( EngineIRConstants.UNITS_EM.equals( columns[i] .getUnits( ) ) || EngineIRConstants.UNITS_EX.equals( columns[i] .getUnits( ) ) ) { int len = getDimensionValue( table, columns[i], getDimensionValue( table.getComputedStyle( ) .getProperty( StyleConstants.STYLE_FONT_SIZE ) ) ); resolvedColumnWidth[i] = len; fixedLength += len; } else { int len = getDimensionValue( table, columns[i], tableWidth ); resolvedColumnWidth[i] = len; preFixedList.add( Integer.valueOf( i ) ); fixedLength += len; } } // all the columns have fixed width. if ( !isTableWidthDefined && unsetList.isEmpty( ) && percentageList.isEmpty( ) ) { return resolvedColumnWidth; } if ( fixedLength >= tableWidth ) { for ( int i = 0; i < unsetList.size( ); i++ ) { Integer index = (Integer) unsetList.get( i ); resolvedColumnWidth[index.intValue( )] = 0; } for ( int i = 0; i < percentageList.size( ); i++ ) { Integer index = (Integer) percentageList.get( i ); resolvedColumnWidth[index.intValue( )] = 0; } return resolvedColumnWidth; } if ( unsetList.isEmpty( ) ) { if ( percentageList.isEmpty( ) ) { int left = tableWidth - fixedLength; if ( !preFixedList.isEmpty( ) ) { int delta = left / preFixedList.size( ); for ( int i = 0; i < preFixedList.size( ); i++ ) { Integer index = (Integer) preFixedList.get( i ); resolvedColumnWidth[index.intValue( )] += delta; } } } else { float leftPercentage = ( ( (float) ( tableWidth - fixedLength ) ) / tableWidth ) * 100.0f; double ratio = leftPercentage / total; for ( int i = 0; i < percentageList.size( ); i++ ) { Integer index = (Integer) percentageList.get( i ); columns[index.intValue( )] = new DimensionType( columns[index.intValue( )].getMeasure( ) * ratio, columns[index.intValue( )] .getUnits( ) ); resolvedColumnWidth[index.intValue( )] = getDimensionValue( table, columns[index.intValue( )], tableWidth ); } } } // unsetList is not empty. else { if ( percentageList.isEmpty( ) ) { int left = tableWidth - fixedLength; int eachWidth = left / unsetList.size( ); for ( int i = 0; i < unsetList.size( ); i++ ) { Integer index = (Integer) unsetList.get( i ); resolvedColumnWidth[index.intValue( )] = eachWidth; } } else { float leftPercentage = ( ( (float) ( tableWidth - fixedLength ) ) / tableWidth ) * 100.0f; if ( leftPercentage <= total ) { double ratio = leftPercentage / total; for ( int i = 0; i < unsetList.size( ); i++ ) { Integer index = (Integer) unsetList.get( i ); resolvedColumnWidth[index.intValue( )] = 0; } for ( int i = 0; i < percentageList.size( ); i++ ) { Integer index = (Integer) percentageList.get( i ); columns[index.intValue( )] = new DimensionType( columns[index.intValue( )].getMeasure( ) * ratio, columns[index.intValue( )] .getUnits( ) ); resolvedColumnWidth[index.intValue( )] = getDimensionValue( table, columns[index.intValue( )], tableWidth ); } } else { int usedLength = fixedLength; for ( int i = 0; i < percentageList.size( ); i++ ) { Integer index = (Integer) percentageList.get( i ); int width = getDimensionValue( table, columns[index .intValue( )], tableWidth ); usedLength += width; resolvedColumnWidth[index.intValue( )] = width; } int left = tableWidth - usedLength; int eachWidth = left / unsetList.size( ); for ( int i = 0; i < unsetList.size( ); i++ ) { Integer index = (Integer) unsetList.get( i ); resolvedColumnWidth[index.intValue( )] = eachWidth; } } } } return resolvedColumnWidth; } public int[] resolveFixedLayout( int maxWidth ) { int columnNumber = table.getColumnCount( ); DimensionType[] columns = new DimensionType[columnNumber]; // handle visibility for ( int i = 0; i < columnNumber; i++ ) { IColumn column = table.getColumn( i ); DimensionType w = column.getWidth( ); if ( startCol < 0 ) { startCol = i; } endCol = i; if ( w == null ) { columns[i] = null; } else { columns[i] = new DimensionType( w.getMeasure( ), w .getUnits( ) ); } } if ( startCol < 0 ) startCol = 0; if ( endCol < 0 ) endCol = 0; boolean isTableWidthDefined = false; int specifiedWidth = getDimensionValue( table, table.getWidth( ), maxWidth ); int tableWidth; if ( specifiedWidth > 0 ) { tableWidth = specifiedWidth; isTableWidthDefined = true; } else { tableWidth = maxWidth; isTableWidthDefined = false; } return formalize( columns, tableWidth, isTableWidthDefined ); } public int[] resolve( int specifiedWidth, int maxWidth ) { assert ( specifiedWidth <= maxWidth ); int columnNumber = table.getColumnCount( ); int[] columns = new int[columnNumber]; int columnWithWidth = 0; int colSum = 0; for ( int j = 0; j < table.getColumnCount( ); j++ ) { IColumn column = table.getColumn( j ); int columnWidth = getDimensionValue( table, column.getWidth( ), width ); if ( columnWidth > 0 ) { columns[j] = columnWidth; colSum += columnWidth; columnWithWidth++; } else { columns[j] = -1; } } if ( columnWithWidth == columnNumber ) { if ( colSum <= maxWidth ) { return columns; } else { float delta = colSum - maxWidth; for ( int i = 0; i < columnNumber; i++ ) { columns[i] -= (int) ( delta * columns[i] / colSum ); } return columns; } } else { if ( specifiedWidth == 0 ) { if ( colSum < maxWidth ) { distributeLeftWidth( columns, ( maxWidth - colSum ) / ( columnNumber - columnWithWidth ) ); } else { redistributeWidth( columns, colSum - maxWidth + ( columnNumber - columnWithWidth ) * maxWidth / columnNumber, maxWidth, colSum ); } } else { if ( colSum < specifiedWidth ) { distributeLeftWidth( columns, ( specifiedWidth - colSum ) / ( columnNumber - columnWithWidth ) ); } else { if ( colSum < maxWidth ) { distributeLeftWidth( columns, ( maxWidth - colSum ) / ( columnNumber - columnWithWidth ) ); } else { redistributeWidth( columns, colSum - specifiedWidth + ( columnNumber - columnWithWidth ) * specifiedWidth / columnNumber, specifiedWidth, colSum ); } } } } return columns; } private void redistributeWidth( int cols[], int delta, int sum, int currentSum ) { int avaWidth = sum / cols.length; for ( int i = 0; i < cols.length; i++ ) { if ( cols[i] < 0 ) { cols[i] = avaWidth; } else { cols[i] -= (int) ( ( (float) cols[i] ) * delta / currentSum ); } } } private void distributeLeftWidth( int cols[], int avaWidth ) { for ( int i = 0; i < cols.length; i++ ) { if ( cols[i] < 0 ) { cols[i] = avaWidth; } } } } public static class TableLayoutInfo { ITableContent tableContent; LayoutContext context; public TableLayoutInfo( ITableContent tableContent, LayoutContext context, int[] colWidth ) { this.tableContent = tableContent; this.context = context; this.colWidth = colWidth; this.columnNumber = colWidth.length; this.xPositions = new int[columnNumber]; this.tableWidth = 0; for ( int i = 0; i < columnNumber; i++ ) { xPositions[i] = tableWidth; tableWidth += colWidth[i]; } } public int getTableWidth( ) { return this.tableWidth; } public int getXPosition( int index ) { return xPositions[index]; } /** * get cell width * * @param startColumn * @param endColumn * @return */ public int getCellWidth( int startColumn, int endColumn ) { assert ( startColumn < endColumn ); assert ( colWidth != null ); int sum = 0; for ( int i = startColumn; i < endColumn; i++ ) { sum += colWidth[i]; } return sum; } protected int columnNumber; protected int tableWidth; /** * Array of column width */ protected int[] colWidth = null; /** * array of position for each column */ protected int[] xPositions = null; /** * Creates a hidden column at X position 0. * * @author bidi_hcg */ private void addDummyColumnForRTL( int[] colWidth ) { this.colWidth = new int[columnNumber + 1]; System.arraycopy( colWidth, 0, this.colWidth, 0, columnNumber ); this.colWidth[columnNumber] = xPositions[columnNumber - 1]; int[] newXPositions = new int[columnNumber + 1]; System.arraycopy( xPositions, 0, newXPositions, 0, columnNumber ); xPositions = newXPositions; xPositions[columnNumber] = 0; tableWidth += this.colWidth[columnNumber - 1]; ++columnNumber; } } }
package eu.scasefp7.eclipse.storyboards.handlers; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.resources.IFile; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.Platform; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.ui.handlers.HandlerUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import eu.scasefp7.eclipse.core.ontology.DynamicOntologyAPI; import eu.scasefp7.eclipse.storyboards.Activator; /** * A command handler for exporting a storyboard diagram to the dynamic ontology. * * @author themis */ public class ExportToOntologyHandler extends ProjectAwareHandler { /** * This function is called when the user selects the menu item. It reads the selected resource(s) and populates the * dynamic ontology. * * @param event the event containing the information about which file was selected. * @return the result of the execution which must be {@code null}. */ @SuppressWarnings("unchecked") public Object execute(ExecutionEvent event) throws ExecutionException { ISelection selection = HandlerUtil.getCurrentSelection(event); if (selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; List<Object> selectionList = structuredSelection.toList(); DynamicOntologyAPI ontology = new DynamicOntologyAPI(getProjectOfSelectionList(selectionList), true); // Iterate over the selected files for (Object object : selectionList) { IFile file = (IFile) Platform.getAdapterManager().getAdapter(object, IFile.class); if (file == null) { if (object instanceof IAdaptable) { file = (IFile) ((IAdaptable) object).getAdapter(IFile.class); } } if (file != null) { instantiateOntology(file, ontology); } } ontology.close(); } return null; } /** * Instantiates the dynamic ontology given the file of a storyboard diagram. * * @param file an {@link IFile} instance of a storyboard diagram. * @param ontology the ontology to be instantiated. */ protected void instantiateOntology(IFile file, DynamicOntologyAPI ontology) { try { String filename = file.getName(); String diagramName = filename.substring(0, filename.lastIndexOf('.')); diagramName = "SBD_" + diagramName.substring(diagramName.lastIndexOf('\\') + 1); instantiateOntology(diagramName, file.getContents(), ontology); } catch (CoreException e) { Activator.log("Error reading the contents of an sbd file", e); } } /** * Instantiates the dynamic ontology given the file of a storyboard diagram. * * @param file an {@link File} instance of a storyboard diagram. * @param ontology the ontology to be instantiated. */ protected void instantiateOntology(File file, DynamicOntologyAPI ontology) { try { String filename = file.getName(); String diagramName = filename.substring(0, filename.lastIndexOf('.')); diagramName = "SBD_" + diagramName.substring(diagramName.lastIndexOf('\\') + 1); InputStream is = new FileInputStream(file); instantiateOntology(diagramName, is, ontology); is.close(); } catch (IOException e) { e.printStackTrace(); } } /** * Instantiates the ontology given a diagram as an inputstream string. * * @param diagramName the name of the diagram. * @param stream the {@link InputStream} that contains the diagram * @param ontology the ontology to be instantiated. */ protected void instantiateOntology(String diagramName, InputStream stream, DynamicOntologyAPI ontology) { try { ontology.addActivityDiagram(diagramName); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(stream); Element doc = dom.getDocumentElement(); doc.normalize(); Node root = doc.getElementsByTagName("auth.storyboards:StoryboardDiagram").item(0); sbdToOwl(diagramName, ontology, root); ontology.close(); } catch (ParserConfigurationException | SAXException | IOException e) { Activator.log("Error instantiating the dynamic ontology", e); } } /** * Transfers an sbd file in the dynamic ontology. * * @param diagramName the name of the diagram. * @param ontology the ontology instance. * @param root the root node of the sbd diagram model. */ private void sbdToOwl(String diagramName, DynamicOntologyAPI ontology, Node root) { HashMap<String, SBDNode> ids = new HashMap<String, SBDNode>(); NodeList nodes = root.getChildNodes(); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); SBDNode sbdnode = new SBDNode(node); if (sbdnode.getType() != null) { // Iterate over all nodes if (sbdnode.getType().equals("action")) { // Add an action node as an activity ontology.addActivity(sbdnode.getName()); ontology.connectActivityDiagramToElement(diagramName, sbdnode.getName()); String[] actionAndObject = getActionAndObject(sbdnode.getName(), sbdnode.getAnnotations()); String action = actionAndObject[0]; String object1 = actionAndObject[1]; ontology.addActionToActivity(sbdnode.getName(), action); ontology.addObjectToActivity(sbdnode.getName(), object1); // String actiontype = sbdnode.get("type") == null ? "create" : sbdnode.get("type"); // ontology.addActivityTypeToActivity(sbdnode.getName(), actiontype); } else if (sbdnode.getType().equals("startnode")) { // Add the start node ontology.addInitialActivity("StartNode"); ontology.connectActivityDiagramToElement(diagramName, "StartNode"); if (sbdnode.getPrecondition() != null) { ontology.addPreconditionToDiagram(diagramName, sbdnode.getPrecondition()); } } else if (sbdnode.getType().equals("endnode")) { // Add the end node ontology.addFinalActivity("EndNode"); ontology.connectActivityDiagramToElement(diagramName, "EndNode"); } else if (sbdnode.getType().equals("storyboard")) { // Add a storyboard node as an activity ontology.addActivity(sbdnode.getName()); ontology.connectActivityDiagramToElement(diagramName, sbdnode.getName()); } ids.put(sbdnode.getId(), sbdnode); } } for (SBDNode sbdnode : ids.values()) { if (sbdnode.getType().equals("action")) { // Add the properties of the action ArrayList<String> propertyIds = sbdnode.getProperties(); for (String propertyId : propertyIds) { SBDNode property = ids.get(propertyId); ontology.addPropertyToActivity(sbdnode.getName(), property.getName()); } } if (sbdnode.getType().equals("action") || sbdnode.getType().equals("storyboard") || sbdnode.getType().equals("startnode")) { String nextNodeId = sbdnode.getNextNode(); String from = sbdnode.getName(); SBDNode nextNode = ids.get(nextNodeId); addTransitions(diagramName, ontology, ids, from, nextNode, new ArrayList<String>()); } } } /** * Adds the transitions to an action node of a storyboard. If there are conditions, this function recursively calls * itself to find the next action node and connects all conditions to the transition. * * @param diagramName the name of the diagram. * @param ontology the ontology instance. * @param ids hashmap used to find the ids of the nodes. * @param from the name of the initial node. * @param nextNode the current name of the next node. * @param conditionNames list used to hold the conditions to be added to the final transition. */ private void addTransitions(String diagramName, DynamicOntologyAPI ontology, HashMap<String, SBDNode> ids, String from, SBDNode nextNode, ArrayList<String> conditionNames) { if (nextNode.getType().equals("condition")) { // Add the transitions in the case of conditions ArrayList<SBDNode> conditionPaths = nextNode.getChildren(); SBDNode actionOfConditionPath0 = ids.get(conditionPaths.get(0).getNextNode()); ArrayList<String> newConditionNames0 = new ArrayList<String>(conditionNames); newConditionNames0.add(conditionPaths.get(0).getName()); if (actionOfConditionPath0.getType().equals("condition")) { addTransitions(diagramName, ontology, ids, from, actionOfConditionPath0, newConditionNames0); } else { ontology.addTransition(from, actionOfConditionPath0.getName()); ontology.connectActivityDiagramToTransition(diagramName, from, actionOfConditionPath0.getName()); for (String conditionName : newConditionNames0) { ontology.addConditionToTransition(conditionName, from, actionOfConditionPath0.getName()); } } SBDNode actionOfConditionPath1 = ids.get(conditionPaths.get(1).getNextNode()); ArrayList<String> newConditionNames1 = new ArrayList<String>(conditionNames); newConditionNames1.add(conditionPaths.get(1).getName()); if (actionOfConditionPath1.getType().equals("condition")) { addTransitions(diagramName, ontology, ids, from, actionOfConditionPath1, newConditionNames1); } else { ontology.addTransition(from, actionOfConditionPath1.getName()); ontology.connectActivityDiagramToTransition(diagramName, from, actionOfConditionPath1.getName()); for (String conditionName : newConditionNames1) { ontology.addConditionToTransition(conditionName, from, actionOfConditionPath1.getName()); } } } else { // Add the transitions ontology.addTransition(from, nextNode.getName()); ontology.connectActivityDiagramToTransition(diagramName, from, nextNode.getName()); } } /** * Extracts the action and the object of an activity. * * @param activity the activity to be split. * @param annotations the annotations of this activity. * @return a string array including the action in the first position and the object in the second. */ private static String[] getActionAndObject(String activity, String annotations) { String[] actobj = new String[2]; actobj[0] = ""; actobj[1] = ""; if (annotations != null) { String[] annotationList = annotations.split("\\\\n"); for (int i = 0; i < annotationList.length; i++) { String annotation = annotationList[i]; String annType = annotation.split("\\\\t")[0].split(":")[1].substring(0, 1); if (annType.equals("T")) { String annotationType = annotation.split("\\\\t")[1].split("\\s+")[0]; if (annotationType.equals("Action")) actobj[0] = annotation.split("\\\\t")[2]; else if (annotationType.equals("Object")) actobj[1] = annotation.split("\\\\t")[2]; } } } String[] tempactobj = activity.split("\\s+"); if (actobj[0].equals("")) actobj[0] = tempactobj[0]; if (actobj[1].equals("")) actobj[1] = tempactobj[tempactobj.length - 1]; return actobj; } /** * Tests this export handler. * * @param args the filename of the file to be added to the dynamic ontology. */ public static void main(String[] args) { File file = new File(args[0]); DynamicOntologyAPI ontology = new DynamicOntologyAPI("Project", true); new ExportToOntologyHandler().instantiateOntology(file, ontology); } }
package com.zngames.skymag; import java.util.Random; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.Circle; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Array.ArrayIterator; public class World { SkyMagGame game; WorldRenderer wr; Ship ship; Magnet leftMagnet; Magnet rightMagnet; float timeSinceLastCircle; Array<Circle> holes; Array<Enemy> enemies; Array<Coin> coins; float globalSpeed; float muRadius; float sigmaRadius; float minDistanceBetweenHoles; float minDistanceBetweenHolesAndCoins; Circle pendingHole; float pendingDistance; float surplusDistance; static final float fieldWidth = SkyMagGame.getWidth() * 0.5f; final float maxRadius = fieldWidth * 0.4f; final float minRadius = fieldWidth/8; final float chanceOfCoinGeneration = 0.25f; public World(SkyMagGame game){ this.game = game; leftMagnet = new Magnet(new Vector2(SkyMagGame.getWidth() / 9, SkyMagGame.getHeight() / 2), 40, 40); rightMagnet = new Magnet(new Vector2(8*SkyMagGame.getWidth() / 9, SkyMagGame.getHeight() / 2), 40, 40); ship = new DiscShip(leftMagnet, rightMagnet); Gdx.input.setInputProcessor(new InputHandler(this)); timeSinceLastCircle = 0; holes = new Array<Circle>(false, 16); enemies = new Array<Enemy>(false, 16); coins = new Array<Coin>(false, 16); globalSpeed = 60; muRadius = (maxRadius-minRadius)*0.25f + minRadius; sigmaRadius = maxRadius*0.50f; minDistanceBetweenHoles = ship.getWidth(); minDistanceBetweenHolesAndCoins = Coin.coinRadius; pendingDistance = 0; surplusDistance = -1; // Creating a freezer enemy enemies.add(new FreezerEnemy(SkyMagGame.getWidth() / 2, SkyMagGame.getHeight() / 3)); } public void update(float delta){ // Updating the game global speed updateGlobalSpeed(delta); // Updating the holes (generating new holes, deleting old holes, etc.) updateHoles(delta); // Updating the coins updateCoins(delta); // Updating the enemies updateEnemies(delta); // Making the ship advance ship.advance(delta); } public void updateGlobalSpeed(float delta){ globalSpeed+=0.3*delta; } public void updateHoles(float delta){ timeSinceLastCircle += delta; if(surplusDistance > 0){ pendingDistance += globalSpeed*delta; if(pendingDistance >= surplusDistance){ holes.add(pendingHole); if(MathUtils.randomBoolean(chanceOfCoinGeneration)){ generateCircleOfCoins(pendingHole.x, pendingHole.y, pendingHole.radius); } surplusDistance = -1; pendingDistance = 0; timeSinceLastCircle = 0; } } // Generating a circle every 2 seconds approximately else if(MathUtils.random(timeSinceLastCircle) > 1.5){ System.out.println("Generating"); timeSinceLastCircle = 0; float x; float y = SkyMagGame.getHeight()+maxRadius; float radius; surplusDistance = -1; x = MathUtils.random(SkyMagGame.getWidth()*0.25f, SkyMagGame.getWidth()*0.25f + fieldWidth); radius = generateRadius(minRadius, maxRadius); ArrayIterator<Circle> iter = new ArrayIterator<Circle>(holes); while(iter.hasNext()){ Circle circle = iter.next(); if(Math.sqrt((circle.x-x)*(circle.x-x) + (circle.y-y)*(circle.y-y)) < radius + minDistanceBetweenHoles + circle.radius){ surplusDistance = (float) Math.sqrt((radius + minDistanceBetweenHoles + circle.radius)*(radius + minDistanceBetweenHoles + circle.radius) - (circle.x-x)*(circle.x-x)) - Math.abs(circle.y-y); } } if(surplusDistance <= 0){ holes.add(new Circle(x,y,radius)); if(MathUtils.randomBoolean(chanceOfCoinGeneration)){ generateCircleOfCoins(x, y, radius); } } else { pendingHole = new Circle(x,y,radius); pendingDistance = 0; } } // Removing old holes and making the current holes advance ArrayIterator<Circle> iterCircles = new ArrayIterator<Circle>(holes); while(iterCircles.hasNext()){ Circle circle = iterCircles.next(); if(circle.y + circle.radius < 0){ iterCircles.remove(); } circle.setPosition(circle.x, circle.y-globalSpeed*delta); } // Updating the hole generation gaussian parameters if(muRadius < maxRadius){ muRadius += maxRadius*0.001*delta; } else{ sigmaRadius += sigmaRadius*0.0001*delta; } } public void updateEnemies(float delta){ ArrayIterator<Enemy> iterEnemies = new ArrayIterator<Enemy>(enemies); while(iterEnemies.hasNext()){ Enemy enemy = iterEnemies.next(); enemy.update(this, delta); // Removing the enemies from the array if they should stop existing if(enemy.shouldStopExisting(this)){ iterEnemies.remove(); } enemy.actOn(ship); } } public void updateCoins(float delta){ ArrayIterator<Coin> iterCoins = new ArrayIterator<Coin>(coins); while(iterCoins.hasNext()){ Coin coin = iterCoins.next(); if(coin.actOn(ship)){ iterCoins.remove(); } else{ coin.setPosition(coin.getX(), coin.getY()-globalSpeed*delta); } } } public float generateRadius(float min, float max){ float z; int cpt = 0; do{ Random random = new Random(); z = (float) random.nextGaussian()*sigmaRadius + muRadius; cpt++; if(cpt>100){ return random.nextFloat()*(max - min) + min; } }while(z < min || z > max); return z; } public void generateCircleOfCoins(float x, float y, float radius){ float distanceFromHoleCenterToCoinCenter = radius+Coin.coinRadius+this.minDistanceBetweenHolesAndCoins; int nbCircles = (int) ( (MathUtils.PI*distanceFromHoleCenterToCoinCenter) / Coin.coinRadius ); float leftSpace = 2*( (MathUtils.PI*distanceFromHoleCenterToCoinCenter) % Coin.coinRadius ); float spaceBetweenCircles = leftSpace/nbCircles; float angleBetweenCircles = (float) (2*Math.atan2(Coin.coinRadius+(spaceBetweenCircles*1.0f/2), distanceFromHoleCenterToCoinCenter)); float currentAngle = 0; for(int i=0;i<nbCircles;i++){ float xCoordinate = x + distanceFromHoleCenterToCoinCenter*MathUtils.cos(currentAngle); if(xCoordinate + Coin.coinRadius < World.getRightBorderXCoordinate() && xCoordinate - Coin.coinRadius > World.getLeftBorderXCoordinate()){ coins.add(new Coin(xCoordinate, y + distanceFromHoleCenterToCoinCenter*MathUtils.sin(currentAngle))); } currentAngle += angleBetweenCircles; } } public Ship getShip() { return ship; } public void setShip(Ship ship) { this.ship = ship; } public Magnet getLeftMagnet() { return leftMagnet; } public void setLeftMagnet(Magnet leftMagnet) { this.leftMagnet = leftMagnet; } public Magnet getRightMagnet() { return rightMagnet; } public void setRightMagnet(Magnet rightMagnet) { this.rightMagnet = rightMagnet; } public WorldRenderer getRenderer(){ return wr; } public void setRenderer(WorldRenderer wr){ this.wr = wr; } public Array<Circle> getHoles(){ return holes; } public Array<Enemy> getEnemies(){ return enemies; } public Array<Coin> getCoins(){ return coins; } static public float getFieldWidth(){ return fieldWidth; } static public float getLeftBorderXCoordinate(){ return (SkyMagGame.getWidth()-fieldWidth)/2; } static public float getRightBorderXCoordinate(){ return (SkyMagGame.getWidth()+fieldWidth)/2; } }
package modules.admin; import java.util.ArrayList; import java.util.Calendar; import java.util.Comparator; import java.util.Formatter; import java.util.GregorianCalendar; import java.util.List; import org.skyve.CORE; import org.skyve.EXT; import org.skyve.bizport.BizPortWorkbook; import org.skyve.domain.Bean; import org.skyve.domain.ChildBean; import org.skyve.domain.PersistentBean; import org.skyve.domain.messages.DomainException; import org.skyve.domain.messages.Message; import org.skyve.domain.messages.UploadException; import org.skyve.domain.messages.ValidationException; import org.skyve.domain.types.DateOnly; import org.skyve.domain.types.Decimal2; import org.skyve.domain.types.Decimal5; import org.skyve.domain.types.converters.date.DD_MMM_YYYY; import org.skyve.impl.bizport.StandardGenerator; import org.skyve.impl.bizport.StandardLoader; import org.skyve.metadata.customer.Customer; import org.skyve.metadata.model.Attribute; import org.skyve.metadata.model.Persistent; import org.skyve.metadata.model.document.Bizlet.DomainValue; import org.skyve.metadata.model.document.Document; import org.skyve.metadata.module.Module; import org.skyve.metadata.user.User; import org.skyve.persistence.DocumentQuery; import org.skyve.persistence.DocumentQuery.AggregateFunction; import org.skyve.persistence.Persistence; import org.skyve.util.Binder; import org.skyve.util.Time; import modules.admin.domain.Contact; import modules.admin.domain.DocumentNumber; /** * Utility methods applicable across application modules. * <p> * This class is provided as part of Skyve * * @author robert.brown * */ public class ModulesUtil { /** comparator to allow sorting of domain values by code */ public static class DomainValueSortByCode implements Comparator<DomainValue> { @Override public int compare(DomainValue d1, DomainValue d2) { return d1.getCode().compareTo(d2.getCode()); } } /** comparator to allow sorting of domain values by description */ public static class DomainValueSortByDescription implements Comparator<DomainValue> { @Override public int compare(DomainValue d1, DomainValue d2) { return d1.getDescription().compareTo(d2.getDescription()); } } /** general types of time-based frequencies */ public static enum OccurenceFrequency { OneOff, EverySecond, EveryMinute, Hourly, Daily, Weekly, Fortnightly, Monthly, Quarterly, HalfYearly, Yearly, Irregularly, DuringHolidays, NotDuringHolidays, WeekDays, Weekends; } public static final List<DomainValue> OCCURRENCE_FREQUENCIES = new ArrayList<>(); static { OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Irregularly.toString())); OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.OneOff.toString())); OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Hourly.toString())); OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Daily.toString())); OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Weekly.toString())); OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Fortnightly.toString())); OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Monthly.toString())); OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Quarterly.toString())); OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.HalfYearly.toString())); OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Yearly.toString())); } /** subset of frequencies relevant for use as terms */ public static final List<DomainValue> TERM_FREQUENCIES = new ArrayList<>(); static { TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Irregularly.toString())); TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Weekly.toString())); TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Fortnightly.toString())); TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Monthly.toString())); TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Quarterly.toString())); TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.HalfYearly.toString())); TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Yearly.toString())); } /** normal days of the week */ public static enum DayOfWeek { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } public static final List<DomainValue> WEEK_DAYS = new ArrayList<>(); static { WEEK_DAYS.add(new DomainValue(DayOfWeek.Sunday.toString())); WEEK_DAYS.add(new DomainValue(DayOfWeek.Monday.toString())); WEEK_DAYS.add(new DomainValue(DayOfWeek.Tuesday.toString())); WEEK_DAYS.add(new DomainValue(DayOfWeek.Wednesday.toString())); WEEK_DAYS.add(new DomainValue(DayOfWeek.Thursday.toString())); WEEK_DAYS.add(new DomainValue(DayOfWeek.Friday.toString())); WEEK_DAYS.add(new DomainValue(DayOfWeek.Saturday.toString())); } /** * Returns a calendar day of the week * * @param weekDay * - the day of the week (DayOfWeek) * @return - the day of the week as a Calendar.day (int) */ public static final int dayOfWeekToCalendar(DayOfWeek weekDay) { int calendarDay = Calendar.MONDAY; if (weekDay.equals(DayOfWeek.Monday)) { calendarDay = Calendar.MONDAY; } if (weekDay.equals(DayOfWeek.Tuesday)) { calendarDay = Calendar.TUESDAY; } if (weekDay.equals(DayOfWeek.Wednesday)) { calendarDay = Calendar.WEDNESDAY; } if (weekDay.equals(DayOfWeek.Thursday)) { calendarDay = Calendar.THURSDAY; } if (weekDay.equals(DayOfWeek.Friday)) { calendarDay = Calendar.FRIDAY; } if (weekDay.equals(DayOfWeek.Saturday)) { calendarDay = Calendar.SATURDAY; } if (weekDay.equals(DayOfWeek.Sunday)) { calendarDay = Calendar.SUNDAY; } return calendarDay; } /** * Returns a day of the week from a Calendar day * * @param calendarDay * - the number of the day (int) * @return - the DayOfWeek (DayOfWeek) */ public static final DayOfWeek calendarToDayOfWeek(int calendarDay) { DayOfWeek weekDay = DayOfWeek.Monday; if (calendarDay == Calendar.MONDAY) { weekDay = DayOfWeek.Monday; } if (calendarDay == Calendar.TUESDAY) { weekDay = DayOfWeek.Tuesday; } if (calendarDay == Calendar.WEDNESDAY) { weekDay = DayOfWeek.Wednesday; } if (calendarDay == Calendar.THURSDAY) { weekDay = DayOfWeek.Thursday; } if (calendarDay == Calendar.FRIDAY) { weekDay = DayOfWeek.Friday; } if (calendarDay == Calendar.SATURDAY) { weekDay = DayOfWeek.Saturday; } if (calendarDay == Calendar.SUNDAY) { weekDay = DayOfWeek.Sunday; } return weekDay; } /** returns the number of days between day1 and day2 */ public static enum OccurrencePeriod { Seconds, Minutes, Hours, Days, Weeks, Months, Years } public static final List<DomainValue> OCCURRENCE_PERIODS = new ArrayList<>(); static { OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Seconds.toString())); OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Minutes.toString())); OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Hours.toString())); OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Days.toString())); OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Weeks.toString())); OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Months.toString())); OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Years.toString())); } /** * Returns the number of periods of specified frequency which occur in the * calendar year. * * @param frequency * - the specified frequency (OccurrenceFrequency) * @return - the number of times the specified frequency occurs in a * calendar year */ public static int annualFrequencyCount(OccurenceFrequency frequency) { int periodCount = 1; // default period Count if (frequency.equals(OccurenceFrequency.Daily)) { // estimated periodCount = 365; } else if (frequency.equals(OccurenceFrequency.Weekly)) { periodCount = 52; } else if (frequency.equals(OccurenceFrequency.Fortnightly)) { periodCount = 26; } else if (frequency.equals(OccurenceFrequency.Monthly)) { periodCount = 12; } else if (frequency.equals(OccurenceFrequency.Quarterly)) { periodCount = 4; } else if (frequency.equals(OccurenceFrequency.HalfYearly)) { periodCount = 2; } return periodCount; } /** * Returns the number of periods which occur in a calendar year. * * @param period * - the time period (OccurrencePeriod) * @return - the number of times the period occurs within a calendar year * (int) */ public static int annualPeriodCount(OccurrencePeriod period) { int periodCount = 1; // default period Count if (period.equals(OccurrencePeriod.Days)) { // estimated periodCount = 365; } else if (period.equals(OccurrencePeriod.Weeks)) { periodCount = 52; } else if (period.equals(OccurrencePeriod.Months)) { periodCount = 12; } else if (period.equals(OccurrencePeriod.Years)) { periodCount = 1; } return periodCount; } /** * Adds a time frequency to a given date. * * @param frequency * - the frequency to add * @param date * - the date to add to * @param numberOfFrequencies * - the number of frequencies to add * @return - the resulting date */ public static final DateOnly addFrequency(OccurenceFrequency frequency, DateOnly date, int numberOfFrequencies) { if (date != null) { if (frequency.equals(OccurenceFrequency.OneOff)) { return new DateOnly(date.getTime()); } DateOnly newDate = new DateOnly(date.getTime()); Calendar calendar = new GregorianCalendar(); calendar.setTime(newDate); calendar.setLenient(false); // NB clear() does not work in JDK 1.3.1 calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); if (frequency.equals(OccurenceFrequency.Daily)) { calendar.add(Calendar.DATE, numberOfFrequencies); } else if (frequency.equals(OccurenceFrequency.Weekly)) { calendar.add(Calendar.DATE, (numberOfFrequencies * 7)); } else if (frequency.equals(OccurenceFrequency.Fortnightly)) { calendar.add(Calendar.DATE, (numberOfFrequencies * 14)); } else if (frequency.equals(OccurenceFrequency.Monthly)) { calendar.add(Calendar.MONTH, numberOfFrequencies); } else if (frequency.equals(OccurenceFrequency.Quarterly)) { calendar.add(Calendar.MONTH, (numberOfFrequencies * 3)); } else if (frequency.equals(OccurenceFrequency.HalfYearly)) { calendar.add(Calendar.MONTH, (numberOfFrequencies * 6)); } else if (frequency.equals(OccurenceFrequency.Yearly)) { calendar.add(Calendar.YEAR, numberOfFrequencies); } newDate.setTime(calendar.getTime().getTime()); return newDate; } return null; } /** * Returns the last day of the month in which the specified date occurs. * * @param date * - the specified date * @return - the date of the last day of the month in which the specified * date occurs */ public static DateOnly lastDayOfMonth(DateOnly date) { if (date != null) { DateOnly newDate = new DateOnly(date.getTime()); Calendar calendar = new GregorianCalendar(); calendar.setTime(newDate); calendar.setLenient(false); // NB clear() does not work in JDK 1.3.1 calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); // last day of month is one day before 1st day of next month calendar.add(Calendar.MONTH, 1); calendar.set(Calendar.DATE, 1); newDate.setTime(calendar.getTime().getTime()); Time.addDays(newDate, -1); return newDate; } return null; } /** * Returns the last day of the year in which the specified date occurs. * * @param date * - the specified date * @return - the date of the last day of the year in which the specified * date occurs */ public static DateOnly lastDayOfYear(DateOnly date) { if (date != null) { DateOnly newDate = new DateOnly(date.getTime()); Calendar calendar = new GregorianCalendar(); calendar.setTime(newDate); calendar.setLenient(false); // NB clear() does not work in JDK 1.3.1 calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); // last day of year is one day before 1st day of next year calendar.add(Calendar.YEAR, 1); calendar.set(Calendar.MONTH, 0); calendar.set(Calendar.DATE, 1); newDate.setTime(calendar.getTime().getTime()); Time.addDays(newDate, -1); return newDate; } return null; } /** * Returns the date of the first day of the month in which the specified * date occurs. * * @param date * - the specified date * @return - the date of the first day of that month */ @SuppressWarnings("deprecation") public static DateOnly firstDayOfMonth(DateOnly date) { Calendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.setLenient(false); // NB clear() does not work in JDK 1.3.1 calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MONTH, date.getMonth()); calendar.set(Calendar.DATE, 1); date.setTime(calendar.getTime().getTime()); return date; } /** * Returns the date of the first day of the year in which the specified date * occurs. * * @param date * - the specified date * @return - the date of the first day of that year */ public static DateOnly firstDayOfYear(DateOnly date) { Calendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.setLenient(false); // NB clear() does not work in JDK 1.3.1 calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MONTH, 0); calendar.set(Calendar.DATE, 1); date.setTime(calendar.getTime().getTime()); return date; } /** * Returns the date which occurs after the specified date, given the number * of days to add. * * @param date * - the specified date * @param daysToAdd * - the number of days to add to that date * @return - the resulting date */ public static DateOnly addDaysDateOnly(DateOnly date, int daysToAdd) { Calendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.setLenient(false); // NB clear() does not work in JDK 1.3.1 calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.add(Calendar.DAY_OF_WEEK, daysToAdd); date.setTime(calendar.getTime().getTime()); return date; } @SuppressWarnings("deprecation") public static String sqlFormatDateOnly(DateOnly theDate) { String result = ""; if (theDate != null) { String month = "0" + (theDate.getMonth() + 1); month = month.substring(month.length() - 2); String day = "0" + theDate.getDate(); day = day.substring(day.length() - 2); result = "convert('" + (theDate.getYear() + 1900) + "-" + month + "-" + day + "', date) "; } return result; } /** Returns a TitleCase version of the String supplied */ public static String titleCase(String raw) { String s = raw; if (s != null) { if (s.length() > 1) { s = s.substring(0, 1).toUpperCase() + s.substring(1); } else if (s.length() == 1) { s = s.toUpperCase(); } } return s; } /** abbreviated forms of calendar months */ public static enum CalendarMonth { JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC } public static final List<DomainValue> CALENDAR_MONTHS = new ArrayList<>(); static { CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.JAN.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.FEB.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.MAR.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.APR.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.MAY.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.JUN.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.JUL.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.AUG.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.SEP.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.OCT.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.NOV.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.DEC.toString())); } /** conversion from month Name to calendar month (int) */ public static int calendarMonthNameToNumber(String monthName) { if (CalendarMonth.JAN.toString().equals(monthName)) { return 0; } else if (CalendarMonth.FEB.toString().equals(monthName)) { return 1; } else if (CalendarMonth.MAR.toString().equals(monthName)) { return 2; } else if (CalendarMonth.APR.toString().equals(monthName)) { return 3; } else if (CalendarMonth.MAY.toString().equals(monthName)) { return 4; } else if (CalendarMonth.JUN.toString().equals(monthName)) { return 5; } else if (CalendarMonth.JUL.toString().equals(monthName)) { return 6; } else if (CalendarMonth.AUG.toString().equals(monthName)) { return 7; } else if (CalendarMonth.SEP.toString().equals(monthName)) { return 8; } else if (CalendarMonth.OCT.toString().equals(monthName)) { return 9; } else if (CalendarMonth.NOV.toString().equals(monthName)) { return 10; } else if (CalendarMonth.DEC.toString().equals(monthName)) { return 11; } else { return 0; } } /** * Returns the current session/conversation user as an Admin module User * * @return The current {@link modules.admin.domain.User} */ public static modules.admin.domain.User currentAdminUser() { modules.admin.domain.User user = null; try { Persistence persistence = CORE.getPersistence(); Customer customer = persistence.getUser().getCustomer(); Module module = customer.getModule(modules.admin.domain.User.MODULE_NAME); Document userDoc = module.getDocument(customer, modules.admin.domain.User.DOCUMENT_NAME); user = persistence.retrieve(userDoc, persistence.getUser().getId(), false); } catch (Exception e) { // do nothing } return user; } public static Contact getCurrentUserContact() { Persistence persistence = CORE.getPersistence(); User user = persistence.getUser(); Customer customer = user.getCustomer(); Module module = customer.getModule(Contact.MODULE_NAME); Document document = module.getDocument(customer, Contact.DOCUMENT_NAME); Contact contact = persistence.retrieve(document, user.getContactId(), false); return contact; } public static void addValidationError(ValidationException e, String fieldName, String messageString) { Message vM = new Message(messageString); vM.addBinding(fieldName); e.getMessages().add(vM); } /** * Returns a new document/sequence number for the given * module.document.fieldName in a thread-safe way. * <p> * If no previous record is found in the DocumentNumber table, the method * attempts to find the Maximum existing value currently extant in the field * and increments that. Otherwise, the value returned is incremented and * updated DocumentNumber value for the specified combination. * * @param prefix * - if the sequence value has a known prefix before the number, * eg INV0001 has a prefix of "INV" * @param moduleName * - the application module * @param documentName * - the application document * @param fieldName * - the fieldName/columnName in which the value is held * @param numberLength * - the minimum length of the number when specified as a string * @return - the next sequence number */ public static String getNextDocumentNumber(String prefix, String moduleName, String documentName, String fieldName, int numberLength) { Persistence pers = CORE.getPersistence(); User user = pers.getUser(); Customer customer = user.getCustomer(); Module module = customer.getModule(DocumentNumber.MODULE_NAME); Document document = module.getDocument(customer, DocumentNumber.DOCUMENT_NAME); String nextNumber = "0"; String lastNumber = "0"; DocumentNumber dN = null; try { DocumentQuery qN = pers.newDocumentQuery(DocumentNumber.MODULE_NAME, DocumentNumber.DOCUMENT_NAME); qN.getFilter().addEquals(DocumentNumber.moduleNamePropertyName, moduleName); qN.getFilter().addEquals(DocumentNumber.documentNamePropertyName, documentName); qN.getFilter().addEquals(DocumentNumber.sequenceNamePropertyName, fieldName); List<DocumentNumber> num = qN.beanResults(); if (num.isEmpty()) { // System.out.println("DOCUMENT NUMBER: No previous found - source from table"); // Check if sequence name is a field in that table boolean isField = false; for (Attribute attribute : document.getAttributes()) { if (attribute.getName().equals(fieldName)) { isField = true; break; } } if (isField) { // first hit - go lookup max number from table DocumentQuery query = pers.newDocumentQuery(moduleName, documentName); query.addAggregateProjection(AggregateFunction.Max, fieldName, "MaxNumber"); List<Bean> beans = query.projectedResults(); if (!beans.isEmpty()) { Object o = Binder.get(beans.get(0), "MaxNumber"); if (o instanceof Integer) { lastNumber = ((Integer) Binder.get(beans.get(0), "MaxNumber")).toString(); } else { lastNumber = (String) Binder.get(beans.get(0), "MaxNumber"); } } } // create a new document number record dN = DocumentNumber.newInstance(); dN.setModuleName(moduleName); dN.setDocumentName(documentName); dN.setSequenceName(fieldName); } else { // System.out.println("DOCUMENT NUMBER: Previous found"); dN = num.get(0); dN = pers.retrieve(document, dN.getBizId(), true); // issue a // row-level // lock lastNumber = dN.getDocumentNumber(); } // just update from the document Number nextNumber = incrementAlpha(prefix, lastNumber, numberLength); dN.setDocumentNumber(nextNumber); pers.preMerge(document, dN); pers.upsertBeanTuple(dN); pers.postMerge(document, dN); } finally { if (dN != null) { pers.evictCached(dN); } } // System.out.println("Next document number for " + moduleName + "." + // documentName + "." + fieldName + " is " + nextNumber); return nextNumber; } /** * Wrapper for getNextDocumentNumber, specifically for numeric only * sequences */ public static Integer getNextDocumentNumber(String moduleName, String documentName, String fieldName) { return new Integer(Integer.parseInt(getNextDocumentNumber(null, moduleName, documentName, fieldName, 0))); } /** * Wrapper for getNextDocumentNumber, specifically for long only * sequences */ public static Long getNextLongDocumentNumber(String moduleName, String documentName, String fieldName) { return new Long(Long.parseLong(getNextDocumentNumber(null, moduleName, documentName, fieldName, 0))); } /** * Returns the next alpha value - ie A00A1 becomes A00A2 etc * * @param prefix * - if the sequence value has a known prefix before the number, * eg INV0001 has a prefix of "INV" * @param numberLength * - the minimum length of the number when specified as a string * @param lastNumber * - the number to increment * @return - the next number */ public static String incrementAlpha(String suppliedPrefix, String lastNumber, int numberLength) { String newNumber = ""; String nonNumeric = lastNumber; Integer value = new Integer(1); String prefix; if (suppliedPrefix != null) { prefix = suppliedPrefix; } else { prefix = ""; } if (lastNumber != null) { String[] parts = (new StringBuilder(" ").append(lastNumber)).toString().split("\\D\\d+$"); // cater for alpha prefix if (parts.length > 0 && parts[0].length() < lastNumber.length()) { String numberPart = lastNumber.substring(parts[0].length(), lastNumber.length()); nonNumeric = lastNumber.substring(0, parts[0].length()); value = new Integer(Integer.parseInt(numberPart) + 1); // cater for purely numeric prefix } else if (prefix.matches("^\\d+$") && lastNumber.matches("^\\d+$") && !"0".equals(lastNumber)) { int len = prefix.length(); value = new Integer(Integer.parseInt(lastNumber.substring(len)) + 1); nonNumeric = prefix; // cater for numeric only } else if (lastNumber.matches("^\\d+$")) { nonNumeric = prefix; value = new Integer(Integer.parseInt(lastNumber) + 1); } } else { nonNumeric = prefix; } // now put prefix and value together int newLength = (nonNumeric.length() + value.toString().length() > numberLength ? nonNumeric.length() + value.toString().length() : numberLength); StringBuilder sb = new StringBuilder(newLength + 1); try (Formatter f = new Formatter(sb)) { newNumber = nonNumeric + f.format(new StringBuilder("%1$").append(newLength - nonNumeric.length()).append("s").toString(), value.toString()).toString().replace(" ", "0"); } return newNumber; } /** returns a fomatted string representing the condition */ public static String getConditionName(String conditionCode) { String result = "is"; result += conditionCode.substring(0, 1).toUpperCase() + conditionCode.substring(1, conditionCode.length()); // System.out.println("GetConditionName " + result); return result; } /** allows comparison where both terms being null evaluates as equality */ public static boolean bothNullOrEqual(Object object1, Object object2) { boolean result = false; if ((object1 == null && object2 == null) || (object1 != null && object2 != null && object1.equals(object2))) { result = true; } return result; } /** returns null if zero - for reports or data import/export */ public static Decimal5 coalesce(Decimal5 val, Decimal5 ifNullValue) { return (val == null ? ifNullValue : val); } /** type-specific coalesce */ public static String coalesce(String val, String ifNullValue) { return (val == null ? ifNullValue : val); } /** type-specific coalesce */ public static Decimal2 coalesce(Decimal2 val, Decimal2 ifNullValue) { return (val == null ? ifNullValue : val); } /** type-specific coalesce */ public static String coalesce(Object val, String ifNullValue) { return (val == null ? ifNullValue : val.toString()); } /** type-specific coalesce */ public static Boolean coalesce(Boolean val, Boolean ifNullValue) { return (val == null ? ifNullValue : val); } /** type-specific coalesce */ public static Integer coalesce(Integer val, Integer ifNullValue) { return (val == null ? ifNullValue : val); } /** * Replaces the value found in the bean for the binding string provided, * e.g. if the bean has a binding of contact.name, for which the * displayNames of those bindings are Contact.FullName , then get the value * of that binding from the bean provided. * * @param bean * - the bean relevant for the binding * @param replacementString * - the string representing the displayName form of the binding * @return - the value from the bean * @throws Exception * general Exception for metadata exception or string * manipulation failure etc */ public static String replaceBindingsInString(Bean bean, String replacementString) throws Exception { StringBuilder result = new StringBuilder(replacementString); int openCurlyBraceIndex = result.indexOf("{"); // now replace contents of each curlyBraced expression if we can while (openCurlyBraceIndex >= 0) { int closedCurlyBraceIndex = result.indexOf("}"); String displayNameOfAttribute = result.substring(openCurlyBraceIndex + 1, closedCurlyBraceIndex); Bean b = bean; StringBuilder binding = new StringBuilder(); String[] attributes = displayNameOfAttribute.toString().split("\\."); boolean found = false; for (String a : attributes) { // if the format string includes a sub-bean attribute, get the // sub-bean if (binding.toString().length() > 0) { b = (Bean) Binder.get(bean, binding.toString()); } // parent special case if (a.equals("parent")) { b = ((ChildBean<?>) bean).getParent(); } // if the sub-bean isn't null, try to match the attribute // because attributes in the format string might be optional found = false; if (b != null) { User user = CORE.getPersistence().getUser(); Customer customer = user.getCustomer(); Module module = customer.getModule(b.getBizModule()); Document document = module.getDocument(customer, b.getBizDocument()); for (Attribute attribute : document.getAllAttributes()) { if (attribute.getDisplayName().equals(a)) { found = true; if (binding.toString().length() > 0) { binding.append('.').append(attribute.getName()); } else { binding.append(attribute.getName()); } } } // check for non-attribute bindings if (!found) { try { if (Binder.get(bean, a) != null) { binding.append(a); } } catch (Exception e) { // do nothing } } } } String term = ""; if (found) { Object value = Binder.get(bean, binding.toString()); if (value instanceof DateOnly) { DateOnly dValue = (DateOnly) value; DD_MMM_YYYY convDate = new DD_MMM_YYYY(); term = convDate.toDisplayValue(dValue); } else if (value instanceof Decimal2) { term = value.toString(); } else if (value instanceof Decimal5) { term = value.toString(); } else { term = coalesce(value, "").toString(); } } // move along String displayValue = ModulesUtil.coalesce(term, ""); result.replace(openCurlyBraceIndex, closedCurlyBraceIndex + 1, displayValue); openCurlyBraceIndex = result.indexOf("{"); } return result.toString(); } /** simple concatenation with a delimiter */ public static String concatWithDelim(String delimiter, String... strings) { StringBuilder sb = new StringBuilder(); String delim = coalesce(delimiter, " "); for (String s : strings) { if (coalesce(s, "").length() > 0) { if (sb.toString().length() > 0) { sb.append(delim); } sb.append(s); } } return sb.toString(); } /** short-hand enquoting of a string */ public static String enquote(String quoteSet, String s) { String l = null; String r = null; if (quoteSet != null) { l = quoteSet.substring(0, 1); if (coalesce(quoteSet, "").length() > 1) { r = quoteSet.substring(1); } } return concatWithDelim("", l, concatWithDelim("", s, r)); } /** * Returns whether the user has access to the specified module * * @param moduleName * @return */ public static boolean hasModule(String moduleName) { boolean result = false; User user = CORE.getPersistence().getUser(); Customer customer = user.getCustomer(); for (Module module : customer.getModules()) { if (module.getName().equals(moduleName)) { result = true; break; } } return result; } /** * Generic bizport export method. * * @param moduleName * - the module to be exported * @param documentName * - the document to be exported * @param b * - the top-level bean to export * @return - the reference to the Bizportable */ public static BizPortWorkbook standardBeanBizExport(String modName, String docName, Bean b) { String documentName = docName; String moduleName = modName; BizPortWorkbook result = EXT.newBizPortWorkbook(false); if (b != null) { moduleName = b.getBizModule(); documentName = b.getBizDocument(); } Persistence persistence = CORE.getPersistence(); Customer customer = persistence.getUser().getCustomer(); Module module = customer.getModule(moduleName); // Project Document document = module.getDocument(customer, documentName); StandardGenerator bgBean = EXT.newBizPortStandardGenerator(customer, document); bgBean.generateStructure(result); result.materialise(); // System.out.println("BIZPORTING PROJECT " ); DocumentQuery query = persistence.newDocumentQuery(moduleName, documentName); if (b != null) { // filter for this project if provided query.getFilter().addEquals(Bean.DOCUMENT_ID, b.getBizId()); } bgBean.generateData(result, query.beanIterable()); return result; } public static void standardBeanBizImport(BizPortWorkbook workbook, UploadException problems) throws Exception { final Persistence persistence = CORE.getPersistence(); final Customer customer = persistence.getUser().getCustomer(); StandardLoader loader = new StandardLoader(workbook, problems); List<Bean> bs = loader.populate(persistence); for (String key : loader.getBeanKeys()) { Bean bean = loader.getBean(key); Module module = customer.getModule(bean.getBizModule()); Document document = module.getDocument(customer, bean.getBizDocument()); try { persistence.preMerge(document, bean); } catch (DomainException e) { loader.addError(customer, bean, e); } } // throw if we have errors found if (problems.hasErrors()) { throw problems; } // do the insert as 1 operation, bugging out if we encounter any errors PersistentBean pb = null; try { for (Bean b : bs) { pb = (PersistentBean) b; pb = persistence.save(pb); } } catch (DomainException e) { if (pb != null) { loader.addError(customer, pb, e); } throw problems; } } /** short-hand way of finding a bean using a legacy key */ public static Bean lookupBean(String moduleName, String documentName, String propertyName, Object objValue) { Persistence persistence = CORE.getPersistence(); DocumentQuery qBean = persistence.newDocumentQuery(moduleName, documentName); qBean.getFilter().addEquals(propertyName, objValue); List<Bean> beans = qBean.beanResults(); Bean bean = null; if (!beans.isEmpty()) { bean = beans.get(0); } else { System.out.println("Cannot find reference to " + objValue + " in document " + documentName); } return bean; } /** * Returns the persistent table name for the specified module and document. */ public static String getPersistentIdentifier(final String moduleName, final String documentName) { Customer customer = CORE.getCustomer(); Module module = customer.getModule(moduleName); Document document = module.getDocument(customer, documentName); Persistent p = document.getPersistent(); return p.getPersistentIdentifier(); } }
package com.psddev.dari.db; import com.jolbox.bonecp.BoneCPDataSource; import com.psddev.dari.util.ObjectUtils; import com.psddev.dari.util.PaginatedResult; import com.psddev.dari.util.PeriodicValue; import com.psddev.dari.util.Profiler; import com.psddev.dari.util.PullThroughValue; import com.psddev.dari.util.Settings; import com.psddev.dari.util.SettingsException; import com.psddev.dari.util.Stats; import com.psddev.dari.util.StringUtils; import com.psddev.dari.util.TypeDefinition; import java.io.ByteArrayInputStream; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.ref.WeakReference; import java.sql.BatchUpdateException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Driver; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.SQLIntegrityConstraintViolationException; import java.sql.SQLTimeoutException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import javax.sql.DataSource; import org.iq80.snappy.Snappy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Database backed by a SQL engine. */ public class SqlDatabase extends AbstractDatabase<Connection> { public static final String DATA_SOURCE_SETTING = "dataSource"; public static final String JDBC_DRIVER_CLASS_SETTING = "jdbcDriverClass"; public static final String JDBC_URL_SETTING = "jdbcUrl"; public static final String JDBC_USER_SETTING = "jdbcUser"; public static final String JDBC_PASSWORD_SETTING = "jdbcPassword"; public static final String JDBC_POOL_SIZE_SETTING = "jdbcPoolSize"; public static final String READ_DATA_SOURCE_SETTING = "readDataSource"; public static final String READ_JDBC_DRIVER_CLASS_SETTING = "readJdbcDriverClass"; public static final String READ_JDBC_URL_SETTING = "readJdbcUrl"; public static final String READ_JDBC_USER_SETTING = "readJdbcUser"; public static final String READ_JDBC_PASSWORD_SETTING = "readJdbcPassword"; public static final String READ_JDBC_POOL_SIZE_SETTING = "readJdbcPoolSize"; public static final String VENDOR_CLASS_SETTING = "vendorClass"; public static final String COMPRESS_DATA_SUB_SETTING = "compressData"; public static final String RECORD_TABLE = "Record"; public static final String RECORD_UPDATE_TABLE = "RecordUpdate"; public static final String SYMBOL_TABLE = "Symbol"; public static final String ID_COLUMN = "id"; public static final String TYPE_ID_COLUMN = "typeId"; public static final String IN_ROW_INDEX_COLUMN = "inRowIndex"; public static final String DATA_COLUMN = "data"; public static final String SYMBOL_ID_COLUMN = "symbolId"; public static final String UPDATE_DATE_COLUMN = "updateDate"; public static final String VALUE_COLUMN = "value"; public static final String EXTRA_COLUMNS_QUERY_OPTION = "sql.extraColumns"; public static final String EXTRA_JOINS_QUERY_OPTION = "sql.extraJoins"; public static final String EXTRA_WHERE_QUERY_OPTION = "sql.extraWhere"; public static final String EXTRA_HAVING_QUERY_OPTION = "sql.extraHaving"; public static final String MYSQL_INDEX_HINT_QUERY_OPTION = "sql.mysqlIndexHint"; public static final String RETURN_ORIGINAL_DATA_QUERY_OPTION = "sql.returnOriginalData"; public static final String USE_JDBC_FETCH_SIZE_QUERY_OPTION = "sql.useJdbcFetchSize"; public static final String USE_READ_DATA_SOURCE_QUERY_OPTION = "sql.useReadDataSource"; public static final String SKIP_INDEX_STATE_EXTRA = "sql.skipIndex"; public static final String INDEX_TABLE_INDEX_OPTION = "sql.indexTable"; public static final String EXTRA_COLUMN_EXTRA_PREFIX = "sql.extraColumn."; public static final String ORIGINAL_DATA_EXTRA = "sql.originalData"; private static final Logger LOGGER = LoggerFactory.getLogger(SqlDatabase.class); private static final String SHORT_NAME = "SQL"; private static final Stats STATS = new Stats(SHORT_NAME); private static final String QUERY_STATS_OPERATION = "Query"; private static final String UPDATE_STATS_OPERATION = "Update"; private static final String QUERY_PROFILER_EVENT = SHORT_NAME + " " + QUERY_STATS_OPERATION; private static final String UPDATE_PROFILER_EVENT = SHORT_NAME + " " + UPDATE_STATS_OPERATION; private final static List<SqlDatabase> INSTANCES = new ArrayList<SqlDatabase>(); { INSTANCES.add(this); } private volatile DataSource dataSource; private volatile DataSource readDataSource; private volatile SqlVendor vendor; private volatile boolean compressData; /** * Quotes the given {@code identifier} so that it's safe to use * in a SQL query. */ public static String quoteIdentifier(String identifier) { return "\"" + StringUtils.replaceAll(identifier, "\\\\", "\\\\\\\\", "\"", "\"\"") + "\""; } /** * Quotes the given {@code value} so that it's safe to use * in a SQL query. */ public static String quoteValue(Object value) { if (value == null) { return "NULL"; } else if (value instanceof Number) { return value.toString(); } else if (value instanceof byte[]) { return "X'" + StringUtils.hex((byte[]) value) + "'"; } else { return "'" + value.toString().replace("'", "''").replace("\\", "\\\\") + "'"; } } /** Closes all resources used by all instances. */ public static void closeAll() { for (SqlDatabase database : INSTANCES) { database.close(); } INSTANCES.clear(); } /** * Creates an {@link SqlDatabaseException} that occurred during * an execution of a query. */ private SqlDatabaseException createQueryException( SQLException error, String sqlQuery, Query<?> query) { String message = error.getMessage(); if (error instanceof SQLTimeoutException || message.contains("timeout")) { return new SqlDatabaseException.ReadTimeout(this, error, sqlQuery, query); } else { return new SqlDatabaseException(this, error, sqlQuery, query); } } /** Returns the JDBC data source used for general database operations. */ public DataSource getDataSource() { return dataSource; } private static final Map<String, Class<? extends SqlVendor>> VENDOR_CLASSES; static { Map<String, Class<? extends SqlVendor>> m = new HashMap<String, Class<? extends SqlVendor>>(); m.put("H2", SqlVendor.H2.class); m.put("MySQL", SqlVendor.MySQL.class); m.put("PostgreSQL", SqlVendor.PostgreSQL.class); m.put("Oracle", SqlVendor.Oracle.class); VENDOR_CLASSES = m; } /** Sets the JDBC data source used for general database operations. */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; if (dataSource == null) { return; } synchronized (this) { try { boolean writable = false; if (vendor == null) { Connection connection; try { connection = openConnection(); writable = true; } catch (DatabaseException error) { LOGGER.debug("Can't read vendor information from the writable server!", error); connection = openReadConnection(); } try { DatabaseMetaData meta = connection.getMetaData(); String vendorName = meta.getDatabaseProductName(); Class<? extends SqlVendor> vendorClass = VENDOR_CLASSES.get(vendorName); LOGGER.info( "Initializing SQL vendor for [{}]: [{}] -> [{}]", new Object[] { getName(), vendorName, vendorClass }); vendor = vendorClass != null ? TypeDefinition.getInstance(vendorClass).newInstance() : new SqlVendor(); vendor.setDatabase(this); } finally { closeConnection(connection); } } tableNames.refresh(); symbols.invalidate(); if (writable) { vendor.createRecord(this); vendor.createRecordUpdate(this); vendor.createSymbol(this); for (SqlIndex index : SqlIndex.values()) { if (index != SqlIndex.CUSTOM) { vendor.createRecordIndex( this, index.getReadTable(this, null).getName(this, null), index); } } tableNames.refresh(); symbols.invalidate(); } } catch (SQLException ex) { throw new SqlDatabaseException(this, "Can't check for required tables!", ex); } } } /** Returns the JDBC data source used exclusively for read operations. */ public DataSource getReadDataSource() { return this.readDataSource; } /** Sets the JDBC data source used exclusively for read operations. */ public void setReadDataSource(DataSource readDataSource) { this.readDataSource = readDataSource; } /** Returns the vendor-specific SQL engine information. */ public SqlVendor getVendor() { return vendor; } /** Sets the vendor-specific SQL engine information. */ public void setVendor(SqlVendor vendor) { this.vendor = vendor; } /** Returns {@code true} if the data should be compressed. */ public boolean isCompressData() { return compressData; } /** Sets whether the data should be compressed. */ public void setCompressData(boolean compressData) { this.compressData = compressData; } /** * Returns {@code true} if the {@link #RECORD_TABLE} in this database * has the {@link #IN_ROW_INDEX_COLUMN}. */ public boolean hasInRowIndex() { return hasInRowIndex; } /** * Returns {@code true} if all comparisons executed in this database * should ignore case by default. */ public boolean comparesIgnoreCase() { return comparesIgnoreCase; } /** * Returns {@code true} if this database contains a table with * the given {@code name}. */ public boolean hasTable(String name) { if (name == null) { return false; } else { Set<String> names = tableNames.get(); return names != null && names.contains(name.toLowerCase()); } } private transient volatile boolean hasInRowIndex; private transient volatile boolean comparesIgnoreCase; private final transient PeriodicValue<Set<String>> tableNames = new PeriodicValue<Set<String>>(0.0, 60.0) { @Override protected Set<String> update() { if (getDataSource() == null) { return Collections.emptySet(); } Connection connection; try { connection = openConnection(); } catch (DatabaseException error) { LOGGER.debug("Can't read table names from the writable server!", error); connection = openReadConnection(); } try { SqlVendor vendor = getVendor(); String recordTable = null; int maxStringVersion = 0; Set<String> loweredNames = new HashSet<String>(); for (String name : vendor.getTables(connection)) { String loweredName = name.toLowerCase(); loweredNames.add(loweredName); if ("record".equals(loweredName)) { recordTable = name; } else if (loweredName.startsWith("recordstring")) { int version = ObjectUtils.to(int.class, loweredName.substring(12)); if (version > maxStringVersion) { maxStringVersion = version; } } } if (recordTable != null) { hasInRowIndex = vendor.hasInRowIndex(connection, recordTable); } comparesIgnoreCase = maxStringVersion >= 3; return loweredNames; } catch (SQLException error) { LOGGER.error("Can't query table names!", error); return get(); } finally { closeConnection(connection); } } }; /** * Returns an unique numeric ID for the given {@code symbol}. */ public int getSymbolId(String symbol) { Integer id = symbols.get().get(symbol); if (id == null) { SqlVendor vendor = getVendor(); Connection connection = openConnection(); try { List<Object> parameters = new ArrayList<Object>(); StringBuilder insertBuilder = new StringBuilder(); insertBuilder.append("INSERT /*! IGNORE */ INTO "); vendor.appendIdentifier(insertBuilder, SYMBOL_TABLE); insertBuilder.append(" ("); vendor.appendIdentifier(insertBuilder, VALUE_COLUMN); insertBuilder.append(") VALUES ("); vendor.appendBindValue(insertBuilder, symbol, parameters); insertBuilder.append(")"); String insertSql = insertBuilder.toString(); try { Static.executeUpdateWithList(connection, insertSql, parameters); } catch (SQLException ex) { if (!Static.isIntegrityConstraintViolation(ex)) { throw createQueryException(ex, insertSql, null); } } StringBuilder selectBuilder = new StringBuilder(); selectBuilder.append("SELECT "); vendor.appendIdentifier(selectBuilder, SYMBOL_ID_COLUMN); selectBuilder.append(" FROM "); vendor.appendIdentifier(selectBuilder, SYMBOL_TABLE); selectBuilder.append(" WHERE "); vendor.appendIdentifier(selectBuilder, VALUE_COLUMN); selectBuilder.append("="); vendor.appendValue(selectBuilder, symbol); String selectSql = selectBuilder.toString(); Statement statement = null; ResultSet result = null; try { statement = connection.createStatement(); result = statement.executeQuery(selectSql); result.next(); id = result.getInt(1); symbols.get().put(symbol, id); } catch (SQLException ex) { throw createQueryException(ex, selectSql, null); } finally { closeResources(null, statement, result); } } finally { closeConnection(connection); } } return id; } // Cache of all internal symbols. private transient PullThroughValue<Map<String, Integer>> symbols = new PullThroughValue<Map<String, Integer>>() { @Override protected Map<String, Integer> produce() { SqlVendor vendor = getVendor(); StringBuilder selectBuilder = new StringBuilder(); selectBuilder.append("SELECT "); vendor.appendIdentifier(selectBuilder, SYMBOL_ID_COLUMN); selectBuilder.append(","); vendor.appendIdentifier(selectBuilder, VALUE_COLUMN); selectBuilder.append(" FROM "); vendor.appendIdentifier(selectBuilder, SYMBOL_TABLE); String selectSql = selectBuilder.toString(); Connection connection; Statement statement = null; ResultSet result = null; try { connection = openConnection(); } catch (DatabaseException error) { LOGGER.debug("Can't read symbols from the writable server!", error); connection = openReadConnection(); } try { statement = connection.createStatement(); result = statement.executeQuery(selectSql); Map<String, Integer> symbols = new ConcurrentHashMap<String, Integer>(); while (result.next()) { symbols.put(new String(result.getBytes(2), StringUtils.UTF_8), result.getInt(1)); } return symbols; } catch (SQLException ex) { throw createQueryException(ex, selectSql, null); } finally { closeResources(connection, statement, result); } } }; /** * Returns the underlying JDBC connection. * * @deprecated Use {@link #openConnection} instead. */ @Deprecated public Connection getConnection() { return openConnection(); } /** Closes any resources used by this database. */ public void close() { DataSource dataSource = getDataSource(); if (dataSource instanceof BoneCPDataSource) { LOGGER.info("Closing BoneCP data source in {}", getName()); ((BoneCPDataSource) dataSource).close(); } DataSource readDataSource = getReadDataSource(); if (readDataSource instanceof BoneCPDataSource) { LOGGER.info("Closing BoneCP read data source in {}", getName()); ((BoneCPDataSource) readDataSource).close(); } setDataSource(null); setReadDataSource(null); } /** * Builds an SQL statement that can be used to get a count of all * objects matching the given {@code query}. */ public String buildCountStatement(Query<?> query) { return new SqlQuery(this, query).countStatement(); } /** * Builds an SQL statement that can be used to delete all rows * matching the given {@code query}. */ public String buildDeleteStatement(Query<?> query) { return new SqlQuery(this, query).deleteStatement(); } /** * Builds an SQL statement that can be used to get all objects * grouped by the values of the given {@code groupFields}. */ public String buildGroupStatement(Query<?> query, String... groupFields) { return new SqlQuery(this, query).groupStatement(groupFields); } /** * Builds an SQL statement that can be used to get when the objects * matching the given {@code query} were last updated. */ public String buildLastUpdateStatement(Query<?> query) { return new SqlQuery(this, query).lastUpdateStatement(); } /** * Builds an SQL statement that can be used to list all rows * matching the given {@code query}. */ public String buildSelectStatement(Query<?> query) { return new SqlQuery(this, query).selectStatement(); } /** Closes all the given SQL resources safely. */ private void closeResources(Connection connection, Statement statement, ResultSet result) { if (result != null) { try { result.close(); } catch (SQLException ex) { } } if (statement != null) { try { statement.close(); } catch (SQLException ex) { } } if (connection != null && connection != readConnection.get()) { try { connection.close(); } catch (SQLException ex) { } } } private byte[] serializeData(Map<String, Object> dataMap) { byte[] dataBytes = ObjectUtils.toJson(dataMap).getBytes(StringUtils.UTF_8); if (isCompressData()) { byte[] compressed = new byte[Snappy.maxCompressedLength(dataBytes.length)]; int compressedLength = Snappy.compress(dataBytes, 0, dataBytes.length, compressed, 0); dataBytes = new byte[compressedLength + 1]; dataBytes[0] = 's'; System.arraycopy(compressed, 0, dataBytes, 1, compressedLength); } return dataBytes; } @SuppressWarnings("unchecked") private Map<String, Object> unserializeData(byte[] dataBytes) { char format = '\0'; while (true) { format = (char) dataBytes[0]; if (format == 's') { dataBytes = Snappy.uncompress(dataBytes, 1, dataBytes.length - 1); } else if (format == '{') { return (Map<String, Object>) ObjectUtils.fromJson(new String(dataBytes, StringUtils.UTF_8)); } else { break; } } throw new IllegalStateException(String.format( "Unknown format! ([%s])", format)); } /** * Creates a previously saved object using the given {@code resultSet}. */ private <T> T createSavedObjectWithResultSet(ResultSet resultSet, Query<T> query) throws SQLException { T object = createSavedObject(resultSet.getObject(2), resultSet.getObject(1), query); State objectState = State.getInstance(object); if (!objectState.isReferenceOnly()) { byte[] data = resultSet.getBytes(3); if (data != null) { objectState.putAll(unserializeData(data)); Boolean returnOriginal = ObjectUtils.to(Boolean.class, query.getOptions().get(RETURN_ORIGINAL_DATA_QUERY_OPTION)); if (returnOriginal == null) { returnOriginal = Boolean.FALSE; } if (returnOriginal) { objectState.getExtras().put(ORIGINAL_DATA_EXTRA, data); } } } ResultSetMetaData meta = resultSet.getMetaData(); for (int i = 4, count = meta.getColumnCount(); i <= count; ++ i) { objectState.getExtras().put(EXTRA_COLUMN_EXTRA_PREFIX + meta.getColumnLabel(i), resultSet.getObject(i)); } return swapObjectType(query, object); } /** * Executes the given read {@code statement} (created from the given * {@code sqlQuery}) before the given {@code timeout} (in seconds). */ private ResultSet executeQueryBeforeTimeout( Statement statement, String sqlQuery, int timeout) throws SQLException { if (timeout > 0 && !(vendor instanceof SqlVendor.PostgreSQL)) { statement.setQueryTimeout(timeout); } Stats.Timer timer = STATS.startTimer(); Profiler.Static.startThreadEvent(QUERY_PROFILER_EVENT); try { return statement.executeQuery(sqlQuery); } finally { double duration = timer.stop(QUERY_STATS_OPERATION); Profiler.Static.stopThreadEvent(sqlQuery); LOGGER.debug( "Read from the SQL database using [{}] in [{}]ms", sqlQuery, duration); } } /** * Selects the first object that matches the given {@code sqlQuery} * with options from the given {@code query}. */ public <T> T selectFirstWithOptions(String sqlQuery, Query<T> query) { sqlQuery = vendor.rewriteQueryWithLimitClause(sqlQuery, 1, 0); Connection connection = null; Statement statement = null; ResultSet result = null; try { connection = openQueryConnection(query); statement = connection.createStatement(); result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query)); return result.next() ? createSavedObjectWithResultSet(result, query) : null; } catch (SQLException ex) { throw createQueryException(ex, sqlQuery, query); } finally { closeResources(connection, statement, result); } } /** * Selects the first object that matches the given {@code sqlQuery} * without a timeout. */ public Object selectFirst(String sqlQuery) { return selectFirstWithOptions(sqlQuery, null); } /** * Selects a list of objects that match the given {@code sqlQuery} * with options from the given {@code query}. */ public <T> List<T> selectListWithOptions(String sqlQuery, Query<T> query) { Connection connection = null; Statement statement = null; ResultSet result = null; List<T> objects = new ArrayList<T>(); int timeout = getQueryReadTimeout(query); try { connection = openQueryConnection(query); statement = connection.createStatement(); result = executeQueryBeforeTimeout(statement, sqlQuery, timeout); while (result.next()) { objects.add(createSavedObjectWithResultSet(result, query)); } return objects; } catch (SQLException ex) { throw createQueryException(ex, sqlQuery, query); } finally { closeResources(connection, statement, result); } } /** * Selects a list of objects that match the given {@code sqlQuery} * without a timeout. */ public List<Object> selectList(String sqlQuery) { return selectListWithOptions(sqlQuery, null); } /** * Returns an iterable that selects all objects matching the given * {@code sqlQuery} with options from the given {@code query}. */ public <T> Iterable<T> selectIterableWithOptions( final String sqlQuery, final int fetchSize, final Query<T> query) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new SqlIterator<T>(sqlQuery, fetchSize, query); } }; } private class SqlIterator<T> implements Iterator<T> { private final String sqlQuery; private final Query<T> query; private final Connection connection; private final Statement statement; private final ResultSet result; private boolean hasNext = true; public SqlIterator(String initialSqlQuery, int fetchSize, Query<T> initialQuery) { sqlQuery = initialSqlQuery; query = initialQuery; try { connection = openReadConnection(); statement = connection.createStatement(); statement.setFetchSize( getVendor() instanceof SqlVendor.MySQL ? Integer.MIN_VALUE : fetchSize <= 0 ? 200 : fetchSize); result = statement.executeQuery(sqlQuery); moveToNext(); } catch (SQLException ex) { close(); throw createQueryException(ex, sqlQuery, query); } } private void moveToNext() throws SQLException { if (hasNext) { hasNext = result.next(); if (!hasNext) { close(); } } } public void close() { hasNext = false; closeResources(connection, statement, result); } @Override public boolean hasNext() { return hasNext; } @Override public T next() { if (!hasNext) { throw new NoSuchElementException(); } try { T object = createSavedObjectWithResultSet(result, query); moveToNext(); return object; } catch (SQLException ex) { close(); throw createQueryException(ex, sqlQuery, query); } } @Override public void remove() { throw new UnsupportedOperationException(); } @Override protected void finalize() { close(); } } /** * Fills the placeholders in the given {@code sqlQuery} with the given * {@code parameters}. */ private static String fillPlaceholders(String sqlQuery, Object... parameters) { StringBuilder filled = new StringBuilder(); int prevPh = 0; for (int ph, index = 0; (ph = sqlQuery.indexOf('?', prevPh)) > -1; ++ index) { filled.append(sqlQuery.substring(prevPh, ph)); prevPh = ph + 1; filled.append(quoteValue(parameters[index])); } filled.append(sqlQuery.substring(prevPh)); return filled.toString(); } /** * Executes the given write {@code sqlQuery} with the given * {@code parameters}. * * @deprecated Use {@link Static#executeUpdate} instead. */ @Deprecated public int executeUpdate(String sqlQuery, Object... parameters) { try { return Static.executeUpdateWithArray(getConnection(), sqlQuery, parameters); } catch (SQLException ex) { throw createQueryException(ex, fillPlaceholders(sqlQuery, parameters), null); } } /** * Reads the given {@code resultSet} into a list of maps * and closes it. */ public List<Map<String, Object>> readResultSet(ResultSet resultSet) throws SQLException { try { ResultSetMetaData meta = resultSet.getMetaData(); List<String> columnNames = new ArrayList<String>(); for (int i = 1, count = meta.getColumnCount(); i < count; ++ i) { columnNames.add(meta.getColumnName(i)); } List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>(); while (resultSet.next()) { Map<String, Object> map = new LinkedHashMap<String, Object>(); maps.add(map); for (int i = 0, size = columnNames.size(); i < size; ++ i) { map.put(columnNames.get(i), resultSet.getObject(i + 1)); } } return maps; } finally { resultSet.close(); } } @Override public Connection openConnection() { DataSource dataSource = getDataSource(); if (dataSource == null) { throw new SqlDatabaseException(this, "No SQL data source!"); } try { return dataSource.getConnection(); } catch (SQLException ex) { throw new SqlDatabaseException(this, "Can't connect to the SQL engine!", ex); } } @Override protected Connection doOpenReadConnection() { Connection connection = readConnection.get(); if (connection != null) { return connection; } DataSource readDataSource = getReadDataSource(); if (readDataSource == null) { readDataSource = getDataSource(); } if (readDataSource == null) { throw new SqlDatabaseException(this, "No SQL data source!"); } try { return readDataSource.getConnection(); } catch (SQLException ex) { throw new SqlDatabaseException(this, "Can't connect to the SQL engine!", ex); } } // Opens a connection that should be used to execute the given query. private Connection openQueryConnection(Query<?> query) { if (query != null) { Boolean useRead = ObjectUtils.to(Boolean.class, query.getOptions().get(USE_READ_DATA_SOURCE_QUERY_OPTION)); if (useRead == null) { useRead = Boolean.TRUE; } if (!useRead) { return openConnection(); } } return openReadConnection(); } @Override public void closeConnection(Connection connection) { if (connection != null && connection != readConnection.get()) { try { connection.close(); } catch (SQLException ex) { } } } @Override protected boolean isRecoverableError(Exception error) { if (error instanceof SQLException) { SQLException sqlError = (SQLException) error; return "40001".equals(sqlError.getSQLState()); } return false; } private final ThreadLocal<Connection> readConnection = new ThreadLocal<Connection>(); public void beginThreadLocalReadConnection() { Connection connection = readConnection.get(); if (connection == null) { connection = openReadConnection(); readConnection.set(connection); } } public void endThreadLocalReadConnection() { Connection connection = readConnection.get(); if (connection != null) { try { connection.close(); } catch (SQLException ex) { } finally { readConnection.remove(); } } } @Override protected void doInitialize(String settingsKey, Map<String, Object> settings) { close(); setReadDataSource(createDataSource( settings, READ_DATA_SOURCE_SETTING, READ_JDBC_DRIVER_CLASS_SETTING, READ_JDBC_URL_SETTING, READ_JDBC_USER_SETTING, READ_JDBC_PASSWORD_SETTING, READ_JDBC_POOL_SIZE_SETTING)); setDataSource(createDataSource( settings, DATA_SOURCE_SETTING, JDBC_DRIVER_CLASS_SETTING, JDBC_URL_SETTING, JDBC_USER_SETTING, JDBC_PASSWORD_SETTING, JDBC_POOL_SIZE_SETTING)); String vendorClassName = ObjectUtils.to(String.class, settings.get(VENDOR_CLASS_SETTING)); Class<?> vendorClass = null; if (vendorClassName != null) { vendorClass = ObjectUtils.getClassByName(vendorClassName); if (vendorClass == null) { throw new SettingsException( VENDOR_CLASS_SETTING, String.format("Can't find [%s]!", vendorClassName)); } else if (!SqlVendor.class.isAssignableFrom(vendorClass)) { throw new SettingsException( VENDOR_CLASS_SETTING, String.format("[%s] doesn't implement [%s]!", vendorClass, Driver.class)); } } if (vendorClass != null) { setVendor((SqlVendor) TypeDefinition.getInstance(vendorClass).newInstance()); } Boolean compressData = ObjectUtils.coalesce( ObjectUtils.to(Boolean.class, settings.get(COMPRESS_DATA_SUB_SETTING)), Settings.get(Boolean.class, "dari/isCompressSqlData")); if (compressData != null) { setCompressData(compressData); } } private static final Map<String, String> DRIVER_CLASS_NAMES; static { Map<String, String> m = new HashMap<String, String>(); m.put("h2", "org.h2.Driver"); m.put("jtds", "net.sourceforge.jtds.jdbc.Driver"); m.put("mysql", "com.mysql.jdbc.Driver"); m.put("postgresql", "org.postgresql.Driver"); DRIVER_CLASS_NAMES = m; } private static final Set<WeakReference<Driver>> REGISTERED_DRIVERS = new HashSet<WeakReference<Driver>>(); private DataSource createDataSource( Map<String, Object> settings, String dataSourceSetting, String jdbcDriverClassSetting, String jdbcUrlSetting, String jdbcUserSetting, String jdbcPasswordSetting, String jdbcPoolSizeSetting) { Object dataSourceObject = settings.get(dataSourceSetting); if (dataSourceObject instanceof DataSource) { return (DataSource) dataSourceObject; } else { String url = ObjectUtils.to(String.class, settings.get(jdbcUrlSetting)); if (ObjectUtils.isBlank(url)) { return null; } else { String driverClassName = ObjectUtils.to(String.class, settings.get(jdbcDriverClassSetting)); Class<?> driverClass = null; if (driverClassName != null) { driverClass = ObjectUtils.getClassByName(driverClassName); if (driverClass == null) { throw new SettingsException( jdbcDriverClassSetting, String.format("Can't find [%s]!", driverClassName)); } else if (!Driver.class.isAssignableFrom(driverClass)) { throw new SettingsException( jdbcDriverClassSetting, String.format("[%s] doesn't implement [%s]!", driverClass, Driver.class)); } } else { int firstColonAt = url.indexOf(':'); if (firstColonAt > -1) { ++ firstColonAt; int secondColonAt = url.indexOf(':', firstColonAt); if (secondColonAt > -1) { driverClass = ObjectUtils.getClassByName(DRIVER_CLASS_NAMES.get(url.substring(firstColonAt, secondColonAt))); } } } if (driverClass != null) { Driver driver = null; for (Enumeration<Driver> e = DriverManager.getDrivers(); e.hasMoreElements(); ) { Driver d = e.nextElement(); if (driverClass.isInstance(d)) { driver = d; break; } } if (driver == null) { driver = (Driver) TypeDefinition.getInstance(driverClass).newInstance(); try { LOGGER.info("Registering [{}]", driver); DriverManager.registerDriver(driver); } catch (SQLException ex) { LOGGER.warn("Can't register [{}]!", driver); } } if (driver != null) { REGISTERED_DRIVERS.add(new WeakReference<Driver>(driver)); } } String user = ObjectUtils.to(String.class, settings.get(jdbcUserSetting)); String password = ObjectUtils.to(String.class, settings.get(jdbcPasswordSetting)); Integer poolSize = ObjectUtils.to(Integer.class, settings.get(jdbcPoolSizeSetting)); if (poolSize == null || poolSize <= 0) { poolSize = 24; } int partitionCount = 3; int connectionsPerPartition = poolSize / partitionCount; LOGGER.info("Automatically creating BoneCP data source:" + "\n\turl={}" + "\n\tusername={}" + "\n\tpoolSize={}" + "\n\tconnectionsPerPartition={}" + "\n\tpartitionCount={}", new Object[] { url, user, poolSize, connectionsPerPartition, partitionCount }); BoneCPDataSource bone = new BoneCPDataSource(); bone.setJdbcUrl(url); bone.setUsername(user); bone.setPassword(password); bone.setMinConnectionsPerPartition(connectionsPerPartition); bone.setMaxConnectionsPerPartition(connectionsPerPartition); bone.setPartitionCount(partitionCount); return bone; } } } /** Returns the read timeout associated with the given {@code query}. */ private int getQueryReadTimeout(Query<?> query) { if (query != null) { Double timeout = query.getTimeout(); if (timeout == null) { timeout = getReadTimeout(); } if (timeout > 0.0) { return (int) Math.round(timeout); } } return 0; } @Override public <T> List<T> readAll(Query<T> query) { return selectListWithOptions(buildSelectStatement(query), query); } @Override public long readCount(Query<?> query) { String sqlQuery = buildCountStatement(query); Connection connection = null; Statement statement = null; ResultSet result = null; try { connection = openQueryConnection(query); statement = connection.createStatement(); result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query)); if (result.next()) { Object countObj = result.getObject(1); if (countObj instanceof Number) { return ((Number) countObj).longValue(); } } return 0; } catch (SQLException ex) { throw createQueryException(ex, sqlQuery, query); } finally { closeResources(connection, statement, result); } } @Override public <T> T readFirst(Query<T> query) { if (query.getSorters().isEmpty()) { Predicate predicate = query.getPredicate(); if (predicate instanceof CompoundPredicate) { CompoundPredicate compoundPredicate = (CompoundPredicate) predicate; if (PredicateParser.OR_OPERATOR.equals(compoundPredicate.getOperator())) { for (Predicate child : compoundPredicate.getChildren()) { Query<T> childQuery = query.clone(); childQuery.setPredicate(child); T first = readFirst(childQuery); if (first != null) { return first; } } return null; } } } return selectFirstWithOptions(buildSelectStatement(query), query); } @Override public <T> Iterable<T> readIterable(Query<T> query, int fetchSize) { Boolean useJdbc = ObjectUtils.to(Boolean.class, query.getOptions().get(USE_JDBC_FETCH_SIZE_QUERY_OPTION)); if (useJdbc == null) { useJdbc = Boolean.TRUE; } if (useJdbc) { return selectIterableWithOptions(buildSelectStatement(query), fetchSize, query); } else { return new ByIdIterable<T>(query, fetchSize); } } private static class ByIdIterable<T> implements Iterable<T> { private final Query<T> query; private final int fetchSize; public ByIdIterable(Query<T> query, int fetchSize) { this.query = query; this.fetchSize = fetchSize; } @Override public Iterator<T> iterator() { return new ByIdIterator<T>(query, fetchSize); } } private static class ByIdIterator<T> implements Iterator<T> { private final Query<T> query; private final int fetchSize; private UUID lastTypeId; private UUID lastId; private List<T> items; private int index; public ByIdIterator(Query<T> query, int fetchSize) { if (!query.getSorters().isEmpty()) { throw new IllegalArgumentException("Can't iterate over a query that has sorters!"); } this.query = query.clone().timeout(0.0).sortAscending("_type").sortAscending("_id"); this.fetchSize = fetchSize > 0 ? fetchSize : 200; } @Override public boolean hasNext() { if (items != null && items.isEmpty()) { return false; } if (items == null || index >= items.size()) { Query<T> nextQuery = query.clone(); if (lastTypeId != null) { nextQuery.and("_type = ? and _id > ?", lastTypeId, lastId); } items = nextQuery.select(0, fetchSize).getItems(); int size = items.size(); if (size < 1) { if (lastTypeId == null) { return false; } else { nextQuery = query.clone().and("_type > ?", lastTypeId); items = nextQuery.select(0, fetchSize).getItems(); size = items.size(); if (size < 1) { return false; } } } State lastState = State.getInstance(items.get(size - 1)); lastTypeId = lastState.getTypeId(); lastId = lastState.getId(); index = 0; } return true; } @Override public T next() { if (hasNext()) { T object = items.get(index); ++ index; return object; } else { throw new NoSuchElementException(); } } @Override public void remove() { throw new UnsupportedOperationException(); } } @Override public Date readLastUpdate(Query<?> query) { String sqlQuery = buildLastUpdateStatement(query); Connection connection = null; Statement statement = null; ResultSet result = null; try { connection = openQueryConnection(query); statement = connection.createStatement(); result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query)); if (result.next()) { Double date = result.getDouble(1); if (date != null) { return new Date((long) (date * 1000L)); } } return null; } catch (SQLException ex) { throw createQueryException(ex, sqlQuery, query); } finally { closeResources(connection, statement, result); } } @Override public <T> PaginatedResult<T> readPartial(final Query<T> query, long offset, int limit) { List<T> objects = selectListWithOptions( vendor.rewriteQueryWithLimitClause(buildSelectStatement(query), limit + 1, offset), query); int size = objects.size(); if (size <= limit) { return new PaginatedResult<T>(offset, limit, offset + size, objects); } else { objects.remove(size - 1); return new PaginatedResult<T>(offset, limit, 0, objects) { private Long count; @Override public long getCount() { if (count == null) { count = readCount(query); } return count; } @Override public boolean hasNext() { return true; } }; } } @Override public <T> PaginatedResult<Grouping<T>> readPartialGrouped(Query<T> query, long offset, int limit, String... fields) { List<Grouping<T>> groupings = new ArrayList<Grouping<T>>(); String sqlQuery = buildGroupStatement(query, fields); Connection connection = null; Statement statement = null; ResultSet result = null; try { connection = openQueryConnection(query); statement = connection.createStatement(); result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query)); int fieldsLength = fields.length; int groupingsCount = 0; for (int i = 0, last = (int) offset + limit; result.next(); ++ i, ++ groupingsCount) { if (i < offset || i >= last) { continue; } long count = ObjectUtils.to(long.class, result.getObject(1)); List<Object> keys = new ArrayList<Object>(); for (int j = 0; j < fieldsLength; ++ j) { keys.add(result.getObject(j + 2)); } groupings.add(new SqlGrouping<T>(keys, query, fields, count)); } int groupingsSize = groupings.size(); for (int i = 0; i < fieldsLength; ++ i) { ObjectField field = query.mapEmbeddedKey(getEnvironment(), fields[i]).getField(); if (field != null) { Map<String, Object> rawKeys = new HashMap<String, Object>(); for (int j = 0; j < groupingsSize; ++ j) { rawKeys.put(String.valueOf(j), groupings.get(j).getKeys().get(i)); } String itemType = field.getInternalItemType(); if (ObjectField.RECORD_TYPE.equals(itemType)) { for (Map.Entry<String, Object> entry : rawKeys.entrySet()) { Map<String, Object> ref = new HashMap<String, Object>(); ref.put(StateValueUtils.REFERENCE_KEY, entry.getValue()); entry.setValue(ref); } } Map<?, ?> convertedKeys = (Map<?, ?>) StateValueUtils.toJavaValue(query.getDatabase(), null, field, "map/" + itemType, rawKeys); for (int j = 0; j < groupingsSize; ++ j) { groupings.get(j).getKeys().set(i, convertedKeys.get(String.valueOf(j))); } } } return new PaginatedResult<Grouping<T>>(offset, limit, groupingsCount, groupings); } catch (SQLException ex) { throw createQueryException(ex, sqlQuery, query); } finally { closeResources(connection, statement, result); } } /** SQL-specific implementation of {@link Grouping}. */ private class SqlGrouping<T> extends AbstractGrouping<T> { private long count; public SqlGrouping(List<Object> keys, Query<T> query, String[] fields, long count) { super(keys, query, fields); this.count = count; } @Override protected Aggregate createAggregate(String field) { throw new UnsupportedOperationException(); } @Override public long getCount() { return count; } } @Override protected void beginTransaction(Connection connection, boolean isImmediate) throws SQLException { connection.setAutoCommit(false); } @Override protected void commitTransaction(Connection connection, boolean isImmediate) throws SQLException { connection.commit(); } @Override protected void rollbackTransaction(Connection connection, boolean isImmediate) throws SQLException { connection.rollback(); } @Override protected void endTransaction(Connection connection, boolean isImmediate) throws SQLException { connection.setAutoCommit(true); } @Override protected void doSaves(Connection connection, boolean isImmediate, List<State> states) throws SQLException { List<State> indexStates = null; for (State state1 : states) { if (Boolean.TRUE.equals(state1.getExtra(SKIP_INDEX_STATE_EXTRA))) { indexStates = new ArrayList<State>(); for (State state2 : states) { if (!Boolean.TRUE.equals(state2.getExtra(SKIP_INDEX_STATE_EXTRA))) { indexStates.add(state2); } } break; } } if (indexStates == null) { indexStates = states; } SqlIndex.Static.deleteByStates(this, connection, indexStates); Map<State, String> inRowIndexes = SqlIndex.Static.insertByStates(this, connection, indexStates); boolean hasInRowIndex = hasInRowIndex(); SqlVendor vendor = getVendor(); double now = System.currentTimeMillis() / 1000.0; for (State state : states) { boolean isNew = state.isNew(); boolean saveInRowIndex = hasInRowIndex && !Boolean.TRUE.equals(state.getExtra(SKIP_INDEX_STATE_EXTRA)); UUID id = state.getId(); UUID typeId = state.getTypeId(); byte[] dataBytes = null; String inRowIndex = inRowIndexes.get(state); byte[] inRowIndexBytes = inRowIndex != null ? inRowIndex.getBytes(StringUtils.UTF_8) : new byte[0]; while (true) { if (isNew) { try { if (dataBytes == null) { dataBytes = serializeData(state.getSimpleValues()); } List<Object> parameters = new ArrayList<Object>(); StringBuilder insertBuilder = new StringBuilder(); insertBuilder.append("INSERT INTO "); vendor.appendIdentifier(insertBuilder, RECORD_TABLE); insertBuilder.append(" ("); vendor.appendIdentifier(insertBuilder, ID_COLUMN); insertBuilder.append(","); vendor.appendIdentifier(insertBuilder, TYPE_ID_COLUMN); insertBuilder.append(","); vendor.appendIdentifier(insertBuilder, DATA_COLUMN); if (saveInRowIndex) { insertBuilder.append(","); vendor.appendIdentifier(insertBuilder, IN_ROW_INDEX_COLUMN); } insertBuilder.append(") VALUES ("); vendor.appendBindValue(insertBuilder, id, parameters); insertBuilder.append(","); vendor.appendBindValue(insertBuilder, typeId, parameters); insertBuilder.append(","); vendor.appendBindValue(insertBuilder, dataBytes, parameters); if (saveInRowIndex) { insertBuilder.append(","); vendor.appendBindValue(insertBuilder, inRowIndexBytes, parameters); } insertBuilder.append(")"); Static.executeUpdateWithList(connection, insertBuilder.toString(), parameters); } catch (SQLException ex) { if (Static.isIntegrityConstraintViolation(ex)) { isNew = false; continue; } else { throw ex; } } } else { List<AtomicOperation> atomicOperations = state.getAtomicOperations(); if (atomicOperations.isEmpty()) { if (dataBytes == null) { dataBytes = serializeData(state.getSimpleValues()); } List<Object> parameters = new ArrayList<Object>(); StringBuilder updateBuilder = new StringBuilder(); updateBuilder.append("UPDATE "); vendor.appendIdentifier(updateBuilder, RECORD_TABLE); updateBuilder.append(" SET "); vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN); updateBuilder.append("="); vendor.appendBindValue(updateBuilder, typeId, parameters); updateBuilder.append(","); if (saveInRowIndex) { vendor.appendIdentifier(updateBuilder, IN_ROW_INDEX_COLUMN); updateBuilder.append("="); vendor.appendBindValue(updateBuilder, inRowIndexBytes, parameters); updateBuilder.append(","); } vendor.appendIdentifier(updateBuilder, DATA_COLUMN); updateBuilder.append("="); vendor.appendBindValue(updateBuilder, dataBytes, parameters); updateBuilder.append(" WHERE "); vendor.appendIdentifier(updateBuilder, ID_COLUMN); updateBuilder.append("="); vendor.appendBindValue(updateBuilder, id, parameters); if (Static.executeUpdateWithList(connection, updateBuilder.toString(), parameters) < 1) { isNew = true; continue; } } else { Object oldObject = Query. from(Object.class). where("_id = ?", id). using(this). resolveToReferenceOnly(). option(RETURN_ORIGINAL_DATA_QUERY_OPTION, Boolean.TRUE). option(USE_READ_DATA_SOURCE_QUERY_OPTION, Boolean.FALSE). first(); if (oldObject == null) { isNew = true; continue; } State oldState = State.getInstance(oldObject); UUID oldTypeId = oldState.getTypeId(); byte[] oldData = Static.getOriginalData(oldObject); for (AtomicOperation operation : atomicOperations) { String field = operation.getField(); state.putValue(field, oldState.getValue(field)); } for (AtomicOperation operation : atomicOperations) { operation.execute(state); } dataBytes = serializeData(state.getSimpleValues()); List<Object> parameters = new ArrayList<Object>(); StringBuilder updateBuilder = new StringBuilder(); updateBuilder.append("UPDATE "); vendor.appendIdentifier(updateBuilder, RECORD_TABLE); updateBuilder.append(" SET "); vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN); updateBuilder.append("="); vendor.appendBindValue(updateBuilder, typeId, parameters); if (saveInRowIndex) { updateBuilder.append(","); vendor.appendIdentifier(updateBuilder, IN_ROW_INDEX_COLUMN); updateBuilder.append("="); vendor.appendBindValue(updateBuilder, inRowIndexBytes, parameters); } updateBuilder.append(","); vendor.appendIdentifier(updateBuilder, DATA_COLUMN); updateBuilder.append("="); vendor.appendBindValue(updateBuilder, dataBytes, parameters); updateBuilder.append(" WHERE "); vendor.appendIdentifier(updateBuilder, ID_COLUMN); updateBuilder.append("="); vendor.appendBindValue(updateBuilder, id, parameters); updateBuilder.append(" AND "); vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN); updateBuilder.append("="); vendor.appendBindValue(updateBuilder, oldTypeId, parameters); updateBuilder.append(" AND "); vendor.appendIdentifier(updateBuilder, DATA_COLUMN); updateBuilder.append("="); vendor.appendBindValue(updateBuilder, oldData, parameters); if (Static.executeUpdateWithList(connection, updateBuilder.toString(), parameters) < 1) { continue; } } } break; } while (true) { if (isNew) { List<Object> parameters = new ArrayList<Object>(); StringBuilder insertBuilder = new StringBuilder(); insertBuilder.append("INSERT INTO "); vendor.appendIdentifier(insertBuilder, RECORD_UPDATE_TABLE); insertBuilder.append(" ("); vendor.appendIdentifier(insertBuilder, ID_COLUMN); insertBuilder.append(","); vendor.appendIdentifier(insertBuilder, TYPE_ID_COLUMN); insertBuilder.append(","); vendor.appendIdentifier(insertBuilder, UPDATE_DATE_COLUMN); insertBuilder.append(") VALUES ("); vendor.appendBindValue(insertBuilder, id, parameters); insertBuilder.append(","); vendor.appendBindValue(insertBuilder, typeId, parameters); insertBuilder.append(","); vendor.appendBindValue(insertBuilder, now, parameters); insertBuilder.append(")"); try { Static.executeUpdateWithList(connection, insertBuilder.toString(), parameters); } catch (SQLException ex) { if (Static.isIntegrityConstraintViolation(ex)) { isNew = false; continue; } else { throw ex; } } } else { List<Object> parameters = new ArrayList<Object>(); StringBuilder updateBuilder = new StringBuilder(); updateBuilder.append("UPDATE "); vendor.appendIdentifier(updateBuilder, RECORD_UPDATE_TABLE); updateBuilder.append(" SET "); vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN); updateBuilder.append("="); vendor.appendBindValue(updateBuilder, typeId, parameters); updateBuilder.append(","); vendor.appendIdentifier(updateBuilder, UPDATE_DATE_COLUMN); updateBuilder.append("="); vendor.appendBindValue(updateBuilder, now, parameters); updateBuilder.append(" WHERE "); vendor.appendIdentifier(updateBuilder, ID_COLUMN); updateBuilder.append("="); vendor.appendBindValue(updateBuilder, id, parameters); if (Static.executeUpdateWithList(connection, updateBuilder.toString(), parameters) < 1) { isNew = true; continue; } } break; } } } @Override protected void doIndexes(Connection connection, boolean isImmediate, List<State> states) throws SQLException { SqlIndex.Static.deleteByStates(this, connection, states); Map<State, String> inRowIndexes = SqlIndex.Static.insertByStates(this, connection, states); if (!hasInRowIndex()) { return; } SqlVendor vendor = getVendor(); for (Map.Entry<State, String> entry : inRowIndexes.entrySet()) { StringBuilder updateBuilder = new StringBuilder(); updateBuilder.append("UPDATE "); vendor.appendIdentifier(updateBuilder, RECORD_TABLE); updateBuilder.append(" SET "); vendor.appendIdentifier(updateBuilder, IN_ROW_INDEX_COLUMN); updateBuilder.append("="); vendor.appendValue(updateBuilder, entry.getValue()); updateBuilder.append(" WHERE "); vendor.appendIdentifier(updateBuilder, ID_COLUMN); updateBuilder.append("="); vendor.appendValue(updateBuilder, entry.getKey().getId()); Static.executeUpdateWithArray(connection, updateBuilder.toString()); } } /** @deprecated Use {@link #index} instead. */ @Deprecated public void fixIndexes(List<State> states) { Connection connection = openConnection(); try { doIndexes(connection, true, states); } catch (SQLException ex) { List<UUID> ids = new ArrayList<UUID>(); for (State state : states) { ids.add(state.getId()); } throw new SqlDatabaseException(this, String.format( "Can't index states! (%s)", ids)); } finally { closeConnection(connection); } } @Override protected void doDeletes(Connection connection, boolean isImmediate, List<State> states) throws SQLException { SqlVendor vendor = getVendor(); StringBuilder whereBuilder = new StringBuilder(); whereBuilder.append(" WHERE "); vendor.appendIdentifier(whereBuilder, ID_COLUMN); whereBuilder.append(" IN ("); for (State state : states) { vendor.appendValue(whereBuilder, state.getId()); whereBuilder.append(","); } whereBuilder.setCharAt(whereBuilder.length() - 1, ')'); StringBuilder deleteBuilder = new StringBuilder(); deleteBuilder.append("DELETE FROM "); vendor.appendIdentifier(deleteBuilder, RECORD_TABLE); deleteBuilder.append(whereBuilder); Static.executeUpdateWithArray(connection, deleteBuilder.toString()); SqlIndex.Static.deleteByStates(this, connection, states); StringBuilder updateBuilder = new StringBuilder(); updateBuilder.append("UPDATE "); vendor.appendIdentifier(updateBuilder, RECORD_UPDATE_TABLE); updateBuilder.append(" SET "); vendor.appendIdentifier(updateBuilder, UPDATE_DATE_COLUMN); updateBuilder.append("="); vendor.appendValue(updateBuilder, System.currentTimeMillis() / 1000.0); updateBuilder.append(whereBuilder); Static.executeUpdateWithArray(connection, updateBuilder.toString()); } /** Specifies the name of the table for storing target field values. */ @Documented @ObjectField.AnnotationProcessorClass(FieldIndexTableProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldIndexTable { String value(); } private static class FieldIndexTableProcessor implements ObjectField.AnnotationProcessor<FieldIndexTable> { @Override public void process(ObjectType type, ObjectField field, FieldIndexTable annotation) { field.getOptions().put(INDEX_TABLE_INDEX_OPTION, annotation.value()); } } /** {@link SqlDatabase} utility methods. */ public static final class Static { private Static() { } public static List<SqlDatabase> getAll() { return INSTANCES; } public static void deregisterAllDrivers() { for (WeakReference<Driver> driverRef : REGISTERED_DRIVERS) { Driver driver = driverRef.get(); if (driver != null) { LOGGER.info("Deregistering [{}]", driver); try { DriverManager.deregisterDriver(driver); } catch (SQLException ex) { LOGGER.warn("Can't deregister [{}]!", driver); } } } } /** * Log a batch update exception with values. */ static void logBatchUpdateException(BatchUpdateException bue, String sqlQuery, List<? extends List<?>> parameters) { int i = 0; int failureOffset = bue.getUpdateCounts().length; List<?> rowData = parameters.get(failureOffset); StringBuilder errorBuilder = new StringBuilder(); errorBuilder.append("Batch update failed with query '"); errorBuilder.append(sqlQuery); errorBuilder.append("' with values ("); for (Object value : rowData) { if (i++ != 0) { errorBuilder.append(", "); } if (value instanceof byte[]) { errorBuilder.append(StringUtils.hex((byte[]) value)); } else { errorBuilder.append(value); } } errorBuilder.append(")"); Exception ex = bue.getNextException() != null ? bue.getNextException() : bue; LOGGER.error(errorBuilder.toString(), ex); } static void logUpdateException(String sqlQuery, List<?> parameters) { int i = 0; StringBuilder errorBuilder = new StringBuilder(); errorBuilder.append("Batch update failed with query '"); errorBuilder.append(sqlQuery); errorBuilder.append("' with values ("); for (Object value : parameters) { if (i++ != 0) { errorBuilder.append(", "); } if (value instanceof byte[]) { errorBuilder.append(StringUtils.hex((byte[]) value)); } else { errorBuilder.append(value); } } errorBuilder.append(")"); LOGGER.error(errorBuilder.toString()); } // Safely binds the given parameter to the given statement at the // given index. private static void bindParameter(PreparedStatement statement, int index, Object parameter) throws SQLException { if (parameter instanceof String) { parameter = ((String) parameter).getBytes(StringUtils.UTF_8); } if (parameter instanceof byte[]) { byte[] parameterBytes = (byte[]) parameter; int parameterBytesLength = parameterBytes.length; if (parameterBytesLength > 2000) { statement.setBinaryStream(index, new ByteArrayInputStream(parameterBytes), parameterBytesLength); return; } } statement.setObject(index, parameter); } /** * Executes the given batch update {@code sqlQuery} with the given * list of {@code parameters} within the given {@code connection}. * * @return Array of number of rows affected by the update query. */ public static int[] executeBatchUpdate( Connection connection, String sqlQuery, List<? extends List<?>> parameters) throws SQLException { PreparedStatement prepared = connection.prepareStatement(sqlQuery); List<?> currentRow = null; try { for (List<?> row : parameters) { currentRow = row; int columnIndex = 1; for (Object parameter : row) { bindParameter(prepared, columnIndex, parameter); columnIndex++; } prepared.addBatch(); } int[] affected = null; Stats.Timer timer = STATS.startTimer(); Profiler.Static.startThreadEvent(UPDATE_PROFILER_EVENT); try { return (affected = prepared.executeBatch()); } finally { double time = timer.stop(UPDATE_STATS_OPERATION); Profiler.Static.stopThreadEvent(sqlQuery); if (LOGGER.isDebugEnabled()) { LOGGER.debug( "SQL batch update: [{}], Parameters: {}, Affected: {}, Time: [{}]ms", new Object[] { sqlQuery, parameters, affected != null ? Arrays.toString(affected) : "[]", time }); } } } catch (SQLException error) { logUpdateException(sqlQuery, currentRow); throw error; } finally { try { prepared.close(); } catch (SQLException error) { } } } /** * Executes the given update {@code sqlQuery} with the given * {@code parameters} within the given {@code connection}. * * @return Number of rows affected by the update query. */ public static int executeUpdateWithList( Connection connection, String sqlQuery, List<?> parameters) throws SQLException { if (parameters == null) { return executeUpdateWithArray(connection, sqlQuery); } else { Object[] array = parameters.toArray(new Object[parameters.size()]); return executeUpdateWithArray(connection, sqlQuery, array); } } /** * Executes the given update {@code sqlQuery} with the given * {@code parameters} within the given {@code connection}. * * @return Number of rows affected by the update query. */ public static int executeUpdateWithArray( Connection connection, String sqlQuery, Object... parameters) throws SQLException { boolean hasParameters = parameters != null && parameters.length > 0; PreparedStatement prepared; Statement statement; if (hasParameters) { prepared = connection.prepareStatement(sqlQuery); statement = prepared; } else { prepared = null; statement = connection.createStatement(); } try { if (hasParameters) { for (int i = 0; i < parameters.length; i++) { bindParameter(prepared, i + 1, parameters[i]); } } Integer affected = null; Stats.Timer timer = STATS.startTimer(); Profiler.Static.startThreadEvent(UPDATE_PROFILER_EVENT); try { return (affected = hasParameters ? prepared.executeUpdate() : statement.executeUpdate(sqlQuery)); } finally { double time = timer.stop(UPDATE_STATS_OPERATION); Profiler.Static.stopThreadEvent(sqlQuery); if (LOGGER.isDebugEnabled()) { LOGGER.debug( "SQL update: [{}], Affected: [{}], Time: [{}]ms", new Object[] { fillPlaceholders(sqlQuery, parameters), affected, time }); } } } finally { try { statement.close(); } catch (SQLException ex) { } } } /** * Returns {@code true} if the given {@code error} looks like a * {@link SQLIntegrityConstraintViolationException}. */ public static boolean isIntegrityConstraintViolation(SQLException error) { if (error instanceof SQLIntegrityConstraintViolationException) { return true; } else { String state = error.getSQLState(); return state != null && state.startsWith("23"); } } /** * Returns the name of the table for storing the values of the * given {@code index}. */ public static String getIndexTable(ObjectIndex index) { return ObjectUtils.to(String.class, index.getOptions().get(INDEX_TABLE_INDEX_OPTION)); } /** * Sets the name of the table for storing the values of the * given {@code index}. */ public static void setIndexTable(ObjectIndex index, String table) { index.getOptions().put(INDEX_TABLE_INDEX_OPTION, table); } public static Object getExtraColumn(Object object, String name) { return State.getInstance(object).getExtra(EXTRA_COLUMN_EXTRA_PREFIX + name); } public static byte[] getOriginalData(Object object) { return (byte[]) State.getInstance(object).getExtra(ORIGINAL_DATA_EXTRA); } /** @deprecated Use {@link #executeUpdateWithArray} instead. */ @Deprecated public static int executeUpdate( Connection connection, String sqlQuery, Object... parameters) throws SQLException { return executeUpdateWithArray(connection, sqlQuery, parameters); } } }
package com.psddev.dari.db; import java.io.ByteArrayInputStream; import java.io.IOException; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.ref.WeakReference; import java.sql.BatchUpdateException; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Driver; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.SQLIntegrityConstraintViolationException; import java.sql.SQLRecoverableException; import java.sql.SQLTimeoutException; import java.sql.Savepoint; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import javax.sql.DataSource; import org.iq80.snappy.Snappy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.jolbox.bonecp.BoneCPDataSource; import com.psddev.dari.util.Lazy; import com.psddev.dari.util.ObjectUtils; import com.psddev.dari.util.PaginatedResult; import com.psddev.dari.util.PeriodicValue; import com.psddev.dari.util.Profiler; import com.psddev.dari.util.Settings; import com.psddev.dari.util.SettingsException; import com.psddev.dari.util.Stats; import com.psddev.dari.util.StringUtils; import com.psddev.dari.util.TypeDefinition; /** Database backed by a SQL engine. */ public class SqlDatabase extends AbstractDatabase<Connection> { public static final String DATA_SOURCE_SETTING = "dataSource"; public static final String JDBC_DRIVER_CLASS_SETTING = "jdbcDriverClass"; public static final String JDBC_URL_SETTING = "jdbcUrl"; public static final String JDBC_USER_SETTING = "jdbcUser"; public static final String JDBC_PASSWORD_SETTING = "jdbcPassword"; public static final String JDBC_POOL_SIZE_SETTING = "jdbcPoolSize"; public static final String READ_DATA_SOURCE_SETTING = "readDataSource"; public static final String READ_JDBC_DRIVER_CLASS_SETTING = "readJdbcDriverClass"; public static final String READ_JDBC_URL_SETTING = "readJdbcUrl"; public static final String READ_JDBC_USER_SETTING = "readJdbcUser"; public static final String READ_JDBC_PASSWORD_SETTING = "readJdbcPassword"; public static final String READ_JDBC_POOL_SIZE_SETTING = "readJdbcPoolSize"; public static final String CATALOG_SUB_SETTING = "catalog"; public static final String METRIC_CATALOG_SUB_SETTING = "metricCatalog"; public static final String VENDOR_CLASS_SETTING = "vendorClass"; public static final String COMPRESS_DATA_SUB_SETTING = "compressData"; public static final String CACHE_DATA_SUB_SETTING = "cacheData"; public static final String RECORD_TABLE = "Record"; public static final String RECORD_UPDATE_TABLE = "RecordUpdate"; public static final String SYMBOL_TABLE = "Symbol"; public static final String ID_COLUMN = "id"; public static final String TYPE_ID_COLUMN = "typeId"; public static final String IN_ROW_INDEX_COLUMN = "inRowIndex"; public static final String DATA_COLUMN = "data"; public static final String SYMBOL_ID_COLUMN = "symbolId"; public static final String UPDATE_DATE_COLUMN = "updateDate"; public static final String VALUE_COLUMN = "value"; public static final String CONNECTION_QUERY_OPTION = "sql.connection"; public static final String EXTRA_COLUMNS_QUERY_OPTION = "sql.extraColumns"; public static final String EXTRA_JOINS_QUERY_OPTION = "sql.extraJoins"; public static final String EXTRA_WHERE_QUERY_OPTION = "sql.extraWhere"; public static final String EXTRA_HAVING_QUERY_OPTION = "sql.extraHaving"; public static final String MYSQL_INDEX_HINT_QUERY_OPTION = "sql.mysqlIndexHint"; public static final String RETURN_ORIGINAL_DATA_QUERY_OPTION = "sql.returnOriginalData"; public static final String USE_JDBC_FETCH_SIZE_QUERY_OPTION = "sql.useJdbcFetchSize"; public static final String USE_READ_DATA_SOURCE_QUERY_OPTION = "sql.useReadDataSource"; public static final String SKIP_INDEX_STATE_EXTRA = "sql.skipIndex"; public static final String INDEX_TABLE_INDEX_OPTION = "sql.indexTable"; public static final String EXTRA_COLUMN_EXTRA_PREFIX = "sql.extraColumn."; public static final String ORIGINAL_DATA_EXTRA = "sql.originalData"; public static final String SUB_DATA_COLUMN_ALIAS_PREFIX = "subData_"; private static final Logger LOGGER = LoggerFactory.getLogger(SqlDatabase.class); private static final String SHORT_NAME = "SQL"; private static final Stats STATS = new Stats(SHORT_NAME); private static final String CONNECTION_ERROR_STATS_OPERATION = "Connection Error"; private static final String QUERY_STATS_OPERATION = "Query"; private static final String UPDATE_STATS_OPERATION = "Update"; private static final String QUERY_PROFILER_EVENT = SHORT_NAME + " " + QUERY_STATS_OPERATION; private static final String UPDATE_PROFILER_EVENT = SHORT_NAME + " " + UPDATE_STATS_OPERATION; private static final long NOW_EXPIRATION_SECONDS = 300; private static final List<SqlDatabase> INSTANCES = new ArrayList<SqlDatabase>(); { INSTANCES.add(this); } private volatile DataSource dataSource; private volatile DataSource readDataSource; private volatile String catalog; private volatile String metricCatalog; private volatile transient String defaultCatalog; private volatile SqlVendor vendor; private volatile boolean compressData; private volatile boolean cacheData; /** * Quotes the given {@code identifier} so that it's safe to use * in a SQL query. */ public static String quoteIdentifier(String identifier) { return "\"" + StringUtils.replaceAll(identifier, "\\\\", "\\\\\\\\", "\"", "\"\"") + "\""; } /** * Quotes the given {@code value} so that it's safe to use * in a SQL query. */ public static String quoteValue(Object value) { if (value == null) { return "NULL"; } else if (value instanceof Number) { return value.toString(); } else if (value instanceof byte[]) { return "X'" + StringUtils.hex((byte[]) value) + "'"; } else { return "'" + value.toString().replace("'", "''").replace("\\", "\\\\") + "'"; } } /** Closes all resources used by all instances. */ public static void closeAll() { for (SqlDatabase database : INSTANCES) { database.close(); } INSTANCES.clear(); } /** * Creates an {@link SqlDatabaseException} that occurred during * an execution of a query. */ private SqlDatabaseException createQueryException( SQLException error, String sqlQuery, Query<?> query) { String message = error.getMessage(); if (error instanceof SQLTimeoutException || message.contains("timeout")) { return new SqlDatabaseException.ReadTimeout(this, error, sqlQuery, query); } else { return new SqlDatabaseException(this, error, sqlQuery, query); } } /** Returns the JDBC data source used for general database operations. */ public DataSource getDataSource() { return dataSource; } private static final Map<String, Class<? extends SqlVendor>> VENDOR_CLASSES; static { Map<String, Class<? extends SqlVendor>> m = new HashMap<String, Class<? extends SqlVendor>>(); m.put("H2", SqlVendor.H2.class); m.put("MySQL", SqlVendor.MySQL.class); m.put("PostgreSQL", SqlVendor.PostgreSQL.class); m.put("Oracle", SqlVendor.Oracle.class); VENDOR_CLASSES = m; } /** Sets the JDBC data source used for general database operations. */ public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; if (dataSource == null) { return; } synchronized (this) { try { boolean writable = false; if (vendor == null) { Connection connection; try { connection = openConnection(); writable = true; } catch (DatabaseException error) { LOGGER.debug("Can't read vendor information from the writable server!", error); connection = openReadConnection(); } try { defaultCatalog = connection.getCatalog(); DatabaseMetaData meta = connection.getMetaData(); String vendorName = meta.getDatabaseProductName(); Class<? extends SqlVendor> vendorClass = VENDOR_CLASSES.get(vendorName); LOGGER.info( "Initializing SQL vendor for [{}]: [{}] -> [{}]", new Object[] { getName(), vendorName, vendorClass }); vendor = vendorClass != null ? TypeDefinition.getInstance(vendorClass).newInstance() : new SqlVendor(); vendor.setDatabase(this); } finally { closeConnection(connection); } } tableColumnNames.refresh(); symbols.reset(); if (writable) { vendor.setUp(this); tableColumnNames.refresh(); symbols.reset(); } } catch (IOException error) { throw new IllegalStateException(error); } catch (SQLException error) { throw new SqlDatabaseException(this, "Can't check for required tables!", error); } } } /** Returns the JDBC data source used exclusively for read operations. */ public DataSource getReadDataSource() { return this.readDataSource; } /** Sets the JDBC data source used exclusively for read operations. */ public void setReadDataSource(DataSource readDataSource) { this.readDataSource = readDataSource; } public String getCatalog() { return catalog; } public void setCatalog(String catalog) { this.catalog = catalog; try { getVendor().setUp(this); tableColumnNames.refresh(); symbols.reset(); } catch (IOException error) { throw new IllegalStateException(error); } catch (SQLException error) { throw new SqlDatabaseException(this, "Can't check for required tables!", error); } } /** Returns the catalog that contains the Metric table. * * @return May be {@code null}. * **/ public String getMetricCatalog() { return metricCatalog; } public void setMetricCatalog(String metricCatalog) { if (ObjectUtils.isBlank(metricCatalog)) { this.metricCatalog = null; } else { StringBuilder str = new StringBuilder(); vendor.appendIdentifier(str, metricCatalog); str.append("."); vendor.appendIdentifier(str, MetricAccess.METRIC_TABLE); if (getVendor().checkTableExists(str.toString())) { this.metricCatalog = metricCatalog; } else { LOGGER.error("SqlDatabase#setMetricCatalog error: " + str.toString() + " does not exist or is not accessible. Falling back to default catalog."); this.metricCatalog = null; } } } /** Returns the vendor-specific SQL engine information. */ public SqlVendor getVendor() { return vendor; } /** Sets the vendor-specific SQL engine information. */ public void setVendor(SqlVendor vendor) { this.vendor = vendor; } /** Returns {@code true} if the data should be compressed. */ public boolean isCompressData() { return compressData; } /** Sets whether the data should be compressed. */ public void setCompressData(boolean compressData) { this.compressData = compressData; } public boolean isCacheData() { return cacheData; } public void setCacheData(boolean cacheData) { this.cacheData = cacheData; } /** * Returns {@code true} if the {@link #RECORD_TABLE} in this database * has the {@link #IN_ROW_INDEX_COLUMN}. */ public boolean hasInRowIndex() { return hasInRowIndex; } /** * Returns {@code true} if all comparisons executed in this database * should ignore case by default. */ public boolean comparesIgnoreCase() { return comparesIgnoreCase; } /** * Returns {@code true} if this database contains a table with * the given {@code name}. */ public boolean hasTable(String name) { if (name == null) { return false; } else { Set<String> names = tableColumnNames.get().keySet(); return names != null && names.contains(name.toLowerCase(Locale.ENGLISH)); } } /** * Returns {@code true} if the given {@code table} in this database * contains the given {@code column}. * * @param table If {@code null}, always returns {@code false}. * @param name If {@code null}, always returns {@code false}. */ public boolean hasColumn(String table, String column) { if (table == null || column == null) { return false; } else { Set<String> columnNames = tableColumnNames.get().get(table.toLowerCase(Locale.ENGLISH)); return columnNames != null && columnNames.contains(column.toLowerCase(Locale.ENGLISH)); } } private transient volatile boolean hasInRowIndex; private transient volatile boolean comparesIgnoreCase; private final transient PeriodicValue<Map<String, Set<String>>> tableColumnNames = new PeriodicValue<Map<String, Set<String>>>(0.0, 60.0) { @Override protected Map<String, Set<String>> update() { if (getDataSource() == null) { return Collections.emptyMap(); } Connection connection; try { connection = openConnection(); } catch (DatabaseException error) { LOGGER.debug("Can't read table names from the writable server!", error); connection = openReadConnection(); } try { SqlVendor vendor = getVendor(); String recordTable = null; int maxStringVersion = 0; Map<String, Set<String>> loweredNames = new HashMap<String, Set<String>>(); for (String name : vendor.getTables(connection)) { String loweredName = name.toLowerCase(Locale.ENGLISH); Set<String> loweredColumnNames = new HashSet<String>(); for (String columnName : vendor.getColumns(connection, name)) { loweredColumnNames.add(columnName.toLowerCase(Locale.ENGLISH)); } loweredNames.put(loweredName, loweredColumnNames); if ("record".equals(loweredName)) { recordTable = name; } else if (loweredName.startsWith("recordstring")) { int version = ObjectUtils.to(int.class, loweredName.substring(12)); if (version > maxStringVersion) { maxStringVersion = version; } } } if (recordTable != null) { hasInRowIndex = vendor.hasInRowIndex(connection, recordTable); } comparesIgnoreCase = maxStringVersion >= 3; return loweredNames; } catch (SQLException error) { LOGGER.error("Can't query table names!", error); return get(); } finally { closeConnection(connection); } } }; /** * Returns an unique numeric ID for the given {@code symbol}. */ public int getSymbolId(String symbol) { Integer id = symbols.get().get(symbol); if (id == null) { SqlVendor vendor = getVendor(); Connection connection = openConnection(); try { List<Object> parameters = new ArrayList<Object>(); StringBuilder insertBuilder = new StringBuilder(); insertBuilder.append("INSERT /*! IGNORE */ INTO "); vendor.appendIdentifier(insertBuilder, SYMBOL_TABLE); insertBuilder.append(" ("); vendor.appendIdentifier(insertBuilder, VALUE_COLUMN); insertBuilder.append(") VALUES ("); vendor.appendBindValue(insertBuilder, symbol, parameters); insertBuilder.append(')'); String insertSql = insertBuilder.toString(); try { Static.executeUpdateWithList(connection, insertSql, parameters); } catch (SQLException ex) { if (!Static.isIntegrityConstraintViolation(ex)) { throw createQueryException(ex, insertSql, null); } } StringBuilder selectBuilder = new StringBuilder(); selectBuilder.append("SELECT "); vendor.appendIdentifier(selectBuilder, SYMBOL_ID_COLUMN); selectBuilder.append(" FROM "); vendor.appendIdentifier(selectBuilder, SYMBOL_TABLE); selectBuilder.append(" WHERE "); vendor.appendIdentifier(selectBuilder, VALUE_COLUMN); selectBuilder.append('='); vendor.appendValue(selectBuilder, symbol); String selectSql = selectBuilder.toString(); Statement statement = null; ResultSet result = null; try { statement = connection.createStatement(); result = statement.executeQuery(selectSql); result.next(); id = result.getInt(1); symbols.get().put(symbol, id); } catch (SQLException ex) { throw createQueryException(ex, selectSql, null); } finally { closeResources(null, null, statement, result); } } finally { closeConnection(connection); } } return id; } private Supplier<Long> nowOffset = Suppliers.memoizeWithExpiration(new Supplier<Long>() { public Long get() { String selectSql = getVendor().getSelectTimestampMillisSql(); Connection connection; Statement statement = null; ResultSet result = null; Long nowOffsetMillis = 0L; try { connection = openConnection(); } catch (DatabaseException error) { LOGGER.debug("Can't read timestamp from the writable server!", error); connection = openReadConnection(); } try { statement = connection.createStatement(); result = statement.executeQuery(selectSql); if (result.next()) { nowOffsetMillis = System.currentTimeMillis() - result.getLong(1); } } catch (SQLException ex) { throw createQueryException(ex, selectSql, null); } finally { closeResources(null, connection, statement, result); } return nowOffsetMillis; } }, NOW_EXPIRATION_SECONDS, TimeUnit.SECONDS); public long now() { return System.currentTimeMillis() - nowOffset.get(); } // Cache of all internal symbols. private final transient Lazy<Map<String, Integer>> symbols = new Lazy<Map<String, Integer>>() { @Override protected Map<String, Integer> create() { SqlVendor vendor = getVendor(); StringBuilder selectBuilder = new StringBuilder(); selectBuilder.append("SELECT "); vendor.appendIdentifier(selectBuilder, SYMBOL_ID_COLUMN); selectBuilder.append(','); vendor.appendIdentifier(selectBuilder, VALUE_COLUMN); selectBuilder.append(" FROM "); vendor.appendIdentifier(selectBuilder, SYMBOL_TABLE); String selectSql = selectBuilder.toString(); Connection connection; Statement statement = null; ResultSet result = null; try { connection = openConnection(); } catch (DatabaseException error) { LOGGER.debug("Can't read symbols from the writable server!", error); connection = openReadConnection(); } try { statement = connection.createStatement(); result = statement.executeQuery(selectSql); Map<String, Integer> symbols = new ConcurrentHashMap<String, Integer>(); while (result.next()) { symbols.put(new String(result.getBytes(2), StringUtils.UTF_8), result.getInt(1)); } return symbols; } catch (SQLException ex) { throw createQueryException(ex, selectSql, null); } finally { closeResources(null, connection, statement, result); } } }; /** * Returns the underlying JDBC connection. * * @deprecated Use {@link #openConnection} instead. */ @Deprecated public Connection getConnection() { return openConnection(); } /** Closes any resources used by this database. */ public void close() { DataSource dataSource = getDataSource(); if (dataSource instanceof BoneCPDataSource) { LOGGER.info("Closing BoneCP data source in {}", getName()); ((BoneCPDataSource) dataSource).close(); } DataSource readDataSource = getReadDataSource(); if (readDataSource instanceof BoneCPDataSource) { LOGGER.info("Closing BoneCP read data source in {}", getName()); ((BoneCPDataSource) readDataSource).close(); } setDataSource(null); setReadDataSource(null); } /** * Builds an SQL statement that can be used to get a count of all * objects matching the given {@code query}. */ public String buildCountStatement(Query<?> query) { return new SqlQuery(this, query).countStatement(); } /** * Builds an SQL statement that can be used to delete all rows * matching the given {@code query}. */ public String buildDeleteStatement(Query<?> query) { return new SqlQuery(this, query).deleteStatement(); } /** * Builds an SQL statement that can be used to get all objects * grouped by the values of the given {@code groupFields}. */ public String buildGroupStatement(Query<?> query, String... groupFields) { return new SqlQuery(this, query).groupStatement(groupFields); } public String buildGroupedMetricStatement(Query<?> query, String metricFieldName, String... groupFields) { return new SqlQuery(this, query).groupedMetricSql(metricFieldName, groupFields); } /** * Builds an SQL statement that can be used to get when the objects * matching the given {@code query} were last updated. */ public String buildLastUpdateStatement(Query<?> query) { return new SqlQuery(this, query).lastUpdateStatement(); } /** * Builds an SQL statement that can be used to list all rows * matching the given {@code query}. */ public String buildSelectStatement(Query<?> query) { return new SqlQuery(this, query).selectStatement(); } // Closes all the given SQL resources safely. protected void closeResources(Query<?> query, Connection connection, Statement statement, ResultSet result) { if (result != null) { try { result.close(); } catch (SQLException error) { // Not likely and probably harmless. } } if (statement != null) { try { statement.close(); } catch (SQLException error) { // Not likely and probably harmless. } } Object queryConnection; if (connection != null && (query == null || (queryConnection = query.getOptions().get(CONNECTION_QUERY_OPTION)) == null || !connection.equals(queryConnection))) { try { if (!connection.isClosed()) { connection.close(); } } catch (SQLException ex) { // Not likely and probably harmless. } } } private byte[] serializeState(State state) { Map<String, Object> values = state.getSimpleValues(); for (Iterator<Map.Entry<String, Object>> i = values.entrySet().iterator(); i.hasNext(); ) { Map.Entry<String, Object> entry = i.next(); ObjectField field = state.getField(entry.getKey()); if (field != null) { if (field.as(FieldData.class).isIndexTableSourceFromAnywhere()) { i.remove(); } } } byte[] dataBytes = ObjectUtils.toJson(values).getBytes(StringUtils.UTF_8); if (isCompressData()) { byte[] compressed = new byte[Snappy.maxCompressedLength(dataBytes.length)]; int compressedLength = Snappy.compress(dataBytes, 0, dataBytes.length, compressed, 0); dataBytes = new byte[compressedLength + 1]; dataBytes[0] = 's'; System.arraycopy(compressed, 0, dataBytes, 1, compressedLength); } return dataBytes; } @SuppressWarnings("unchecked") private Map<String, Object> unserializeData(byte[] dataBytes) { char format = '\0'; while (true) { format = (char) dataBytes[0]; if (format == 's') { dataBytes = Snappy.uncompress(dataBytes, 1, dataBytes.length - 1); } else if (format == '{') { return (Map<String, Object>) ObjectUtils.fromJson(dataBytes); } else { break; } } throw new IllegalStateException(String.format( "Unknown format! ([%s])", format)); } private final transient Cache<String, byte[]> dataCache = CacheBuilder.newBuilder().maximumSize(10000).build(); private class ConnectionRef { private Connection connection; public Connection getOrOpen(Query<?> query) { if (connection == null) { connection = SqlDatabase.super.openQueryConnection(query); } return connection; } public void close() { if (connection != null) { try { if (!connection.isClosed()) { connection.close(); } } catch (SQLException error) { // Not likely and probably harmless. } } } } // Creates a previously saved object using the given resultSet. private <T> T createSavedObjectWithResultSet( ResultSet resultSet, Query<T> query, ConnectionRef extraConnectionRef) throws SQLException { T object = createSavedObject(resultSet.getObject(2), resultSet.getObject(1), query); State objectState = State.getInstance(object); if (!objectState.isReferenceOnly()) { byte[] data = null; if (isCacheData()) { UUID id = objectState.getId(); String key = id + "/" + resultSet.getDouble(3); data = dataCache.getIfPresent(key); if (data == null) { SqlVendor vendor = getVendor(); StringBuilder sqlQuery = new StringBuilder(); sqlQuery.append("SELECT r."); vendor.appendIdentifier(sqlQuery, "data"); sqlQuery.append(", ru."); vendor.appendIdentifier(sqlQuery, "updateDate"); sqlQuery.append(" FROM "); vendor.appendIdentifier(sqlQuery, "Record"); sqlQuery.append(" AS r LEFT OUTER JOIN "); vendor.appendIdentifier(sqlQuery, "RecordUpdate"); sqlQuery.append(" AS ru ON r."); vendor.appendIdentifier(sqlQuery, "id"); sqlQuery.append(" = ru."); vendor.appendIdentifier(sqlQuery, "id"); sqlQuery.append(" WHERE r."); vendor.appendIdentifier(sqlQuery, "id"); sqlQuery.append(" = "); vendor.appendUuid(sqlQuery, id); Connection connection = null; Statement statement = null; ResultSet result = null; try { connection = extraConnectionRef.getOrOpen(query); statement = connection.createStatement(); result = executeQueryBeforeTimeout(statement, sqlQuery.toString(), 0); if (result.next()) { data = result.getBytes(1); dataCache.put(id + "/" + result.getDouble(2), data); } } catch (SQLException error) { throw createQueryException(error, sqlQuery.toString(), query); } finally { closeResources(null, null, statement, result); } } } else { data = resultSet.getBytes(3); } if (data != null) { objectState.setValues(unserializeData(data)); Boolean returnOriginal = ObjectUtils.to(Boolean.class, query.getOptions().get(RETURN_ORIGINAL_DATA_QUERY_OPTION)); if (returnOriginal == null) { returnOriginal = Boolean.FALSE; } if (returnOriginal) { objectState.getExtras().put(ORIGINAL_DATA_EXTRA, data); } } } ResultSetMetaData meta = resultSet.getMetaData(); Object subId = null, subTypeId = null; byte[] subData; for (int i = 4, count = meta.getColumnCount(); i <= count; ++ i) { String columnName = meta.getColumnLabel(i); if (columnName.startsWith(SUB_DATA_COLUMN_ALIAS_PREFIX)) { if (columnName.endsWith("_"+ID_COLUMN)) { subId = resultSet.getObject(i); } else if (columnName.endsWith("_"+TYPE_ID_COLUMN)) { subTypeId = resultSet.getObject(i); } else if (columnName.endsWith("_"+DATA_COLUMN)) { subData = resultSet.getBytes(i); if (subId != null && subTypeId != null && subData != null && ! subId.equals(objectState.getId())) { Object subObject = createSavedObject(subTypeId, subId, query); State subObjectState = State.getInstance(subObject); subObjectState.setValues(unserializeData(subData)); subId = null; subTypeId = null; subData = null; objectState.getExtras().put(State.SUB_DATA_STATE_EXTRA_PREFIX + subObjectState.getId(), subObject); } } } else if (query.getExtraSourceColumns().containsKey(columnName)) { objectState.put(query.getExtraSourceColumns().get(columnName), resultSet.getObject(i)); } else { objectState.getExtras().put(EXTRA_COLUMN_EXTRA_PREFIX + meta.getColumnLabel(i), resultSet.getObject(i)); } } // Load some extra column from source index tables. @SuppressWarnings("unchecked") Set<UUID> unresolvedTypeIds = (Set<UUID>) query.getOptions().get(State.UNRESOLVED_TYPE_IDS_QUERY_OPTION); Set<ObjectType> queryTypes = query.getConcreteTypes(getEnvironment()); ObjectType type = objectState.getType(); HashSet<ObjectField> loadExtraFields = new HashSet<ObjectField>(); if (type != null) { if ((unresolvedTypeIds == null || !unresolvedTypeIds.contains(type.getId())) && !queryTypes.contains(type)) { for (ObjectField field : type.getFields()) { SqlDatabase.FieldData fieldData = field.as(SqlDatabase.FieldData.class); if (fieldData.isIndexTableSource() && !field.isMetric()) { loadExtraFields.add(field); } } } } if (!loadExtraFields.isEmpty()) { Connection connection = extraConnectionRef.getOrOpen(query); for (ObjectField field : loadExtraFields) { Statement extraStatement = null; ResultSet extraResult = null; try { extraStatement = connection.createStatement(); extraResult = executeQueryBeforeTimeout( extraStatement, extraSourceSelectStatementById(field, objectState.getId(), objectState.getTypeId()), getQueryReadTimeout(query)); if (extraResult.next()) { meta = extraResult.getMetaData(); for (int i = 1, count = meta.getColumnCount(); i <= count; ++ i) { objectState.put(meta.getColumnLabel(i), extraResult.getObject(i)); } } } finally { closeResources(null, null, extraStatement, extraResult); } } } return swapObjectType(query, object); } // Creates an SQL statement to return a single row from a FieldIndexTable // used as a source table. // Maybe: move this to SqlQuery and use initializeClauses() and // needsRecordTable=false instead of passing id to this method. Needs // countperformance branch to do this. private String extraSourceSelectStatementById(ObjectField field, UUID id, UUID typeId) { FieldData fieldData = field.as(FieldData.class); ObjectType parentType = field.getParentType(); StringBuilder keyName = new StringBuilder(parentType.getInternalName()); keyName.append('/'); keyName.append(field.getInternalName()); Query<?> query = Query.fromType(parentType); Query.MappedKey key = query.mapEmbeddedKey(getEnvironment(), keyName.toString()); ObjectIndex useIndex = null; for (ObjectIndex index : key.getIndexes()) { if (field.getInternalName().equals(index.getFields().get(0))) { useIndex = index; break; } } SqlIndex useSqlIndex = SqlIndex.Static.getByIndex(useIndex); SqlIndex.Table indexTable = useSqlIndex.getReadTable(this, useIndex); String sourceTableName = fieldData.getIndexTable(); int symbolId = getSymbolId(key.getIndexKey(useIndex)); StringBuilder sql = new StringBuilder(); int fieldIndex = 0; sql.append("SELECT "); for (String indexFieldName : useIndex.getFields()) { String indexColumnName = indexTable.getValueField(this, useIndex, fieldIndex); ++ fieldIndex; vendor.appendIdentifier(sql, indexColumnName); sql.append(" AS "); vendor.appendIdentifier(sql, indexFieldName); sql.append(", "); } sql.setLength(sql.length() - 2); sql.append(" FROM "); vendor.appendIdentifier(sql, sourceTableName); sql.append(" WHERE "); vendor.appendIdentifier(sql, "id"); sql.append(" = "); vendor.appendValue(sql, id); sql.append(" AND "); vendor.appendIdentifier(sql, "symbolId"); sql.append(" = "); sql.append(symbolId); return sql.toString(); } /** * Executes the given read {@code statement} (created from the given * {@code sqlQuery}) before the given {@code timeout} (in seconds). */ ResultSet executeQueryBeforeTimeout( Statement statement, String sqlQuery, int timeout) throws SQLException { if (timeout > 0 && !(vendor instanceof SqlVendor.PostgreSQL)) { statement.setQueryTimeout(timeout); } Stats.Timer timer = STATS.startTimer(); Profiler.Static.startThreadEvent(QUERY_PROFILER_EVENT); try { return statement.executeQuery(sqlQuery); } finally { double duration = timer.stop(QUERY_STATS_OPERATION); Profiler.Static.stopThreadEvent(sqlQuery); LOGGER.debug( "Read from the SQL database using [{}] in [{}]ms", sqlQuery, duration * 1000.0); } } /** * Selects the first object that matches the given {@code sqlQuery} * with options from the given {@code query}. */ public <T> T selectFirstWithOptions(String sqlQuery, Query<T> query) { sqlQuery = vendor.rewriteQueryWithLimitClause(sqlQuery, 1, 0); ConnectionRef extraConnectionRef = new ConnectionRef(); Connection connection = null; Statement statement = null; ResultSet result = null; try { connection = openQueryConnection(query); statement = connection.createStatement(); result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query)); return result.next() ? createSavedObjectWithResultSet(result, query, extraConnectionRef) : null; } catch (SQLException ex) { throw createQueryException(ex, sqlQuery, query); } finally { closeResources(query, connection, statement, result); extraConnectionRef.close(); } } /** * Selects the first object that matches the given {@code sqlQuery} * without a timeout. */ public Object selectFirst(String sqlQuery) { return selectFirstWithOptions(sqlQuery, null); } /** * Selects a list of objects that match the given {@code sqlQuery} * with options from the given {@code query}. */ public <T> List<T> selectListWithOptions(String sqlQuery, Query<T> query) { ConnectionRef extraConnectionRef = new ConnectionRef(); Connection connection = null; Statement statement = null; ResultSet result = null; List<T> objects = new ArrayList<T>(); int timeout = getQueryReadTimeout(query); try { connection = openQueryConnection(query); statement = connection.createStatement(); result = executeQueryBeforeTimeout(statement, sqlQuery, timeout); while (result.next()) { objects.add(createSavedObjectWithResultSet(result, query, extraConnectionRef)); } return objects; } catch (SQLException ex) { throw createQueryException(ex, sqlQuery, query); } finally { closeResources(query, connection, statement, result); extraConnectionRef.close(); } } /** * Selects a list of objects that match the given {@code sqlQuery} * without a timeout. */ public List<Object> selectList(String sqlQuery) { return selectListWithOptions(sqlQuery, null); } /** * Returns an iterable that selects all objects matching the given * {@code sqlQuery} with options from the given {@code query}. */ public <T> Iterable<T> selectIterableWithOptions( final String sqlQuery, final int fetchSize, final Query<T> query) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new SqlIterator<T>(sqlQuery, fetchSize, query); } }; } private class SqlIterator<T> implements java.io.Closeable, Iterator<T> { private final String sqlQuery; private final Query<T> query; private final ConnectionRef extraConnectionRef; private final Connection connection; private final Statement statement; private final ResultSet result; private boolean hasNext = true; public SqlIterator(String initialSqlQuery, int fetchSize, Query<T> initialQuery) { sqlQuery = initialSqlQuery; query = initialQuery; extraConnectionRef = new ConnectionRef(); try { connection = openQueryConnection(query); statement = connection.createStatement(); statement.setFetchSize( getVendor() instanceof SqlVendor.MySQL ? Integer.MIN_VALUE : fetchSize <= 0 ? 200 : fetchSize); result = statement.executeQuery(sqlQuery); moveToNext(); } catch (SQLException ex) { close(); throw createQueryException(ex, sqlQuery, query); } } private void moveToNext() throws SQLException { if (hasNext) { hasNext = result.next(); if (!hasNext) { close(); } } } public void close() { hasNext = false; closeResources(query, connection, statement, result); extraConnectionRef.close(); } @Override public boolean hasNext() { return hasNext; } @Override public T next() { if (!hasNext) { throw new NoSuchElementException(); } try { T object = createSavedObjectWithResultSet(result, query, extraConnectionRef); moveToNext(); return object; } catch (SQLException ex) { close(); throw createQueryException(ex, sqlQuery, query); } } @Override public void remove() { throw new UnsupportedOperationException(); } @Override protected void finalize() { close(); } } /** * Fills the placeholders in the given {@code sqlQuery} with the given * {@code parameters}. */ private static String fillPlaceholders(String sqlQuery, Object... parameters) { StringBuilder filled = new StringBuilder(); int prevPh = 0; for (int ph, index = 0; (ph = sqlQuery.indexOf('?', prevPh)) > -1; ++ index) { filled.append(sqlQuery.substring(prevPh, ph)); prevPh = ph + 1; filled.append(quoteValue(parameters[index])); } filled.append(sqlQuery.substring(prevPh)); return filled.toString(); } /** * Executes the given write {@code sqlQuery} with the given * {@code parameters}. * * @deprecated Use {@link Static#executeUpdate} instead. */ @Deprecated public int executeUpdate(String sqlQuery, Object... parameters) { try { return Static.executeUpdateWithArray(getConnection(), sqlQuery, parameters); } catch (SQLException ex) { throw createQueryException(ex, fillPlaceholders(sqlQuery, parameters), null); } } /** * Reads the given {@code resultSet} into a list of maps * and closes it. */ public List<Map<String, Object>> readResultSet(ResultSet resultSet) throws SQLException { try { ResultSetMetaData meta = resultSet.getMetaData(); List<String> columnNames = new ArrayList<String>(); for (int i = 1, count = meta.getColumnCount(); i < count; ++ i) { columnNames.add(meta.getColumnName(i)); } List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>(); while (resultSet.next()) { Map<String, Object> map = new LinkedHashMap<String, Object>(); maps.add(map); for (int i = 0, size = columnNames.size(); i < size; ++ i) { map.put(columnNames.get(i), resultSet.getObject(i + 1)); } } return maps; } finally { resultSet.close(); } } @Override public Connection openConnection() { DataSource dataSource = getDataSource(); if (dataSource == null) { throw new SqlDatabaseException(this, "No SQL data source!"); } try { Connection connection = getConnectionFromDataSource(dataSource); connection.setReadOnly(false); if (vendor != null) { vendor.setTransactionIsolation(connection); } return connection; } catch (SQLException error) { throw new SqlDatabaseException(this, "Can't connect to the SQL engine!", error); } } private Connection getConnectionFromDataSource(DataSource dataSource) throws SQLException { int limit = Settings.getOrDefault(int.class, "dari/sqlConnectionRetryLimit", 5); while (true) { try { Connection connection = dataSource.getConnection(); String catalog = getCatalog(); if (catalog != null) { connection.setCatalog(catalog); } return connection; } catch (SQLException error) { if (error instanceof SQLRecoverableException) { -- limit; if (limit >= 0) { Stats.Timer timer = STATS.startTimer(); try { Thread.sleep(ObjectUtils.jitter(10L, 0.5)); } catch (InterruptedException ignore) { // Ignore and keep retrying. } finally { timer.stop(CONNECTION_ERROR_STATS_OPERATION); continue; } } } throw error; } } } @Override protected Connection doOpenReadConnection() { DataSource readDataSource = getReadDataSource(); if (readDataSource == null) { readDataSource = getDataSource(); } if (readDataSource == null) { throw new SqlDatabaseException(this, "No SQL data source!"); } try { Connection connection = getConnectionFromDataSource(readDataSource); connection.setReadOnly(true); return connection; } catch (SQLException error) { throw new SqlDatabaseException(this, "Can't connect to the SQL engine!", error); } } @Override public Connection openQueryConnection(Query<?> query) { if (query != null) { Connection connection = (Connection) query.getOptions().get(CONNECTION_QUERY_OPTION); if (connection != null) { return connection; } Boolean useRead = ObjectUtils.to(Boolean.class, query.getOptions().get(USE_READ_DATA_SOURCE_QUERY_OPTION)); if (useRead == null) { useRead = Boolean.TRUE; } if (!useRead) { return openConnection(); } } return super.openQueryConnection(query); } @Override public void closeConnection(Connection connection) { if (connection != null) { try { if (defaultCatalog != null) { String catalog = getCatalog(); if (catalog != null) { connection.setCatalog(defaultCatalog); } } if (!connection.isClosed()) { connection.close(); } } catch (SQLException error) { // Not likely and probably harmless. } } } @Override protected boolean isRecoverableError(Exception error) { if (error instanceof SQLException) { SQLException sqlError = (SQLException) error; return "40001".equals(sqlError.getSQLState()); } return false; } @Override protected void doInitialize(String settingsKey, Map<String, Object> settings) { close(); setReadDataSource(createDataSource( settings, READ_DATA_SOURCE_SETTING, READ_JDBC_DRIVER_CLASS_SETTING, READ_JDBC_URL_SETTING, READ_JDBC_USER_SETTING, READ_JDBC_PASSWORD_SETTING, READ_JDBC_POOL_SIZE_SETTING)); setDataSource(createDataSource( settings, DATA_SOURCE_SETTING, JDBC_DRIVER_CLASS_SETTING, JDBC_URL_SETTING, JDBC_USER_SETTING, JDBC_PASSWORD_SETTING, JDBC_POOL_SIZE_SETTING)); setCatalog(ObjectUtils.to(String.class, settings.get(CATALOG_SUB_SETTING))); setMetricCatalog(ObjectUtils.to(String.class, settings.get(METRIC_CATALOG_SUB_SETTING))); String vendorClassName = ObjectUtils.to(String.class, settings.get(VENDOR_CLASS_SETTING)); Class<?> vendorClass = null; if (vendorClassName != null) { vendorClass = ObjectUtils.getClassByName(vendorClassName); if (vendorClass == null) { throw new SettingsException( VENDOR_CLASS_SETTING, String.format("Can't find [%s]!", vendorClassName)); } else if (!SqlVendor.class.isAssignableFrom(vendorClass)) { throw new SettingsException( VENDOR_CLASS_SETTING, String.format("[%s] doesn't implement [%s]!", vendorClass, Driver.class)); } } if (vendorClass != null) { setVendor((SqlVendor) TypeDefinition.getInstance(vendorClass).newInstance()); } Boolean compressData = ObjectUtils.firstNonNull( ObjectUtils.to(Boolean.class, settings.get(COMPRESS_DATA_SUB_SETTING)), Settings.get(Boolean.class, "dari/isCompressSqlData")); if (compressData != null) { setCompressData(compressData); } setCacheData(ObjectUtils.to(boolean.class, settings.get(CACHE_DATA_SUB_SETTING))); } private static final Map<String, String> DRIVER_CLASS_NAMES; static { Map<String, String> m = new HashMap<String, String>(); m.put("h2", "org.h2.Driver"); m.put("jtds", "net.sourceforge.jtds.jdbc.Driver"); m.put("mysql", "com.mysql.jdbc.Driver"); m.put("postgresql", "org.postgresql.Driver"); DRIVER_CLASS_NAMES = m; } private static final Set<WeakReference<Driver>> REGISTERED_DRIVERS = new HashSet<WeakReference<Driver>>(); private DataSource createDataSource( Map<String, Object> settings, String dataSourceSetting, String jdbcDriverClassSetting, String jdbcUrlSetting, String jdbcUserSetting, String jdbcPasswordSetting, String jdbcPoolSizeSetting) { Object dataSourceObject = settings.get(dataSourceSetting); if (dataSourceObject instanceof DataSource) { return (DataSource) dataSourceObject; } else { String url = ObjectUtils.to(String.class, settings.get(jdbcUrlSetting)); if (ObjectUtils.isBlank(url)) { return null; } else { String driverClassName = ObjectUtils.to(String.class, settings.get(jdbcDriverClassSetting)); Class<?> driverClass = null; if (driverClassName != null) { driverClass = ObjectUtils.getClassByName(driverClassName); if (driverClass == null) { throw new SettingsException( jdbcDriverClassSetting, String.format("Can't find [%s]!", driverClassName)); } else if (!Driver.class.isAssignableFrom(driverClass)) { throw new SettingsException( jdbcDriverClassSetting, String.format("[%s] doesn't implement [%s]!", driverClass, Driver.class)); } } else { int firstColonAt = url.indexOf(':'); if (firstColonAt > -1) { ++ firstColonAt; int secondColonAt = url.indexOf(':', firstColonAt); if (secondColonAt > -1) { driverClass = ObjectUtils.getClassByName(DRIVER_CLASS_NAMES.get(url.substring(firstColonAt, secondColonAt))); } } } if (driverClass != null) { Driver driver = null; for (Enumeration<Driver> e = DriverManager.getDrivers(); e.hasMoreElements(); ) { Driver d = e.nextElement(); if (driverClass.isInstance(d)) { driver = d; break; } } if (driver == null) { driver = (Driver) TypeDefinition.getInstance(driverClass).newInstance(); try { LOGGER.info("Registering [{}]", driver); DriverManager.registerDriver(driver); } catch (SQLException ex) { LOGGER.warn("Can't register [{}]!", driver); } } if (driver != null) { REGISTERED_DRIVERS.add(new WeakReference<Driver>(driver)); } } String user = ObjectUtils.to(String.class, settings.get(jdbcUserSetting)); String password = ObjectUtils.to(String.class, settings.get(jdbcPasswordSetting)); Integer poolSize = ObjectUtils.to(Integer.class, settings.get(jdbcPoolSizeSetting)); if (poolSize == null || poolSize <= 0) { poolSize = 24; } int partitionCount = 3; int connectionsPerPartition = poolSize / partitionCount; LOGGER.info("Automatically creating BoneCP data source:" + "\n\turl={}" + "\n\tusername={}" + "\n\tpoolSize={}" + "\n\tconnectionsPerPartition={}" + "\n\tpartitionCount={}", new Object[] { url, user, poolSize, connectionsPerPartition, partitionCount }); BoneCPDataSource bone = new BoneCPDataSource(); bone.setJdbcUrl(url); bone.setUsername(user); bone.setPassword(password); bone.setMinConnectionsPerPartition(connectionsPerPartition); bone.setMaxConnectionsPerPartition(connectionsPerPartition); bone.setPartitionCount(partitionCount); bone.setConnectionTimeoutInMs(5000L); return bone; } } } /** Returns the read timeout associated with the given {@code query}. */ private int getQueryReadTimeout(Query<?> query) { if (query != null) { Double timeout = query.getTimeout(); if (timeout == null) { timeout = getReadTimeout(); } if (timeout > 0.0) { return (int) Math.round(timeout); } } return 0; } @Override public <T> List<T> readAll(Query<T> query) { return selectListWithOptions(buildSelectStatement(query), query); } @Override public long readCount(Query<?> query) { String sqlQuery = buildCountStatement(query); Connection connection = null; Statement statement = null; ResultSet result = null; try { connection = openQueryConnection(query); statement = connection.createStatement(); result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query)); if (result.next()) { Object countObj = result.getObject(1); if (countObj instanceof Number) { return ((Number) countObj).longValue(); } } return 0; } catch (SQLException ex) { throw createQueryException(ex, sqlQuery, query); } finally { closeResources(query, connection, statement, result); } } @Override public <T> T readFirst(Query<T> query) { if (query.getSorters().isEmpty()) { Predicate predicate = query.getPredicate(); if (predicate instanceof CompoundPredicate) { CompoundPredicate compoundPredicate = (CompoundPredicate) predicate; if (PredicateParser.OR_OPERATOR.equals(compoundPredicate.getOperator())) { for (Predicate child : compoundPredicate.getChildren()) { Query<T> childQuery = query.clone(); childQuery.setPredicate(child); T first = readFirst(childQuery); if (first != null) { return first; } } return null; } } } return selectFirstWithOptions(buildSelectStatement(query), query); } @Override public <T> Iterable<T> readIterable(Query<T> query, int fetchSize) { Boolean useJdbc = ObjectUtils.to(Boolean.class, query.getOptions().get(USE_JDBC_FETCH_SIZE_QUERY_OPTION)); if (useJdbc == null) { useJdbc = Boolean.TRUE; } if (useJdbc) { return selectIterableWithOptions(buildSelectStatement(query), fetchSize, query); } else { return new ByIdIterable<T>(query, fetchSize); } } private static class ByIdIterable<T> implements Iterable<T> { private final Query<T> query; private final int fetchSize; public ByIdIterable(Query<T> query, int fetchSize) { this.query = query; this.fetchSize = fetchSize; } @Override public Iterator<T> iterator() { return new ByIdIterator<T>(query, fetchSize); } } private static class ByIdIterator<T> implements Iterator<T> { private final Query<T> query; private final int fetchSize; private UUID lastTypeId; private UUID lastId; private List<T> items; private int index; public ByIdIterator(Query<T> query, int fetchSize) { if (!query.getSorters().isEmpty()) { throw new IllegalArgumentException("Can't iterate over a query that has sorters!"); } this.query = query.clone().timeout(0.0).sortAscending("_type").sortAscending("_id"); this.fetchSize = fetchSize > 0 ? fetchSize : 200; } @Override public boolean hasNext() { if (items != null && items.isEmpty()) { return false; } if (items == null || index >= items.size()) { Query<T> nextQuery = query.clone(); if (lastTypeId != null) { nextQuery.and("_type = ? and _id > ?", lastTypeId, lastId); } items = nextQuery.select(0, fetchSize).getItems(); int size = items.size(); if (size < 1) { if (lastTypeId == null) { return false; } else { nextQuery = query.clone().and("_type > ?", lastTypeId); items = nextQuery.select(0, fetchSize).getItems(); size = items.size(); if (size < 1) { return false; } } } State lastState = State.getInstance(items.get(size - 1)); lastTypeId = lastState.getTypeId(); lastId = lastState.getId(); index = 0; } return true; } @Override public T next() { if (hasNext()) { T object = items.get(index); ++ index; return object; } else { throw new NoSuchElementException(); } } @Override public void remove() { throw new UnsupportedOperationException(); } } @Override public Date readLastUpdate(Query<?> query) { String sqlQuery = buildLastUpdateStatement(query); Connection connection = null; Statement statement = null; ResultSet result = null; try { connection = openQueryConnection(query); statement = connection.createStatement(); result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query)); if (result.next()) { Double date = ObjectUtils.to(Double.class, result.getObject(1)); if (date != null) { return new Date((long) (date * 1000L)); } } return null; } catch (SQLException ex) { throw createQueryException(ex, sqlQuery, query); } finally { closeResources(query, connection, statement, result); } } @Override public <T> PaginatedResult<T> readPartial(final Query<T> query, long offset, int limit) { List<T> objects = selectListWithOptions( vendor.rewriteQueryWithLimitClause(buildSelectStatement(query), limit + 1, offset), query); int size = objects.size(); if (size <= limit) { return new PaginatedResult<T>(offset, limit, offset + size, objects); } else { objects.remove(size - 1); return new PaginatedResult<T>(offset, limit, 0, objects) { private Long count; @Override public long getCount() { if (count == null) { count = readCount(query); } return count; } @Override public boolean hasNext() { return true; } }; } } @Override public <T> PaginatedResult<Grouping<T>> readPartialGrouped(Query<T> query, long offset, int limit, String... fields) { List<Grouping<T>> groupings = new ArrayList<Grouping<T>>(); String sqlQuery = buildGroupStatement(query, fields); Connection connection = null; Statement statement = null; ResultSet result = null; try { connection = openQueryConnection(query); statement = connection.createStatement(); result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query)); int fieldsLength = fields.length; int groupingsCount = 0; for (int i = 0, last = (int) offset + limit; result.next(); ++ i, ++ groupingsCount) { if (i < offset || i >= last) { continue; } List<Object> keys = new ArrayList<Object>(); SqlGrouping<T> grouping; ResultSetMetaData meta = result.getMetaData(); String aggregateColumnName = meta.getColumnName(1); if ("_count".equals(aggregateColumnName)) { long count = ObjectUtils.to(long.class, result.getObject(1)); for (int j = 0; j < fieldsLength; ++ j) { keys.add(result.getObject(j + 2)); } grouping = new SqlGrouping<T>(keys, query, fields, count, groupings); } else { Double amount = ObjectUtils.to(Double.class, result.getObject(1)); for (int j = 0; j < fieldsLength; ++ j) { keys.add(result.getObject(j + 3)); } long count = 0L; if (meta.getColumnName(2).equals("_count")) { count = ObjectUtils.to(long.class, result.getObject(2)); } grouping = new SqlGrouping<T>(keys, query, fields, count, groupings); if (amount == null) { amount = 0d; } grouping.setSum(aggregateColumnName, amount); } groupings.add(grouping); } int groupingsSize = groupings.size(); List<Integer> removes = new ArrayList<Integer>(); for (int i = 0; i < fieldsLength; ++ i) { Query.MappedKey key = query.mapEmbeddedKey(getEnvironment(), fields[i]); ObjectField field = key.getSubQueryKeyField(); if (field == null) { field = key.getField(); } if (field != null) { Map<String, Object> rawKeys = new HashMap<String, Object>(); for (int j = 0; j < groupingsSize; ++ j) { rawKeys.put(String.valueOf(j), groupings.get(j).getKeys().get(i)); } String itemType = field.getInternalItemType(); if (ObjectField.RECORD_TYPE.equals(itemType)) { for (Map.Entry<String, Object> entry : rawKeys.entrySet()) { Map<String, Object> ref = new HashMap<String, Object>(); ref.put(StateValueUtils.REFERENCE_KEY, entry.getValue()); entry.setValue(ref); } } Map<String, Object> rawKeysCopy = new HashMap<String, Object>(rawKeys); Map<?, ?> convertedKeys = (Map<?, ?>) StateValueUtils.toJavaValue(query.getDatabase(), null, field, "map/" + itemType, rawKeys); for (int j = 0; j < groupingsSize; ++ j) { String jString = String.valueOf(j); Object convertedKey = convertedKeys.get(jString); if (convertedKey == null && rawKeysCopy.get(jString) != null) { removes.add(j - removes.size()); } groupings.get(j).getKeys().set(i, convertedKey); } } } for (Integer i : removes) { groupings.remove((int) i); } return new PaginatedResult<Grouping<T>>(offset, limit, groupingsCount - removes.size(), groupings); } catch (SQLException ex) { throw createQueryException(ex, sqlQuery, query); } finally { closeResources(query, connection, statement, result); } } /** SQL-specific implementation of {@link Grouping}. */ private class SqlGrouping<T> extends AbstractGrouping<T> { private final long count; private final Map<String, Double> metricSums = new HashMap<String, Double>(); private final List<Grouping<T>> groupings; public SqlGrouping(List<Object> keys, Query<T> query, String[] fields, long count, List<Grouping<T>> groupings) { super(keys, query, fields); this.count = count; this.groupings = groupings; } @Override public double getSum(String field) { Query.MappedKey mappedKey = this.query.mapEmbeddedKey(getEnvironment(), field); ObjectField sumField = mappedKey.getField(); if (sumField.isMetric()) { if (!metricSums.containsKey(field)) { String sqlQuery = buildGroupedMetricStatement(query, field, fields); Connection connection = null; Statement statement = null; ResultSet result = null; try { connection = openQueryConnection(query); statement = connection.createStatement(); result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query)); if (this.getKeys().size() == 0) { // Special case for .groupby() without any fields if (this.groupings.size() != 1) { throw new RuntimeException("There should only be one grouping when grouping by nothing. Something went wrong internally."); } if (result.next() && result.getBytes(1) != null) { this.setSum(field, result.getDouble(1)); } else { this.setSum(field, 0); } } else { // Find the ObjectFields for the specified fields List<ObjectField> objectFields = new ArrayList<ObjectField>(); for (String fieldName : fields) { objectFields.add(query.mapEmbeddedKey(getEnvironment(), fieldName).getField()); } // index the groupings by their keys Map<List<Object>, SqlGrouping<T>> groupingMap = new HashMap<List<Object>, SqlGrouping<T>>(); for (Grouping<T> grouping : groupings) { if (grouping instanceof SqlGrouping) { ((SqlGrouping<T>) grouping).setSum(field, 0); groupingMap.put(grouping.getKeys(), (SqlGrouping<T>) grouping); } } // Find the sums and set them on each grouping while (result.next()) { // TODO: limit/offset List<Object> keys = new ArrayList<Object>(); for (int j = 0; j < objectFields.size(); ++ j) { keys.add(StateValueUtils.toJavaValue(query.getDatabase(), null, objectFields.get(j), objectFields.get(j).getInternalItemType(), result.getObject(j + 3))); // 3 because _count and amount } if (groupingMap.containsKey(keys)) { if (result.getBytes(1) != null) { groupingMap.get(keys).setSum(field, result.getDouble(1)); } else { groupingMap.get(keys).setSum(field, 0); } } } } } catch (SQLException ex) { throw createQueryException(ex, sqlQuery, query); } finally { closeResources(query, connection, statement, result); } } if (metricSums.containsKey(field)) { return metricSums.get(field); } else { return 0; } } else { // If it's not a MetricValue, we don't need to override it. return super.getSum(field); } } private void setSum(String field, double sum) { metricSums.put(field, sum); } @Override protected Aggregate createAggregate(String field) { throw new UnsupportedOperationException(); } @Override public long getCount() { return count; } } @Override protected void beginTransaction(Connection connection, boolean isImmediate) throws SQLException { connection.setAutoCommit(false); } @Override protected void commitTransaction(Connection connection, boolean isImmediate) throws SQLException { connection.commit(); } @Override protected void rollbackTransaction(Connection connection, boolean isImmediate) throws SQLException { connection.rollback(); } @Override protected void endTransaction(Connection connection, boolean isImmediate) throws SQLException { connection.setAutoCommit(true); } @Override protected void doSaves(Connection connection, boolean isImmediate, List<State> states) throws SQLException { List<State> indexStates = null; for (State state1 : states) { if (Boolean.TRUE.equals(state1.getExtra(SKIP_INDEX_STATE_EXTRA))) { indexStates = new ArrayList<State>(); for (State state2 : states) { if (!Boolean.TRUE.equals(state2.getExtra(SKIP_INDEX_STATE_EXTRA))) { indexStates.add(state2); } } break; } } if (indexStates == null) { indexStates = states; } SqlIndex.Static.deleteByStates(this, connection, indexStates); Map<State, String> inRowIndexes = SqlIndex.Static.insertByStates(this, connection, indexStates); boolean hasInRowIndex = hasInRowIndex(); SqlVendor vendor = getVendor(); double now = System.currentTimeMillis() / 1000.0; for (State state : states) { boolean isNew = state.isNew(); boolean saveInRowIndex = hasInRowIndex && !Boolean.TRUE.equals(state.getExtra(SKIP_INDEX_STATE_EXTRA)); UUID id = state.getId(); UUID typeId = state.getVisibilityAwareTypeId(); byte[] dataBytes = null; String inRowIndex = inRowIndexes.get(state); byte[] inRowIndexBytes = inRowIndex != null ? inRowIndex.getBytes(StringUtils.UTF_8) : new byte[0]; while (true) { if (isNew) { try { if (dataBytes == null) { dataBytes = serializeState(state); } List<Object> parameters = new ArrayList<Object>(); StringBuilder insertBuilder = new StringBuilder(); insertBuilder.append("INSERT INTO "); vendor.appendIdentifier(insertBuilder, RECORD_TABLE); insertBuilder.append(" ("); vendor.appendIdentifier(insertBuilder, ID_COLUMN); insertBuilder.append(','); vendor.appendIdentifier(insertBuilder, TYPE_ID_COLUMN); insertBuilder.append(','); vendor.appendIdentifier(insertBuilder, DATA_COLUMN); if (saveInRowIndex) { insertBuilder.append(','); vendor.appendIdentifier(insertBuilder, IN_ROW_INDEX_COLUMN); } insertBuilder.append(") VALUES ("); vendor.appendBindValue(insertBuilder, id, parameters); insertBuilder.append(','); vendor.appendBindValue(insertBuilder, typeId, parameters); insertBuilder.append(','); vendor.appendBindValue(insertBuilder, dataBytes, parameters); if (saveInRowIndex) { insertBuilder.append(','); vendor.appendBindValue(insertBuilder, inRowIndexBytes, parameters); } insertBuilder.append(')'); Static.executeUpdateWithList(connection, insertBuilder.toString(), parameters); } catch (SQLException ex) { if (Static.isIntegrityConstraintViolation(ex)) { isNew = false; continue; } else { throw ex; } } } else { List<AtomicOperation> atomicOperations = state.getAtomicOperations(); if (atomicOperations.isEmpty()) { if (dataBytes == null) { dataBytes = serializeState(state); } List<Object> parameters = new ArrayList<Object>(); StringBuilder updateBuilder = new StringBuilder(); updateBuilder.append("UPDATE "); vendor.appendIdentifier(updateBuilder, RECORD_TABLE); updateBuilder.append(" SET "); vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN); updateBuilder.append('='); vendor.appendBindValue(updateBuilder, typeId, parameters); updateBuilder.append(','); if (saveInRowIndex) { vendor.appendIdentifier(updateBuilder, IN_ROW_INDEX_COLUMN); updateBuilder.append('='); vendor.appendBindValue(updateBuilder, inRowIndexBytes, parameters); updateBuilder.append(','); } vendor.appendIdentifier(updateBuilder, DATA_COLUMN); updateBuilder.append('='); vendor.appendBindValue(updateBuilder, dataBytes, parameters); updateBuilder.append(" WHERE "); vendor.appendIdentifier(updateBuilder, ID_COLUMN); updateBuilder.append('='); vendor.appendBindValue(updateBuilder, id, parameters); if (Static.executeUpdateWithList(connection, updateBuilder.toString(), parameters) < 1) { isNew = true; continue; } } else { Object oldObject = Query. from(Object.class). where("_id = ?", id). using(this). option(CONNECTION_QUERY_OPTION, connection). option(RETURN_ORIGINAL_DATA_QUERY_OPTION, Boolean.TRUE). option(USE_READ_DATA_SOURCE_QUERY_OPTION, Boolean.FALSE). first(); if (oldObject == null) { retryWrites(); break; } State oldState = State.getInstance(oldObject); UUID oldTypeId = oldState.getVisibilityAwareTypeId(); byte[] oldData = Static.getOriginalData(oldObject); state.setValues(oldState.getValues()); for (AtomicOperation operation : atomicOperations) { String field = operation.getField(); state.put(field, oldState.get(field)); } for (AtomicOperation operation : atomicOperations) { operation.execute(state); } dataBytes = serializeState(state); List<Object> parameters = new ArrayList<Object>(); StringBuilder updateBuilder = new StringBuilder(); updateBuilder.append("UPDATE "); vendor.appendIdentifier(updateBuilder, RECORD_TABLE); updateBuilder.append(" SET "); vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN); updateBuilder.append('='); vendor.appendBindValue(updateBuilder, typeId, parameters); if (saveInRowIndex) { updateBuilder.append(','); vendor.appendIdentifier(updateBuilder, IN_ROW_INDEX_COLUMN); updateBuilder.append('='); vendor.appendBindValue(updateBuilder, inRowIndexBytes, parameters); } updateBuilder.append(','); vendor.appendIdentifier(updateBuilder, DATA_COLUMN); updateBuilder.append('='); vendor.appendBindValue(updateBuilder, dataBytes, parameters); updateBuilder.append(" WHERE "); vendor.appendIdentifier(updateBuilder, ID_COLUMN); updateBuilder.append('='); vendor.appendBindValue(updateBuilder, id, parameters); updateBuilder.append(" AND "); vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN); updateBuilder.append('='); vendor.appendBindValue(updateBuilder, oldTypeId, parameters); updateBuilder.append(" AND "); vendor.appendIdentifier(updateBuilder, DATA_COLUMN); updateBuilder.append('='); vendor.appendBindValue(updateBuilder, oldData, parameters); if (Static.executeUpdateWithList(connection, updateBuilder.toString(), parameters) < 1) { retryWrites(); break; } } } break; } while (true) { if (isNew) { List<Object> parameters = new ArrayList<Object>(); StringBuilder insertBuilder = new StringBuilder(); insertBuilder.append("INSERT INTO "); vendor.appendIdentifier(insertBuilder, RECORD_UPDATE_TABLE); insertBuilder.append(" ("); vendor.appendIdentifier(insertBuilder, ID_COLUMN); insertBuilder.append(','); vendor.appendIdentifier(insertBuilder, TYPE_ID_COLUMN); insertBuilder.append(','); vendor.appendIdentifier(insertBuilder, UPDATE_DATE_COLUMN); insertBuilder.append(") VALUES ("); vendor.appendBindValue(insertBuilder, id, parameters); insertBuilder.append(','); vendor.appendBindValue(insertBuilder, typeId, parameters); insertBuilder.append(','); vendor.appendBindValue(insertBuilder, now, parameters); insertBuilder.append(')'); try { Static.executeUpdateWithList(connection, insertBuilder.toString(), parameters); } catch (SQLException ex) { if (Static.isIntegrityConstraintViolation(ex)) { isNew = false; continue; } else { throw ex; } } } else { List<Object> parameters = new ArrayList<Object>(); StringBuilder updateBuilder = new StringBuilder(); updateBuilder.append("UPDATE "); vendor.appendIdentifier(updateBuilder, RECORD_UPDATE_TABLE); updateBuilder.append(" SET "); vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN); updateBuilder.append('='); vendor.appendBindValue(updateBuilder, typeId, parameters); updateBuilder.append(','); vendor.appendIdentifier(updateBuilder, UPDATE_DATE_COLUMN); updateBuilder.append('='); vendor.appendBindValue(updateBuilder, now, parameters); updateBuilder.append(" WHERE "); vendor.appendIdentifier(updateBuilder, ID_COLUMN); updateBuilder.append('='); vendor.appendBindValue(updateBuilder, id, parameters); if (Static.executeUpdateWithList(connection, updateBuilder.toString(), parameters) < 1) { isNew = true; continue; } } break; } } } @Override protected void doIndexes(Connection connection, boolean isImmediate, List<State> states) throws SQLException { SqlIndex.Static.deleteByStates(this, connection, states); Map<State, String> inRowIndexes = SqlIndex.Static.insertByStates(this, connection, states); if (!hasInRowIndex()) { return; } SqlVendor vendor = getVendor(); for (Map.Entry<State, String> entry : inRowIndexes.entrySet()) { StringBuilder updateBuilder = new StringBuilder(); updateBuilder.append("UPDATE "); vendor.appendIdentifier(updateBuilder, RECORD_TABLE); updateBuilder.append(" SET "); vendor.appendIdentifier(updateBuilder, IN_ROW_INDEX_COLUMN); updateBuilder.append('='); vendor.appendValue(updateBuilder, entry.getValue()); updateBuilder.append(" WHERE "); vendor.appendIdentifier(updateBuilder, ID_COLUMN); updateBuilder.append('='); vendor.appendValue(updateBuilder, entry.getKey().getId()); Static.executeUpdateWithArray(connection, updateBuilder.toString()); } } /** @deprecated Use {@link #index} instead. */ @Deprecated public void fixIndexes(List<State> states) { Connection connection = openConnection(); try { doIndexes(connection, true, states); } catch (SQLException ex) { List<UUID> ids = new ArrayList<UUID>(); for (State state : states) { ids.add(state.getId()); } throw new SqlDatabaseException(this, String.format( "Can't index states! (%s)", ids)); } finally { closeConnection(connection); } } @Override protected void doDeletes(Connection connection, boolean isImmediate, List<State> states) throws SQLException { SqlVendor vendor = getVendor(); StringBuilder whereBuilder = new StringBuilder(); whereBuilder.append(" WHERE "); vendor.appendIdentifier(whereBuilder, ID_COLUMN); whereBuilder.append(" IN ("); for (State state : states) { vendor.appendValue(whereBuilder, state.getId()); whereBuilder.append(','); } whereBuilder.setCharAt(whereBuilder.length() - 1, ')'); StringBuilder deleteBuilder = new StringBuilder(); deleteBuilder.append("DELETE FROM "); vendor.appendIdentifier(deleteBuilder, RECORD_TABLE); deleteBuilder.append(whereBuilder); Static.executeUpdateWithArray(connection, deleteBuilder.toString()); SqlIndex.Static.deleteByStates(this, connection, states); StringBuilder updateBuilder = new StringBuilder(); updateBuilder.append("UPDATE "); vendor.appendIdentifier(updateBuilder, RECORD_UPDATE_TABLE); updateBuilder.append(" SET "); vendor.appendIdentifier(updateBuilder, UPDATE_DATE_COLUMN); updateBuilder.append('='); vendor.appendValue(updateBuilder, System.currentTimeMillis() / 1000.0); updateBuilder.append(whereBuilder); Static.executeUpdateWithArray(connection, updateBuilder.toString()); } @FieldData.FieldInternalNamePrefix("sql.") public static class FieldData extends Modification<ObjectField> { private String indexTable; private String indexTableColumnName; private boolean indexTableReadOnly; private boolean indexTableSameColumnNames; private boolean indexTableSource; public String getIndexTable() { return indexTable; } public void setIndexTable(String indexTable) { this.indexTable = indexTable; } public boolean isIndexTableReadOnly() { return indexTableReadOnly; } public void setIndexTableReadOnly(boolean indexTableReadOnly) { this.indexTableReadOnly = indexTableReadOnly; } public boolean isIndexTableSameColumnNames() { return indexTableSameColumnNames; } public void setIndexTableSameColumnNames(boolean indexTableSameColumnNames) { this.indexTableSameColumnNames = indexTableSameColumnNames; } public void setIndexTableColumnName(String indexTableColumnName) { this.indexTableColumnName = indexTableColumnName; } public String getIndexTableColumnName() { return this.indexTableColumnName; } public boolean isIndexTableSource() { return indexTableSource; } public void setIndexTableSource(boolean indexTableSource) { this.indexTableSource = indexTableSource; } public boolean isIndexTableSourceFromAnywhere() { if (isIndexTableSource()) { return true; } ObjectField field = getOriginalObject(); ObjectStruct parent = field.getParent(); String fieldName = field.getInternalName(); for (ObjectIndex index : parent.getIndexes()) { List<String> indexFieldNames = index.getFields(); if (!indexFieldNames.isEmpty() && indexFieldNames.contains(fieldName)) { String firstIndexFieldName = indexFieldNames.get(0); if (!fieldName.equals(firstIndexFieldName)) { ObjectField firstIndexField = parent.getField(firstIndexFieldName); if (firstIndexField != null) { return firstIndexField.as(FieldData.class).isIndexTableSource(); } } } } return false; } } /** Specifies the name of the table for storing target field values. */ @Documented @ObjectField.AnnotationProcessorClass(FieldIndexTableProcessor.class) @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface FieldIndexTable { String value(); boolean readOnly() default false; boolean sameColumnNames() default false; boolean source() default false; } private static class FieldIndexTableProcessor implements ObjectField.AnnotationProcessor<FieldIndexTable> { @Override public void process(ObjectType type, ObjectField field, FieldIndexTable annotation) { FieldData data = field.as(FieldData.class); data.setIndexTable(annotation.value()); data.setIndexTableSameColumnNames(annotation.sameColumnNames()); data.setIndexTableSource(annotation.source()); data.setIndexTableReadOnly(annotation.readOnly()); } } /** {@link SqlDatabase} utility methods. */ public static final class Static { public static List<SqlDatabase> getAll() { return INSTANCES; } public static void deregisterAllDrivers() { for (WeakReference<Driver> driverRef : REGISTERED_DRIVERS) { Driver driver = driverRef.get(); if (driver != null) { LOGGER.info("Deregistering [{}]", driver); try { DriverManager.deregisterDriver(driver); } catch (SQLException ex) { LOGGER.warn("Can't deregister [{}]!", driver); } } } } /** * Log a batch update exception with values. */ static void logBatchUpdateException(BatchUpdateException bue, String sqlQuery, List<? extends List<?>> parameters) { int i = 0; StringBuilder errorBuilder = new StringBuilder(); for (int code : bue.getUpdateCounts()) { if (code == Statement.EXECUTE_FAILED) { List<?> rowData = parameters.get(i); errorBuilder.append("Batch update failed with query '"); errorBuilder.append(sqlQuery); errorBuilder.append("' with values ("); int o = 0; for (Object value : rowData) { if (o++ != 0) { errorBuilder.append(", "); } if (value instanceof byte[]) { errorBuilder.append(StringUtils.hex((byte[]) value)); } else { errorBuilder.append(value); } } errorBuilder.append(')'); } i++; } Exception ex = bue.getNextException() != null ? bue.getNextException() : bue; LOGGER.error(errorBuilder.toString(), ex); } static void logUpdateException(String sqlQuery, List<?> parameters) { int i = 0; StringBuilder errorBuilder = new StringBuilder(); errorBuilder.append("Batch update failed with query '"); errorBuilder.append(sqlQuery); errorBuilder.append("' with values ("); for (Object value : parameters) { if (i++ != 0) { errorBuilder.append(", "); } if (value instanceof byte[]) { errorBuilder.append(StringUtils.hex((byte[]) value)); } else { errorBuilder.append(value); } } errorBuilder.append(')'); LOGGER.error(errorBuilder.toString()); } // Safely binds the given parameter to the given statement at the // given index. private static void bindParameter(PreparedStatement statement, int index, Object parameter) throws SQLException { if (parameter instanceof String) { parameter = ((String) parameter).getBytes(StringUtils.UTF_8); } if (parameter instanceof StringBuilder) { parameter = ((StringBuilder) parameter).toString(); } if (parameter instanceof byte[]) { byte[] parameterBytes = (byte[]) parameter; int parameterBytesLength = parameterBytes.length; if (parameterBytesLength > 2000) { statement.setBinaryStream(index, new ByteArrayInputStream(parameterBytes), parameterBytesLength); return; } } statement.setObject(index, parameter); } /** * Executes the given batch update {@code sqlQuery} with the given * list of {@code parameters} within the given {@code connection}. * * @return Array of number of rows affected by the update query. */ public static int[] executeBatchUpdate( Connection connection, String sqlQuery, List<? extends List<?>> parameters) throws SQLException { PreparedStatement prepared = connection.prepareStatement(sqlQuery); List<?> currentRow = null; try { for (List<?> row : parameters) { currentRow = row; int columnIndex = 1; for (Object parameter : row) { bindParameter(prepared, columnIndex, parameter); columnIndex++; } prepared.addBatch(); } int[] affected = null; Stats.Timer timer = STATS.startTimer(); Profiler.Static.startThreadEvent(UPDATE_PROFILER_EVENT); try { affected = prepared.executeBatch(); return affected; } finally { double time = timer.stop(UPDATE_STATS_OPERATION); Profiler.Static.stopThreadEvent(sqlQuery); if (LOGGER.isDebugEnabled()) { LOGGER.debug( "SQL batch update: [{}], Parameters: {}, Affected: {}, Time: [{}]ms", new Object[] { sqlQuery, parameters, affected != null ? Arrays.toString(affected) : "[]", time * 1000.0 }); } } } catch (SQLException error) { logUpdateException(sqlQuery, currentRow); throw error; } finally { try { prepared.close(); } catch (SQLException error) { // Not likely and probably harmless. } } } /** * Executes the given update {@code sqlQuery} with the given * {@code parameters} within the given {@code connection}. * * @return Number of rows affected by the update query. */ public static int executeUpdateWithList( Connection connection, String sqlQuery, List<?> parameters) throws SQLException { if (parameters == null) { return executeUpdateWithArray(connection, sqlQuery); } else { Object[] array = parameters.toArray(new Object[parameters.size()]); return executeUpdateWithArray(connection, sqlQuery, array); } } /** * Executes the given update {@code sqlQuery} with the given * {@code parameters} within the given {@code connection}. * * @return Number of rows affected by the update query. */ public static int executeUpdateWithArray( Connection connection, String sqlQuery, Object... parameters) throws SQLException { boolean hasParameters = parameters != null && parameters.length > 0; PreparedStatement prepared; Statement statement; if (hasParameters) { prepared = connection.prepareStatement(sqlQuery); statement = prepared; } else { prepared = null; statement = connection.createStatement(); } try { if (hasParameters) { for (int i = 0; i < parameters.length; i++) { bindParameter(prepared, i + 1, parameters[i]); } } Integer affected = null; Stats.Timer timer = STATS.startTimer(); Profiler.Static.startThreadEvent(UPDATE_PROFILER_EVENT); Savepoint savePoint = null; try { if (!connection.getAutoCommit()) { savePoint = connection.setSavepoint(); } affected = hasParameters ? prepared.executeUpdate() : statement.executeUpdate(sqlQuery); return affected; } catch(SQLException sqlEx) { if (savePoint != null) { connection.rollback(savePoint); } throw sqlEx; } finally { if (savePoint != null) { connection.releaseSavepoint(savePoint); } double time = timer.stop(UPDATE_STATS_OPERATION); Profiler.Static.stopThreadEvent(sqlQuery); if (LOGGER.isDebugEnabled()) { LOGGER.debug( "SQL update: [{}], Affected: [{}], Time: [{}]ms", new Object[] { fillPlaceholders(sqlQuery, parameters), affected, time * 1000.0 }); } } } finally { try { statement.close(); } catch (SQLException error) { // Not likely and probably harmless. } } } /** * Returns {@code true} if the given {@code error} looks like a * {@link SQLIntegrityConstraintViolationException}. */ public static boolean isIntegrityConstraintViolation(SQLException error) { if (error instanceof SQLIntegrityConstraintViolationException) { return true; } else { String state = error.getSQLState(); return state != null && state.startsWith("23"); } } /** * Returns the name of the table for storing the values of the * given {@code index}. */ public static String getIndexTable(ObjectIndex index) { return ObjectUtils.to(String.class, index.getOptions().get(INDEX_TABLE_INDEX_OPTION)); } /** * Sets the name of the table for storing the values of the * given {@code index}. */ public static void setIndexTable(ObjectIndex index, String table) { index.getOptions().put(INDEX_TABLE_INDEX_OPTION, table); } public static Object getExtraColumn(Object object, String name) { return State.getInstance(object).getExtra(EXTRA_COLUMN_EXTRA_PREFIX + name); } public static byte[] getOriginalData(Object object) { return (byte[]) State.getInstance(object).getExtra(ORIGINAL_DATA_EXTRA); } /** @deprecated Use {@link #executeUpdateWithArray} instead. */ @Deprecated public static int executeUpdate( Connection connection, String sqlQuery, Object... parameters) throws SQLException { return executeUpdateWithArray(connection, sqlQuery, parameters); } } /** @deprecated No replacement. */ @Deprecated public void beginThreadLocalReadConnection() { } /** @deprecated No replacement. */ @Deprecated public void endThreadLocalReadConnection() { } }
package com.oracle.graal.nodeinfo.processor; import static com.oracle.graal.nodeinfo.processor.GraphNodeGenerator.NodeRefsType.*; import static com.oracle.truffle.dsl.processor.java.ElementUtils.*; import static java.util.Arrays.*; import static javax.lang.model.element.Modifier.*; import java.util.*; import java.util.stream.*; import javax.annotation.processing.*; import javax.lang.model.element.*; import javax.lang.model.type.*; import javax.lang.model.util.*; import javax.tools.Diagnostic.Kind; import com.oracle.graal.nodeinfo.*; import com.oracle.truffle.dsl.processor.java.*; import com.oracle.truffle.dsl.processor.java.compiler.*; import com.oracle.truffle.dsl.processor.java.compiler.Compiler; import com.oracle.truffle.dsl.processor.java.model.*; /** * Generates the source code for a Node class. */ public class GraphNodeGenerator { private final GraphNodeProcessor env; private final Types types; private final Elements elements; private final TypeElement Input; private final TypeElement OptionalInput; private final TypeElement Successor; final TypeElement Node; private final TypeElement NodeList; private final TypeElement NodeInputList; private final TypeElement NodeSuccessorList; private final TypeElement Position; private final List<VariableElement> inputFields = new ArrayList<>(); private final List<VariableElement> inputListFields = new ArrayList<>(); private final List<VariableElement> successorFields = new ArrayList<>(); private final List<VariableElement> successorListFields = new ArrayList<>(); private final List<VariableElement> dataFields = new ArrayList<>(); private final Set<VariableElement> optionalInputs = new HashSet<>(); private final Map<VariableElement, VariableElement> inputTypes = new HashMap<>(); private CodeTypeElement genClass; private String genClassName; public GraphNodeGenerator(GraphNodeProcessor processor) { this.env = processor; this.types = processor.getProcessingEnv().getTypeUtils(); this.elements = processor.getProcessingEnv().getElementUtils(); this.Input = getTypeElement("com.oracle.graal.graph.Node.Input"); this.OptionalInput = getTypeElement("com.oracle.graal.graph.Node.OptionalInput"); this.Successor = getTypeElement("com.oracle.graal.graph.Node.Successor"); this.Node = getTypeElement("com.oracle.graal.graph.Node"); this.NodeList = getTypeElement("com.oracle.graal.graph.NodeList"); this.NodeInputList = getTypeElement("com.oracle.graal.graph.NodeInputList"); this.NodeSuccessorList = getTypeElement("com.oracle.graal.graph.NodeSuccessorList"); this.Position = getTypeElement("com.oracle.graal.graph.Position"); } @SafeVarargs private static Collection<VariableElement> concat(List<VariableElement> fields1, List<VariableElement> fields2, List<VariableElement>... tail) { return new AbstractCollection<VariableElement>() { @Override public Iterator<VariableElement> iterator() { Stream<VariableElement> joined = Stream.concat(fields1.stream(), fields2.stream()); for (List<VariableElement> t : tail) { joined = Stream.concat(joined, t.stream()); } return joined.iterator(); } @Override public int size() { return fields1.size() + fields2.size(); } }; } /** * Returns a type element given a canonical name. * * @throw {@link NoClassDefFoundError} if a type element does not exist for {@code name} */ public TypeElement getTypeElement(String name) { TypeElement typeElement = elements.getTypeElement(name); if (typeElement == null) { throw new NoClassDefFoundError(name); } return typeElement; } public TypeElement getTypeElement(Class<?> cls) { return getTypeElement(cls.getName()); } public TypeMirror getType(String name) { return getTypeElement(name).asType(); } public TypeMirror getType(Class<?> cls) { return ElementUtils.getType(getProcessingEnv(), cls); } public ProcessingEnvironment getProcessingEnv() { return env.getProcessingEnv(); } private static String getGeneratedClassName(TypeElement node) { TypeElement typeElement = node; String genClassName = typeElement.getSimpleName().toString() + "Gen"; Element enclosing = typeElement.getEnclosingElement(); while (enclosing != null) { if (enclosing.getKind() == ElementKind.CLASS || enclosing.getKind() == ElementKind.INTERFACE) { if (enclosing.getModifiers().contains(Modifier.PRIVATE)) { throw new ElementException(enclosing, "%s %s cannot be private", enclosing.getKind().name().toLowerCase(), enclosing); } genClassName = enclosing.getSimpleName() + "_" + genClassName; } else { assert enclosing.getKind() == ElementKind.PACKAGE; } enclosing = enclosing.getEnclosingElement(); } return genClassName; } public boolean isAssignableWithErasure(Element from, Element to) { TypeMirror fromType = types.erasure(from.asType()); TypeMirror toType = types.erasure(to.asType()); return types.isAssignable(fromType, toType); } private void scanFields(TypeElement node) { Compiler compiler = CompilerFactory.getCompiler(node); TypeElement currentClazz = node; do { for (VariableElement field : ElementFilter.fieldsIn(compiler.getEnclosedElementsInDeclarationOrder(currentClazz))) { Set<Modifier> modifiers = field.getModifiers(); if (modifiers.contains(STATIC) || modifiers.contains(TRANSIENT)) { continue; } List<? extends AnnotationMirror> annotations = field.getAnnotationMirrors(); boolean isNonOptionalInput = findAnnotationMirror(annotations, Input) != null; boolean isOptionalInput = findAnnotationMirror(annotations, OptionalInput) != null; boolean isSuccessor = findAnnotationMirror(annotations, Successor) != null; if (isNonOptionalInput || isOptionalInput) { if (findAnnotationMirror(annotations, Successor) != null) { throw new ElementException(field, "Field cannot be both input and successor"); } else if (isNonOptionalInput && isOptionalInput) { throw new ElementException(field, "Inputs must be either optional or non-optional"); } else if (isAssignableWithErasure(field, NodeInputList)) { if (modifiers.contains(FINAL)) { throw new ElementException(field, "Input list field must not be final"); } if (modifiers.contains(PUBLIC) || modifiers.contains(PRIVATE)) { throw new ElementException(field, "Input list field must be protected or package-private"); } inputListFields.add(field); } else { if (!isAssignableWithErasure(field, Node) && field.getKind() == ElementKind.INTERFACE) { throw new ElementException(field, "Input field type must be an interface or assignable to Node"); } if (modifiers.contains(FINAL)) { throw new ElementException(field, "Input field must not be final"); } if (modifiers.contains(PUBLIC) || modifiers.contains(PRIVATE)) { throw new ElementException(field, "Input field must be protected or package-private"); } inputFields.add(field); } if (isOptionalInput) { inputTypes.put(field, getAnnotationValue(VariableElement.class, findAnnotationMirror(annotations, OptionalInput), "value")); optionalInputs.add(field); } else { inputTypes.put(field, getAnnotationValue(VariableElement.class, findAnnotationMirror(annotations, Input), "value")); } } else if (isSuccessor) { if (isAssignableWithErasure(field, NodeSuccessorList)) { if (modifiers.contains(FINAL)) { throw new ElementException(field, "Successor list field must not be final"); } if (modifiers.contains(PUBLIC)) { throw new ElementException(field, "Successor list field must not be public"); } successorListFields.add(field); } else { if (!isAssignableWithErasure(field, Node)) { throw new ElementException(field, "Successor field must be a Node type"); } if (modifiers.contains(FINAL)) { throw new ElementException(field, "Successor field must not be final"); } if (modifiers.contains(PUBLIC) || modifiers.contains(PRIVATE)) { throw new ElementException(field, "Successor field must be protected or package-private"); } successorFields.add(field); } } else { if (isAssignableWithErasure(field, Node) && !field.getSimpleName().contentEquals("Null")) { throw new ElementException(field, "Node field must be annotated with @" + Input.getSimpleName() + ", @" + OptionalInput.getSimpleName() + " or @" + Successor.getSimpleName()); } if (isAssignableWithErasure(field, NodeInputList)) { throw new ElementException(field, "NodeInputList field must be annotated with @" + Input.getSimpleName() + " or @" + OptionalInput.getSimpleName()); } if (isAssignableWithErasure(field, NodeSuccessorList)) { throw new ElementException(field, "NodeSuccessorList field must be annotated with @" + Successor.getSimpleName()); } dataFields.add(field); } } currentClazz = getSuperType(currentClazz); } while (!isObject(getSuperType(currentClazz).asType())); } /** * Determines if two parameter lists contain the * {@linkplain Types#isSameType(TypeMirror, TypeMirror) same} types. */ private boolean parametersMatch(List<? extends VariableElement> p1, List<? extends VariableElement> p2) { if (p1.size() == p2.size()) { for (int i = 0; i < p1.size(); i++) { if (!types.isSameType(p1.get(i).asType(), p2.get(i).asType())) { return false; } } return true; } return false; } /** * Searches a type for a method based on a given name and parameter types. */ private ExecutableElement findMethod(TypeElement type, String name, List<? extends VariableElement> parameters) { List<? extends ExecutableElement> methods = ElementFilter.methodsIn(type.getEnclosedElements()); for (ExecutableElement method : methods) { if (method.getSimpleName().toString().equals(name)) { if (parametersMatch(method.getParameters(), parameters)) { return method; } } } return null; } enum NodeRefsType { Inputs, Successors; } CodeCompilationUnit process(TypeElement node, boolean constructorsOnly) { try { return process0(node, constructorsOnly); } finally { reset(); } } private CodeCompilationUnit process0(TypeElement node, boolean constructorsOnly) { CodeCompilationUnit compilationUnit = new CodeCompilationUnit(); PackageElement packageElement = ElementUtils.findPackageElement(node); genClassName = getGeneratedClassName(node); genClass = new CodeTypeElement(modifiers(FINAL), ElementKind.CLASS, packageElement, genClassName); genClass.setSuperClass(node.asType()); for (ExecutableElement constructor : ElementFilter.constructorsIn(node.getEnclosedElements())) { if (constructor.getModifiers().contains(PUBLIC)) { throw new ElementException(constructor, "Node class constructor must not be public"); } checkFactoryMethodExists(node, constructor); CodeExecutableElement subConstructor = createConstructor(genClass, constructor); subConstructor.getModifiers().removeAll(Arrays.asList(PUBLIC, PRIVATE, PROTECTED)); genClass.add(subConstructor); } if (!constructorsOnly) { DeclaredType generatedNode = (DeclaredType) getType(GeneratedNode.class); CodeAnnotationMirror generatedNodeMirror = new CodeAnnotationMirror(generatedNode); generatedNodeMirror.setElementValue(generatedNodeMirror.findExecutableElement("value"), new CodeAnnotationValue(node.asType())); genClass.getAnnotationMirrors().add(generatedNodeMirror); scanFields(node); boolean hasInputs = !inputFields.isEmpty() || !inputListFields.isEmpty(); boolean hasSuccessors = !successorFields.isEmpty() || !successorListFields.isEmpty(); if (hasInputs || hasSuccessors) { createGetNodeAtMethod(); createGetInputTypeAtMethod(); createGetNameOfMethod(); createUpdateOrInitializeNodeAtMethod(false); createUpdateOrInitializeNodeAtMethod(true); createIsLeafNodeMethod(); createPositionAccessibleFieldOrderClass(packageElement); if (!inputListFields.isEmpty() || !successorListFields.isEmpty()) { createGetNodeListAtMethod(); createSetNodeListAtMethod(); } } if (hasInputs) { createIsOptionalInputAtMethod(); createGetFirstLevelPositionsMethod(Inputs, inputFields, inputListFields); createContainsMethod(Inputs, inputFields, inputListFields); createIterableMethod(Inputs); CodeTypeElement inputsIteratorClass = createIteratorClass(Inputs, packageElement, inputFields, inputListFields); createAllIteratorClass(Inputs, inputsIteratorClass.asType(), packageElement, inputFields, inputListFields); createWithModCountIteratorClass(Inputs, inputsIteratorClass.asType(), packageElement); createIterableClass(Inputs, packageElement); } if (hasSuccessors) { createGetFirstLevelPositionsMethod(Successors, successorFields, successorListFields); createContainsMethod(Successors, successorFields, successorListFields); createIterableMethod(Successors); CodeTypeElement successorsIteratorClass = createIteratorClass(Successors, packageElement, successorFields, successorListFields); createAllIteratorClass(Successors, successorsIteratorClass.asType(), packageElement, successorFields, successorListFields); createWithModCountIteratorClass(Successors, successorsIteratorClass.asType(), packageElement); createIterableClass(Successors, packageElement); } } compilationUnit.add(genClass); return compilationUnit; } /** * Checks that a public static factory method named {@code "create"} exists in {@code node} * whose signature matches that of a given constructor. * * @throws ElementException if the check fails */ private void checkFactoryMethodExists(TypeElement node, ExecutableElement constructor) { ExecutableElement create = findMethod(node, "create", constructor.getParameters()); if (create == null) { Formatter f = new Formatter(); f.format("public static %s create(", node.getSimpleName()); String sep = ""; Formatter callArgs = new Formatter(); for (VariableElement v : constructor.getParameters()) { f.format("%s%s %s", sep, ElementUtils.getSimpleName(v.asType()), v.getSimpleName()); callArgs.format("%s%s", sep, v.getSimpleName()); sep = ", "; } f.format(") { return USE_GENERATED_NODES ? new %s(%s) : new %s(%s); }", genClassName, callArgs, node.getSimpleName(), callArgs); throw new ElementException(constructor, "Missing Node class factory method '%s'", f); } if (!create.getModifiers().containsAll(asList(PUBLIC, STATIC))) { throw new ElementException(constructor, "Node class factory method must be public and static"); } } private CodeExecutableElement createConstructor(TypeElement type, ExecutableElement element) { CodeExecutableElement executable = CodeExecutableElement.clone(getProcessingEnv(), element); // to create a constructor we have to set the return type to null.(TODO needs fix) executable.setReturnType(null); // we have to set the name manually otherwise <init> is inferred (TODO needs fix) executable.setSimpleName(CodeNames.of(type.getSimpleName().toString())); CodeTreeBuilder b = executable.createBuilder(); b.startStatement().startSuperCall(); for (VariableElement v : element.getParameters()) { b.string(v.getSimpleName().toString()); } b.end().end(); return executable; } private void reset() { inputFields.clear(); inputListFields.clear(); successorFields.clear(); successorListFields.clear(); dataFields.clear(); optionalInputs.clear(); inputTypes.clear(); genClass = null; genClassName = null; } /** * Checks that a generated method overrides exactly one method in a super type and that the * super type is Node. */ private void checkOnlyInGenNode(CodeExecutableElement method) { List<ExecutableElement> overriddenMethods = getDeclaredMethodsInSuperTypes(method.getEnclosingClass(), method.getSimpleName().toString(), method.getParameterTypes()); for (ExecutableElement overriddenMethod : overriddenMethods) { if (!overriddenMethod.getEnclosingElement().equals(Node)) { env.message(Kind.WARNING, overriddenMethod, "This method is overridden in a generated subclass will never be called"); } } } private void createIsLeafNodeMethod() { CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC), getType(boolean.class), "isLeafNode"); method.createBuilder().startReturn().string("false").end(); genClass.add(method); checkOnlyInGenNode(method); } private ExecutableElement createIsOptionalInputAtMethod() { CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC), getType(boolean.class), "isOptionalInputAt"); method.addParameter(new CodeVariableElement(Position.asType(), "pos")); CodeTreeBuilder b = method.createBuilder(); b.startAssert().string("pos.isInput()").end(); if (!optionalInputs.isEmpty()) { b.startSwitch().string("pos.getIndex()").end().startBlock(); int index = 0; for (VariableElement f : concat(inputFields, inputListFields)) { if (optionalInputs.contains(f)) { b.startCase().string(String.valueOf(index)).end(); } index++; } b.startStatement().string("return true").end(); b.end(); } b.startReturn().string("false").end(); genClass.add(method); checkOnlyInGenNode(method); return method; } private ExecutableElement createGetFirstLevelPositionsMethod(NodeRefsType nodeRefsType, List<VariableElement> nodeFields, List<VariableElement> nodeListFields) { DeclaredType collectionOfPosition = types.getDeclaredType((TypeElement) types.asElement(getType(Collection.class)), Position.asType()); CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC), collectionOfPosition, "getFirstLevel" + nodeRefsType); CodeTreeBuilder b = method.createBuilder(); b.startReturn().startNew(getTypeElement("com.oracle.graal.graph.FirstLevelPositionCollection").asType()); b.string(String.valueOf(nodeFields.size())); b.string(String.valueOf(nodeListFields.size())); b.string(String.valueOf(nodeRefsType == NodeRefsType.Inputs)); b.end().end(); genClass.add(method); checkOnlyInGenNode(method); return method; } private CodeTypeElement createIteratorClass(NodeRefsType nodeRefsType, PackageElement packageElement, List<VariableElement> nodeFields, List<VariableElement> nodeListFields) { String name = nodeRefsType + "Iterator"; CodeTypeElement cls = new CodeTypeElement(modifiers(PRIVATE), ElementKind.CLASS, packageElement, name); cls.setSuperClass(getType("com.oracle.graal.graph.NodeRefIterator")); // Constructor CodeExecutableElement ctor = new CodeExecutableElement(Collections.emptySet(), null, name); ctor.addParameter(new CodeVariableElement(getType(boolean.class), "callForward")); CodeTreeBuilder b = ctor.createBuilder(); b.startStatement().startSuperCall(); b.string(String.valueOf(nodeFields.size())); b.string(String.valueOf(nodeListFields.size())); b.string(String.valueOf(nodeRefsType == NodeRefsType.Inputs)); b.end().end(); b.startIf().string("callForward").end().startBlock(); b.startStatement().string("forward()").end(); b.end(); cls.add(ctor); // Methods overriding those in NodeRefIterator createGetFieldMethod(cls, nodeFields, Node.asType(), "getNode"); createGetFieldMethod(cls, nodeListFields, types.getDeclaredType(NodeList, types.getWildcardType(Node.asType(), null)), "getNodeList"); genClass.add(cls); return cls; } private void createGetFieldMethod(CodeTypeElement cls, List<VariableElement> fields, TypeMirror returnType, String name) { if (!fields.isEmpty()) { CodeExecutableElement method = new CodeExecutableElement(modifiers(PROTECTED, FINAL), returnType, name); method.addParameter(new CodeVariableElement(getType(int.class), "at")); CodeTreeBuilder b = method.createBuilder(); createGetFieldCases(b, fields, returnType, null); cls.add(method); } } private void createGetFieldCases(CodeTreeBuilder b, List<VariableElement> fields, TypeMirror returnType, String returnExpressionSuffix) { for (int i = 0; i < fields.size(); i++) { VariableElement field = fields.get(i); b.startIf().string("at == " + i).end().startBlock(); b.startReturn(); if (returnExpressionSuffix == null && !isAssignableWithErasure(field, types.asElement(returnType))) { b.cast(((DeclaredType) returnType).asElement().getSimpleName().toString()); } b.string(genClassName + ".this." + field.getSimpleName()); if (returnExpressionSuffix != null) { b.string(returnExpressionSuffix); } b.end(); b.end(); } b.startThrow().startNew(getType(NoSuchElementException.class)).end().end(); } private void createSetNodeListAtCases(CodeTreeBuilder b, List<VariableElement> fields, TypeMirror returnType, String returnExpressionSuffix) { for (int i = 0; i < fields.size(); i++) { VariableElement field = fields.get(i); b.startIf().string("at == " + i).end().startBlock(); if (returnExpressionSuffix == null && !isAssignableWithErasure(field, types.asElement(returnType))) { b.cast(((DeclaredType) returnType).asElement().getSimpleName().toString()); } b.startStatement(); b.string(genClassName + ".this." + field.getSimpleName(), " = "); b.cast(field.asType(), CodeTreeBuilder.singleString("list")); b.end(); b.end(); } } private void createUpdateOrInitializeFieldCases(CodeTreeBuilder b, List<VariableElement> fields, boolean isInitialization, boolean isList) { boolean elseIf = false; for (int i = 0; i < fields.size(); i++) { VariableElement field = fields.get(i); String fieldRef = genClassName + ".this." + field.getSimpleName(); if (!isList) { elseIf = b.startIf(elseIf); b.string("at == " + i).end().startBlock(); if (!isInitialization) { b.startStatement().string("Node old = "); if (!isAssignableWithErasure(field, Node)) { b.cast(Node.asType(), CodeTreeBuilder.singleString(fieldRef)); } else { b.string(fieldRef); } b.end(); } b.startStatement().string(fieldRef, " = "); if (!isAssignableWithErasure(Node, field)) { b.cast(field.asType(), CodeTreeBuilder.singleString("newValue")); } else { b.string("newValue"); } b.end(); if (!isInitialization) { b.startIf().string("pos.isInput()").end().startBlock(); b.startStatement().string("updateUsages(old, newValue)").end(); b.end(); b.startElseBlock(); b.startStatement().string("updatePredecessor(old, newValue)").end(); b.end(); } b.end(); } else { elseIf = b.startIf(elseIf); b.string("at == " + i).end().startBlock(); DeclaredType nodeListOfNode = types.getDeclaredType(NodeList, types.getWildcardType(Node.asType(), null)); b.declaration(nodeListOfNode, "list", fieldRef); if (!isInitialization) { // if (pos.getSubIndex() < list.size()) { b.startIf().string("pos.getSubIndex() < list.size()").end().startBlock(); b.startStatement().string("list.set(pos.getSubIndex(), newValue)").end(); b.end(); b.startElseBlock(); } b.startWhile().string("list.size() <= pos.getSubIndex()").end().startBlock(); b.startStatement().string("list.add(null)").end(); b.end(); if (isInitialization) { b.startStatement().string("list.initialize(pos.getSubIndex(), newValue)").end(); } else { b.startStatement().string("list.add(newValue)").end(); b.end(); } b.end(); } } b.startElseBlock(); b.startThrow().startNew(getType(NoSuchElementException.class)).end().end(); b.end(); } private void createPositionAccessibleFieldOrderClass(PackageElement packageElement) { CodeTypeElement cls = new CodeTypeElement(modifiers(PUBLIC, STATIC), ElementKind.CLASS, packageElement, "FieldOrder"); cls.getImplements().add(getType("com.oracle.graal.graph.NodeClass.PositionFieldOrder")); CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC), getType(String[].class), "getOrderedFieldNames"); method.addParameter(new CodeVariableElement(getType(boolean.class), "input")); CodeTreeBuilder b = method.createBuilder(); b.startIf().string("input").end().startBlock(); String initializer = concat(inputFields, inputListFields).stream().map(v -> v.getSimpleName().toString()).collect(Collectors.joining("\", \"", "\"", "\"")); b.startStatement().string("return new String[] {", initializer, "}").end(); b.end(); b.startElseBlock(); initializer = concat(successorFields, successorListFields).stream().map(v -> v.getSimpleName().toString()).collect(Collectors.joining("\", \"", "\"", "\"")); b.startStatement().string("return new String[] {", initializer, "}").end(); b.end(); cls.add(method); genClass.add(cls); } private void createAllIteratorClass(NodeRefsType nodeRefsType, TypeMirror inputsIteratorType, PackageElement packageElement, List<VariableElement> nodeFields, List<VariableElement> nodeListFields) { String name = "All" + nodeRefsType + "Iterator"; CodeTypeElement cls = new CodeTypeElement(modifiers(PRIVATE, FINAL), ElementKind.CLASS, packageElement, name); cls.setSuperClass(inputsIteratorType); // Constructor CodeExecutableElement ctor = new CodeExecutableElement(Collections.emptySet(), null, name); CodeTreeBuilder b = ctor.createBuilder(); b.startStatement().startSuperCall(); b.string("true"); b.end().end(); cls.add(ctor); // forward() method CodeExecutableElement method = new CodeExecutableElement(modifiers(PROTECTED), getType(void.class), "forward"); b = method.createBuilder(); int nodeFieldsSize = nodeFields.size(); int nodeListFieldsSize = nodeListFields.size(); String cond = "index < " + nodeFieldsSize; b.startIf().string(cond).end().startBlock(); b.startStatement().string("index++").end(); b.startIf().string(cond).end().startBlock(); b.startStatement().string("return").end(); b.end(); b.end(); b.startElseBlock(); b.startStatement().string("subIndex++").end(); b.end(); DeclaredType nodeListOfNode = types.getDeclaredType(NodeList, types.getWildcardType(Node.asType(), null)); int count = nodeFieldsSize + nodeListFieldsSize; b.startWhile().string("index < " + count).end().startBlock(); b.declaration(nodeListOfNode, "list", "getNodeList(index - " + nodeFieldsSize + ")"); b.startIf().string("subIndex < list.size()").end().startBlock(); b.startStatement().string("return").end(); b.end(); b.startStatement().string("subIndex = 0").end(); b.startStatement().string("index++").end(); b.end(); cls.add(method); genClass.add(cls); } private void createWithModCountIteratorClass(NodeRefsType nodeRefsType, TypeMirror superType, PackageElement packageElement) { String name = nodeRefsType + "WithModCountIterator"; CodeTypeElement cls = new CodeTypeElement(modifiers(PRIVATE, FINAL), ElementKind.CLASS, packageElement, name); cls.setSuperClass(superType); // modCount field cls.add(new CodeVariableElement(modifiers(PRIVATE, FINAL), getType(int.class), "modCount")); // Constructor CodeExecutableElement ctor = new CodeExecutableElement(Collections.emptySet(), null, name); CodeTreeBuilder b = ctor.createBuilder(); b.startStatement().startSuperCall(); b.string("false"); b.end().end(); b.startAssert().staticReference(getType("com.oracle.graal.graph.Graph"), "MODIFICATION_COUNTS_ENABLED").end(); b.startStatement().string("this.modCount = modCount()").end(); b.startStatement().string("forward()").end(); cls.add(ctor); // hasNext, next and nextPosition methods overrideModWithCounterMethod(cls, "hasNext", getType(boolean.class)); overrideModWithCounterMethod(cls, "next", Node.asType()); overrideModWithCounterMethod(cls, "nextPosition", Position.asType()); genClass.add(cls); } private static void overrideModWithCounterMethod(CodeTypeElement cls, String name, TypeMirror returnType) { CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC), returnType, name); CodeTreeBuilder b = method.createBuilder(); b.startTryBlock(); b.startStatement().string("return super." + name + "()").end(); b.end().startFinallyBlock(); b.startAssert().string("modCount == modCount() : \"must not be modified\"").end(); b.end(); cls.add(method); } private void createIterableClass(NodeRefsType nodeRefsType, PackageElement packageElement) { String name = nodeRefsType + "Iterable"; CodeTypeElement cls = new CodeTypeElement(modifiers(PRIVATE), ElementKind.CLASS, packageElement, name); cls.getImplements().add(getType("com.oracle.graal.graph.NodeClassIterable")); // iterator() method CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC, FINAL), getType("com.oracle.graal.graph.NodeRefIterator"), "iterator"); CodeTreeBuilder b = method.createBuilder(); b.startIf().staticReference(getType("com.oracle.graal.graph.Graph"), "MODIFICATION_COUNTS_ENABLED").end().startBlock(); b.startStatement().string("return new " + nodeRefsType + "WithModCountIterator()").end(); b.end(); b.startElseBlock(); b.startStatement().string("return new " + nodeRefsType + "Iterator(true)").end(); b.end(); cls.add(method); // withNullIterator() method method = new CodeExecutableElement(modifiers(PUBLIC, FINAL), getType("com.oracle.graal.graph.NodePosIterator"), "withNullIterator"); b = method.createBuilder(); b.startStatement().string("return new All" + nodeRefsType + "Iterator()").end(); cls.add(method); // contains(Node) method method = new CodeExecutableElement(modifiers(PUBLIC, FINAL), getType(boolean.class), "contains"); method.addParameter(new CodeVariableElement(Node.asType(), "n")); b = method.createBuilder(); b.startStatement().string("return " + nodeRefsType.name().toLowerCase() + "Contain(n)").end(); cls.add(method); genClass.add(cls); } private void createContainsMethod(NodeRefsType nodeRefsType, List<VariableElement> nodeFields, List<VariableElement> nodeListFields) { CodeExecutableElement method = new CodeExecutableElement(modifiers(PRIVATE, FINAL), getType(boolean.class), nodeRefsType.name().toLowerCase() + "Contain"); method.addParameter(new CodeVariableElement(Node.asType(), "n")); CodeTreeBuilder b = method.createBuilder(); for (VariableElement f : nodeFields) { b.startIf().string("n == " + f).end().startBlock(); b.startStatement().string("return true").end(); b.end(); } for (VariableElement f : nodeListFields) { b.startIf().string(f + ".contains(n)").end().startBlock(); b.startStatement().string("return true").end(); b.end(); } b.startStatement().string("return false").end(); genClass.add(method); checkOnlyInGenNode(method); } private static final String API_TAG = "V2"; private void createIterableMethod(NodeRefsType nodeRefsType) { CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC, FINAL), getType("com.oracle.graal.graph.NodeClassIterable"), (nodeRefsType == Inputs ? "inputs" : "successors") + API_TAG); CodeTreeBuilder b = method.createBuilder(); b.startStatement().string("return new " + nodeRefsType + "Iterable()").end(); genClass.add(method); checkOnlyInGenNode(method); } private void createGetNodeAtMethod() { CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC, FINAL), Node.asType(), "getNodeAt"); method.addParameter(new CodeVariableElement(Position.asType(), "pos")); CodeTreeBuilder b = method.createBuilder(); b.startIf().string("pos.isInput()").end().startBlock(); createGetNodeAt(b, inputFields, inputListFields); b.end(); b.startElseBlock(); createGetNodeAt(b, successorFields, successorListFields); b.end(); genClass.add(method); checkOnlyInGenNode(method); } private void createGetNodeListAtMethod() { CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC, FINAL), types.getDeclaredType(NodeList, types.getWildcardType(Node.asType(), null)), "getNodeListAt"); method.addParameter(new CodeVariableElement(Position.asType(), "pos")); CodeTreeBuilder b = method.createBuilder(); b.startIf().string("pos.isInput()").end().startBlock(); createGetNodeListAt(b, inputFields, inputListFields); b.end(); b.startElseBlock(); createGetNodeListAt(b, successorFields, successorListFields); b.end(); genClass.add(method); checkOnlyInGenNode(method); } private void createSetNodeListAtMethod() { CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC, FINAL), getType(void.class), "setNodeListAt"); DeclaredType suppress = (DeclaredType) getType(SuppressWarnings.class); CodeAnnotationMirror suppressMirror = new CodeAnnotationMirror(suppress); suppressMirror.setElementValue(suppressMirror.findExecutableElement("value"), new CodeAnnotationValue("unchecked")); method.getAnnotationMirrors().add(suppressMirror); method.addParameter(new CodeVariableElement(Position.asType(), "pos")); method.addParameter(new CodeVariableElement(types.getDeclaredType(NodeList, types.getWildcardType(Node.asType(), null)), "list")); CodeTreeBuilder b = method.createBuilder(); b.startIf().string("pos.isInput()").end().startBlock(); createSetNodeListAt(b, inputFields, inputListFields); b.end(); b.startElseBlock(); createSetNodeListAt(b, successorFields, successorListFields); b.end(); genClass.add(method); checkOnlyInGenNode(method); } private void createGetNameOfMethod() { CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC, FINAL), getType(String.class), "getNameOf"); method.addParameter(new CodeVariableElement(Position.asType(), "pos")); CodeTreeBuilder b = method.createBuilder(); b.startIf().string("pos.isInput()").end().startBlock(); createGetNameOf(b, inputFields, inputListFields); b.end(); b.startElseBlock(); createGetNameOf(b, successorFields, successorListFields); b.end(); genClass.add(method); checkOnlyInGenNode(method); } private void createGetInputTypeAtMethod() { CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC, FINAL), getType(InputType.class), "getInputTypeAt"); method.addParameter(new CodeVariableElement(Position.asType(), "pos")); CodeTreeBuilder b = method.createBuilder(); b.startAssert().string("pos.isInput()").end(); boolean hasNodes = !inputFields.isEmpty(); boolean hasNodeLists = !inputListFields.isEmpty(); if (hasNodeLists || hasNodes) { int index = 0; for (VariableElement f : concat(inputFields, inputListFields)) { b.startIf().string("pos.getIndex() == " + index).end().startBlock(); b.startStatement().string("return ").staticReference(getType(InputType.class), inputTypes.get(f).getSimpleName().toString()).end(); b.end(); index++; } } b.startThrow().startNew(getType(NoSuchElementException.class)).end().end(); genClass.add(method); checkOnlyInGenNode(method); } private boolean hidesField(String name) { for (VariableElement field : concat(inputFields, inputListFields, successorFields, successorListFields, dataFields)) { if (field.getSimpleName().contentEquals(name)) { return true; } } return false; } private void createUpdateOrInitializeNodeAtMethod(boolean isInitialization) { CodeExecutableElement method = new CodeExecutableElement(modifiers(PUBLIC, FINAL), getType(void.class), (isInitialization ? "initialize" : "update") + "NodeAt"); method.addParameter(new CodeVariableElement(Position.asType(), "pos")); CodeVariableElement newValue = new CodeVariableElement(Node.asType(), "newValue"); if (hidesField(newValue.getSimpleName().toString())) { DeclaredType suppress = (DeclaredType) getType(SuppressWarnings.class); CodeAnnotationMirror suppressMirror = new CodeAnnotationMirror(suppress); suppressMirror.setElementValue(suppressMirror.findExecutableElement("value"), new CodeAnnotationValue("hiding")); newValue.getAnnotationMirrors().add(suppressMirror); } method.addParameter(newValue); CodeTreeBuilder b = method.createBuilder(); b.startIf().string("pos.isInput()").end().startBlock(); createUpdateOrInitializeNodeAt(b, inputFields, inputListFields, isInitialization); b.end(); b.startElseBlock(); createUpdateOrInitializeNodeAt(b, successorFields, successorListFields, isInitialization); b.end(); genClass.add(method); checkOnlyInGenNode(method); } private void createGetNodeAt(CodeTreeBuilder b, List<VariableElement> nodes, List<VariableElement> nodeLists) { boolean hasNodes = !nodes.isEmpty(); boolean hasNodeLists = !nodeLists.isEmpty(); if (!hasNodeLists && !hasNodes) { b.startThrow().startNew(getType(NoSuchElementException.class)).end().end(); } else { if (hasNodes) { if (!hasNodeLists) { b.startAssert().string("pos.getSubIndex() == NOT_ITERABLE").end(); } else { b.startIf().string("pos.getSubIndex() == NOT_ITERABLE").end().startBlock(); } b.declaration("int", "at", "pos.getIndex()"); createGetFieldCases(b, nodes, Node.asType(), null); if (hasNodeLists) { b.end(); } } if (hasNodeLists) { if (!hasNodes) { b.startAssert().string("pos.getSubIndex() != NOT_ITERABLE").end(); } else { b.startElseBlock(); } b.declaration("int", "at", "pos.getIndex() - " + nodes.size()); createGetFieldCases(b, nodeLists, Node.asType(), ".get(pos.getSubIndex())"); if (hasNodes) { b.end(); } } } } private void createGetNodeListAt(CodeTreeBuilder b, List<VariableElement> nodes, List<VariableElement> nodeLists) { boolean hasNodeLists = !nodeLists.isEmpty(); if (!hasNodeLists) { b.startThrow().startNew(getType(NoSuchElementException.class)).end().end(); } else { b.startAssert().string("pos.getSubIndex() == NODE_LIST").end(); b.declaration("int", "at", "pos.getIndex() - " + nodes.size()); createGetFieldCases(b, nodeLists, Node.asType(), ""); } } private void createSetNodeListAt(CodeTreeBuilder b, List<VariableElement> nodes, List<VariableElement> nodeLists) { boolean hasNodeLists = !nodeLists.isEmpty(); if (!hasNodeLists) { b.startThrow().startNew(getType(NoSuchElementException.class)).end().end(); } else { b.startAssert().string("pos.getSubIndex() == NODE_LIST").end(); b.declaration("int", "at", "pos.getIndex() - " + nodes.size()); createSetNodeListAtCases(b, nodeLists, Node.asType(), ""); } } private void createGetNameOf(CodeTreeBuilder b, List<VariableElement> nodes, List<VariableElement> nodeLists) { boolean hasNodes = !nodes.isEmpty(); boolean hasNodeLists = !nodeLists.isEmpty(); if (hasNodeLists || hasNodes) { int index = 0; for (VariableElement f : nodes) { b.startIf().string("pos.getIndex() == " + index).end().startBlock(); b.startStatement().string("return \"" + f.getSimpleName() + "\"").end(); b.end(); index++; } for (VariableElement f : nodeLists) { b.startIf().string("pos.getIndex() == " + index).end().startBlock(); b.startStatement().string("return \"" + f.getSimpleName() + "\"").end(); b.end(); index++; } } b.startThrow().startNew(getType(NoSuchElementException.class)).end().end(); } private void createUpdateOrInitializeNodeAt(CodeTreeBuilder b, List<VariableElement> nodes, List<VariableElement> nodeLists, boolean isInitialization) { boolean hasNodes = !nodes.isEmpty(); boolean hasNodeLists = !nodeLists.isEmpty(); if (nodes.isEmpty() && nodeLists.isEmpty()) { b.startThrow().startNew(getType(NoSuchElementException.class)).end().end(); } else { if (hasNodes) { if (!hasNodeLists) { b.startAssert().string("pos.getSubIndex() == NOT_ITERABLE").end(); } else { b.startIf().string("pos.getSubIndex() == NOT_ITERABLE").end().startBlock(); } b.declaration("int", "at", "pos.getIndex()"); createUpdateOrInitializeFieldCases(b, nodes, isInitialization, false); if (hasNodeLists) { b.end(); } } if (hasNodeLists) { if (!hasNodes) { b.startAssert().string("pos.getSubIndex() != NOT_ITERABLE").end(); } else { b.startElseBlock(); } b.declaration("int", "at", "pos.getIndex() - " + nodes.size()); createUpdateOrInitializeFieldCases(b, nodeLists, isInitialization, true); if (hasNodes) { b.end(); } } } } }
package pl.zankowski.iextrading4j.client.rest.request.stocks; public enum DividendRange { ONE_MONTH("1m"), THREE_MONTHS("3m"), SIX_MONTHS("6m"), YEAR_TO_DATE("ytd"), ONE_YEAR("1y"), TWO_YEARS("2y"), FIVE_YEARS("5y"), NEXT("next"); private final String code; DividendRange(String code) { this.code = code; } public String getCode() { return code; } }
package org.jboss.forge.addon.javaee.validation.ui; import java.util.EnumSet; import java.util.Map; import java.util.concurrent.Callable; import javax.inject.Inject; import org.jboss.forge.addon.convert.Converter; import org.jboss.forge.addon.javaee.ui.AbstractJavaEECommand; import org.jboss.forge.addon.javaee.validation.ConstraintOperations; import org.jboss.forge.addon.javaee.validation.ConstraintType; import org.jboss.forge.addon.javaee.validation.CoreConstraints; import org.jboss.forge.addon.parser.java.resources.JavaResource; import org.jboss.forge.addon.projects.Project; import org.jboss.forge.addon.ui.context.UIBuilder; import org.jboss.forge.addon.ui.context.UIContext; import org.jboss.forge.addon.ui.context.UIExecutionContext; import org.jboss.forge.addon.ui.context.UINavigationContext; import org.jboss.forge.addon.ui.hints.InputType; import org.jboss.forge.addon.ui.input.UIInput; import org.jboss.forge.addon.ui.input.UISelectOne; import org.jboss.forge.addon.ui.metadata.UICommandMetadata; import org.jboss.forge.addon.ui.metadata.WithAttributes; import org.jboss.forge.addon.ui.result.NavigationResult; import org.jboss.forge.addon.ui.result.Result; import org.jboss.forge.addon.ui.result.Results; import org.jboss.forge.addon.ui.util.Metadata; import org.jboss.forge.addon.ui.wizard.UIWizardStep; import org.jboss.forge.roaster.model.JavaClass; import org.jboss.forge.roaster.model.Property; import org.jboss.forge.roaster.model.source.PropertySource; public class ValidationSelectFieldWizardStep extends AbstractJavaEECommand implements UIWizardStep { @Inject @WithAttributes(label = "On Property", description = "The property on which the constraint applies", required = true, type = InputType.DROPDOWN) private UISelectOne<PropertySource<?>> onProperty; @Inject @WithAttributes(label = "Constraint", description = "The type of constraint to add", required = true, type = InputType.DROPDOWN) private UISelectOne<CoreConstraints> constraint; @Inject @WithAttributes(label = "Add constraint on the property accessor?") private UIInput<Boolean> onAccessor; @Inject private ConstraintOperations constraintOperations; @Override public void initializeUI(UIBuilder builder) throws Exception { setupProperty(builder.getUIContext()); setupConstraint(); setupAccessor(); builder.add(onProperty).add(constraint).add(onAccessor); } @Override public UICommandMetadata getMetadata(UIContext context) { return Metadata.from(super.getMetadata(context), ValidationSelectFieldWizardStep.class) .name("Select constrained field") .description("Select the property you wish to constraint"); } @SuppressWarnings("unchecked") private void setupProperty(UIContext context) throws Exception { JavaResource selectedResource = (JavaResource) context.getAttributeMap().get(JavaResource.class); JavaClass<?> javaClass = selectedResource.getJavaType(); onProperty.setItemLabelConverter(new Converter<PropertySource<?>, String>() { @Override public String convert(PropertySource<?> source) { return (source == null) ? null : source.getName(); } }); onProperty.setValueChoices((Iterable<PropertySource<?>>) javaClass.getProperties()); } private void setupConstraint() { constraint.setItemLabelConverter(new Converter<CoreConstraints, String>() { @Override public String convert(CoreConstraints source) { return (source == null) ? null : source.getDescription(); } }); constraint.setValueChoices(EnumSet.allOf(CoreConstraints.class)); } private void setupAccessor() { onAccessor.setEnabled(new Callable<Boolean>() { @Override public Boolean call() throws Exception { Property<?> value = onProperty.getValue(); return value == null ? Boolean.FALSE : value.isAccessible(); } }); } @Override public Result execute(UIExecutionContext context) throws Exception { ConstraintType constraintType = constraint.getValue(); if (constraintType == CoreConstraints.VALID) { Project project = getSelectedProject(context); Result result = constraintOperations.addValidConstraint(project, onProperty.getValue(), onAccessor.getValue()); return result; } else { return Results.success(); } } @Override public NavigationResult next(UINavigationContext context) throws Exception { ConstraintType constraintType = constraint.getValue(); UIContext uiContext = context.getUIContext(); Map<Object, Object> attributeMap = uiContext.getAttributeMap(); attributeMap.put(PropertySource.class, onProperty.getValue()); attributeMap.put(ConstraintType.class, constraintType); attributeMap.put("onAccessor", onAccessor.getValue()); if (constraintType == CoreConstraints.VALID) { return null; } else { return Results.navigateTo(ValidationGenerateConstraintWizardStep.class); } } @Override protected boolean isProjectRequired() { return false; } }
package org.eclipse.kura.core.data.transport.mqtt; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.net.ssl.SSLSocketFactory; import org.eclipse.kura.KuraConnectException; import org.eclipse.kura.KuraException; import org.eclipse.kura.KuraNotConnectedException; import org.eclipse.kura.KuraTimeoutException; import org.eclipse.kura.KuraTooManyInflightMessagesException; import org.eclipse.kura.configuration.ConfigurableComponent; import org.eclipse.kura.configuration.ConfigurationService; import org.eclipse.kura.configuration.Password; import org.eclipse.kura.core.data.transport.mqtt.MqttClientConfiguration.PersistenceType; import org.eclipse.kura.core.util.ValidationUtil; import org.eclipse.kura.crypto.CryptoService; import org.eclipse.kura.data.transport.listener.DataTransportListener; import org.eclipse.kura.data.DataTransportService; import org.eclipse.kura.data.DataTransportToken; import org.eclipse.kura.ssl.SslManagerService; import org.eclipse.kura.ssl.SslManagerServiceOptions; import org.eclipse.kura.ssl.SslServiceListener; import org.eclipse.kura.status.CloudConnectionStatusComponent; import org.eclipse.kura.status.CloudConnectionStatusEnum; import org.eclipse.kura.status.CloudConnectionStatusService; import org.eclipse.kura.system.SystemService; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.IMqttToken; import org.eclipse.paho.client.mqttv3.MqttAsyncClient; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttClientPersistence; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.MqttPersistenceException; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import org.eclipse.paho.client.mqttv3.persist.MqttDefaultFilePersistence; import org.osgi.service.component.ComponentContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MqttDataTransport implements DataTransportService, MqttCallback, ConfigurableComponent, SslServiceListener, CloudConnectionStatusComponent { private static final Logger s_logger = LoggerFactory.getLogger(MqttDataTransport.class); private static final String MQTT_SCHEME = "mqtt: private static final String MQTTS_SCHEME = "mqtts: // TODO: add mqtt+ssl for secure mqtt private static final String TOPIC_PATTERN = "#([^\\s/]+)"; // '#' followed // by one or // more // non-whitespace // but not the private static final Pattern s_topicPattern = Pattern.compile(TOPIC_PATTERN); private SystemService m_systemService; private SslManagerService m_sslManagerService; private CloudConnectionStatusService m_cloudConnectionStatusService; private CloudConnectionStatusEnum m_notificationStatus = CloudConnectionStatusEnum.OFF; private MqttAsyncClient m_mqttClient; private DataTransportListenerS m_dataTransportListeners; private MqttClientConfiguration m_clientConf; private boolean m_newSession; private String m_sessionId; PersistenceType m_persistenceType; MqttClientPersistence m_persistence; private Map<String, String> m_topicContext = new HashMap<String, String>(); private Map<String, Object> m_properties = new HashMap<String, Object>(); private CryptoService m_cryptoService; private static final String MQTT_BROKER_URL_PROP_NAME = "broker-url"; private static final String MQTT_USERNAME_PROP_NAME = "username"; private static final String MQTT_PASSWORD_PROP_NAME = "password"; private static final String MQTT_CLIENT_ID_PROP_NAME = "client-id"; private static final String MQTT_KEEP_ALIVE_PROP_NAME = "keep-alive"; private static final String MQTT_CLEAN_SESSION_PROP_NAME = "clean-session"; private static final String MQTT_TIMEOUT_PROP_NAME = "timeout"; // All // timeouts private static final String MQTT_DEFAULT_VERSION_PROP_NAME = "protocol-version"; private static final String MQTT_LWT_QOS_PROP_NAME = "lwt.qos"; private static final String MQTT_LWT_RETAIN_PROP_NAME = "lwt.retain"; private static final String MQTT_LWT_TOPIC_PROP_NAME = "lwt.topic"; private static final String MQTT_LWT_PAYLOAD_PROP_NAME = "lwt.payload"; private static final String CLOUD_ACCOUNT_NAME_PROP_NAME = "topic.context.account-name"; private static final String PERSISTENCE_TYPE_PROP_NAME = "in-flight.persistence"; private static final String TOPIC_ACCOUNT_NAME_CTX_NAME = "account-name"; private static final String TOPIC_DEVICE_ID_CTX_NAME = "client-id"; private static final String SSL_PROTOCOL = SslManagerServiceOptions.PROP_PROTOCOL; private static final String SSL_CIPHERS = SslManagerServiceOptions.PROP_CIPHERS; private static final String SSL_HN_VERIFY = SslManagerServiceOptions.PROP_HN_VERIFY; private static final String SSL_CERT_ALIAS = "ssl.certificate.alias"; private static final String SSL_DEFAULT_HN_VERIFY = "use-ssl-service-config"; // Dependencies public void setSystemService(SystemService systemService) { this.m_systemService = systemService; } public void unsetSystemService(SystemService systemService) { this.m_systemService = null; } public void setSslManagerService(SslManagerService sslManagerService) { this.m_sslManagerService = sslManagerService; } public void unsetSslManagerService(SslManagerService sslManagerService) { this.m_sslManagerService = null; } public void setCryptoService(CryptoService cryptoService) { this.m_cryptoService = cryptoService; } public void unsetCryptoService(CryptoService cryptoService) { this.m_cryptoService = null; } public void setCloudConnectionStatusService(CloudConnectionStatusService cloudConnectionStatusService) { this.m_cloudConnectionStatusService = cloudConnectionStatusService; } public void unsetCloudConnectionStatusService(CloudConnectionStatusService cloudConnectionStatusService) { this.m_cloudConnectionStatusService = null; } // Activation APIs protected void activate(ComponentContext componentContext, Map<String, Object> properties) { s_logger.info("Activating {}...", properties.get(ConfigurationService.KURA_SERVICE_PID)); // We need to catch the configuration exception and activate anyway. // Otherwise the ConfigurationService will not be able to track us. HashMap<String, Object> decryptedPropertiesMap = new HashMap<String, Object>(); for (Map.Entry<String, Object> entry : properties.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (key.equals(MQTT_PASSWORD_PROP_NAME)) { try { Password decryptedPassword = new Password(m_cryptoService.decryptAes(((String) value).toCharArray())); decryptedPropertiesMap.put(key, decryptedPassword); } catch (Exception e) { s_logger.info("Password is not encrypted"); decryptedPropertiesMap.put(key, new Password((String) value)); } } else { decryptedPropertiesMap.put(key, value); } } m_properties.putAll(decryptedPropertiesMap); try { m_clientConf = buildConfiguration(m_properties); setupMqttSession(); } catch (RuntimeException e) { s_logger.error("Invalid client configuration. Service will not be able to connect until the configuration is updated", e); } m_dataTransportListeners = new DataTransportListenerS(componentContext); // Do nothing waiting for the connect request from the upper layer. } protected void deactivate(ComponentContext componentContext) { s_logger.debug("Deactivating {}...", m_properties.get(ConfigurationService.KURA_SERVICE_PID)); // Before deactivating us, the OSGi container should have first // deactivated all dependent components. // They should be able to complete whatever is needed, // e.g. publishing a special last message, // synchronously in their deactivate method and disconnect us cleanly. // There shouldn't be anything to do here other then // perhaps forcibly disconnecting the MQTT client if not already done. if (isConnected()) { disconnect(0); } } public void updated(Map<String, Object> properties) { s_logger.info("Updating {}...", properties.get(ConfigurationService.KURA_SERVICE_PID)); m_properties.clear(); HashMap<String, Object> decryptedPropertiesMap = new HashMap<String, Object>(); for (Map.Entry<String, Object> entry : properties.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); if (key.equals(MQTT_PASSWORD_PROP_NAME)) { try { Password decryptedPassword = new Password(m_cryptoService.decryptAes(((String) value).toCharArray())); decryptedPropertiesMap.put(key, decryptedPassword); } catch (Exception e) { s_logger.info("Password is not encrypted"); decryptedPropertiesMap.put(key, new Password((String) value)); } } else { decryptedPropertiesMap.put(key, value); } } m_properties.putAll(decryptedPropertiesMap); update(); } private void update() { boolean wasConnected = isConnected(); // First notify the Listeners // We do nothing other than notifying the listeners which may later // request to disconnect and reconnect again. m_dataTransportListeners.onConfigurationUpdating(wasConnected); // Then update the configuration // Throwing a RuntimeException here is fine. // Listeners will not be notified of an invalid configuration update. s_logger.info("Building new configuration..."); m_clientConf = buildConfiguration(m_properties); // We do nothing other than notifying the listeners which may later // request to disconnect and reconnect again. m_dataTransportListeners.onConfigurationUpdated(wasConnected); } // Service APIs public synchronized void connect() throws KuraConnectException { // We treat this as an application bug. if (isConnected()) { s_logger.error("Already connected"); throw new IllegalStateException("Already connected"); // TODO: define an KuraRuntimeException } // Attempt to setup the MQTT session setupMqttSession(); if (m_mqttClient == null) { s_logger.error("Invalid configuration"); throw new IllegalStateException("Invalid configuration"); // TODO: define an KuraRuntimeException } s_logger.info(" s_logger.info("# Connection Properties"); s_logger.info("# broker = " + m_clientConf.getBrokerUrl()); s_logger.info("# clientId = " + m_clientConf.getClientId()); s_logger.info("# username = " + m_clientConf.getConnectOptions().getUserName()); s_logger.info("# password = XXXXXXXXXXXXXX"); s_logger.info("# keepAlive = " + m_clientConf.getConnectOptions().getKeepAliveInterval()); s_logger.info("# timeout = " + m_clientConf.getConnectOptions().getConnectionTimeout()); s_logger.info("# cleanSession = " + m_clientConf.getConnectOptions().isCleanSession()); s_logger.info("# MQTT version = " + getMqttVersionLabel(m_clientConf.getConnectOptions().getMqttVersion())); s_logger.info("# willDestination = " + m_clientConf.getConnectOptions().getWillDestination()); s_logger.info("# willMessage = " + m_clientConf.getConnectOptions().getWillMessage()); s_logger.info(" s_logger.info("# Connecting..."); //Register the component in the CloudConnectionStatus service m_cloudConnectionStatusService.register(this); //Update status notification service m_cloudConnectionStatusService.updateStatus(this, CloudConnectionStatusEnum.FAST_BLINKING); // connect try { IMqttToken connectToken = m_mqttClient.connect(m_clientConf.getConnectOptions()); connectToken.waitForCompletion(getTimeToWaitMillis() * 3); s_logger.info("# Connected!"); s_logger.info(" //Update status notification service m_cloudConnectionStatusService.updateStatus(this, CloudConnectionStatusEnum.ON); } catch (MqttException e) { s_logger.warn("xxxxx Connect failed. Forcing disconnect. xxxxx {}", e); try { // prevent callbacks from a zombie client m_mqttClient.setCallback(null); m_mqttClient.close(); } catch (Exception de) { s_logger.warn("Forced disconnect exception.", de); } finally { m_mqttClient = null; } //Update status notification service m_cloudConnectionStatusService.updateStatus(this, CloudConnectionStatusEnum.OFF); throw new KuraConnectException(e, "Cannot connect"); } finally{ //Always unregister from CloudConnectionStatus service so to switch to the previous state m_cloudConnectionStatusService.unregister(this); } // notify the listeners m_dataTransportListeners.onConnectionEstablished(m_newSession); } @Override public boolean isConnected() { if (m_mqttClient != null) { return m_mqttClient.isConnected(); } return false; } @Override public String getBrokerUrl() { if (m_clientConf != null) { String brokerUrl = m_clientConf.getBrokerUrl(); if(brokerUrl!=null) return brokerUrl; } return ""; } @Override public String getAccountName() { if (m_clientConf != null) { String accountName = m_topicContext.get(TOPIC_ACCOUNT_NAME_CTX_NAME); if(accountName!=null) return accountName; } return ""; } @Override public String getUsername() { if (m_clientConf != null) { String username = m_clientConf.getConnectOptions().getUserName(); if(username!=null) return username; } return ""; } @Override public String getClientId() { if (m_clientConf != null) { String clientId = m_clientConf.getClientId(); if(clientId!=null) return clientId; } return ""; } // TODO: java.lang.reflect.Proxy for every listener in order to catch // runtime exceptions thrown by listener implementor and log them. @Override public synchronized void disconnect(long quiesceTimeout) { // Disconnect the client if it's connected. If it fails log the // exception. // Don't throw an exception because the caller would not // be able to handle it. if (isConnected()) { s_logger.info("Disconnecting..."); // notify the listeners m_dataTransportListeners.onDisconnecting(); try { IMqttToken token = m_mqttClient.disconnect(quiesceTimeout); token.waitForCompletion(getTimeToWaitMillis()); s_logger.info("Disconnected"); } catch (MqttException e) { s_logger.error("Disconnect failed", e); } // notify the listeners m_dataTransportListeners.onDisconnected(); } else { s_logger.warn("MQTT client already disconnected"); } } // Subscription Management Methods @Override public void subscribe(String topic, int qos) throws KuraTimeoutException, KuraException, KuraNotConnectedException { if (m_mqttClient == null || !m_mqttClient.isConnected()) { throw new KuraNotConnectedException("Not connected"); } topic = replaceTopicVariables(topic); s_logger.info("Subscribing to topic: {} with QoS: {}", topic, qos); try { IMqttToken token = m_mqttClient.subscribe(topic, qos); token.waitForCompletion(getTimeToWaitMillis()); } catch (MqttException e) { if (e.getReasonCode() == MqttException.REASON_CODE_CLIENT_TIMEOUT) { s_logger.warn("Timeout subscribing to topic: {}", topic); throw new KuraTimeoutException("Timeout subscribing to topic: " + topic, e); } else { s_logger.error("Cannot subscribe to topic: " + topic, e); throw KuraException.internalError(e, "Cannot subscribe to topic: " + topic); } } } @Override public void unsubscribe(String topic) throws KuraTimeoutException, KuraException, KuraNotConnectedException { if (m_mqttClient == null || !m_mqttClient.isConnected()) { throw new KuraNotConnectedException("Not connected"); } topic = replaceTopicVariables(topic); s_logger.info("Unsubscribing to topic: {}", topic); try { IMqttToken token = m_mqttClient.unsubscribe(topic); token.waitForCompletion(getTimeToWaitMillis()); } catch (MqttException e) { if (e.getReasonCode() == MqttException.REASON_CODE_CLIENT_TIMEOUT) { s_logger.warn("Timeout unsubscribing to topic: {}", topic); throw new KuraTimeoutException("Timeout unsubscribing to topic: " + topic, e); } else { s_logger.error("Cannot unsubscribe to topic: " + topic, e); throw KuraException.internalError(e, "Cannot unsubscribe to topic: " + topic); } } } /* * (non-Javadoc) * * @see org.eclipse.kura.data.DataPublisherService#publish(java.lang.String * , byte[], int, boolean) * * DataConnectException this can be easily recovered connecting the service. * TooManyInflightMessagesException the caller SHOULD retry publishing the * message at a later time. RuntimeException (unchecked) all other * unrecoverable faults that are not recoverable by the caller. */ @Override public DataTransportToken publish(String topic, byte[] payload, int qos, boolean retain) throws KuraTooManyInflightMessagesException, KuraException, KuraNotConnectedException { if (m_mqttClient == null || !m_mqttClient.isConnected()) { throw new KuraNotConnectedException("Not connected"); } topic = replaceTopicVariables(topic); s_logger.info("Publishing message on topic: {} with QoS: {}", topic, qos); MqttMessage message = new MqttMessage(); message.setPayload(payload); message.setQos(qos); message.setRetained(retain); Integer messageId = null; try { IMqttDeliveryToken token = m_mqttClient.publish(topic, message); // At present Paho ALWAYS allocates (gets and increments) internally // a message ID, // even for messages published with QoS == 0. // Of course, for QoS == 0 this "internal" message ID will not hit // the wire. // On top of that, messages published with QoS == 0 are confirmed // in the deliveryComplete callback. // Another implementation might behave differently // and only allocate a message ID for messages published with QoS > // We don't want to rely on this and only return and confirm IDs // of messages published with QoS > 0. s_logger.debug("Published message with ID: {}", token.getMessageId()); if (qos > 0) { messageId = Integer.valueOf(token.getMessageId()); } } catch (MqttPersistenceException e) { // This is probably an unrecoverable internal error s_logger.error("Cannot publish on topic: {}", topic, e); throw new IllegalStateException("Cannot publish on topic: " + topic, e); } catch (MqttException e) { if (e.getReasonCode() == MqttException.REASON_CODE_MAX_INFLIGHT) { s_logger.info("Too many inflight messages"); throw new KuraTooManyInflightMessagesException(e, "Too many in-fligh messages"); } else { s_logger.error("Cannot publish on topic: " + topic, e); throw KuraException.internalError(e, "Cannot publish on topic: " + topic); } } DataTransportToken token = null; if (messageId != null) { token = new DataTransportToken(messageId, m_sessionId); } return token; } @Override public void addDataTransportListener(DataTransportListener listener) { m_dataTransportListeners.add(listener); } @Override public void removeDataTransportListener(DataTransportListener listener) { m_dataTransportListeners.remove(listener); } // MqttCallback methods @Override public void connectionLost(final Throwable cause) { s_logger.warn("Connection Lost", cause); // notify the listeners m_dataTransportListeners.onConnectionLost(cause); } @Override public void deliveryComplete(IMqttDeliveryToken token) { if (token == null) { s_logger.error("null token"); return; } // Weird, tokens related to messages published with QoS > 0 have a null // nested message MqttMessage msg = null; try { msg = token.getMessage(); } catch (MqttException e) { s_logger.error("Cannot get message", e); return; } if (msg != null) { // Note that Paho call this also for messages published with QoS == // We don't want to rely on that and we drop asynchronous confirms // for QoS == 0. int qos = msg.getQos(); if (qos == 0) { s_logger.debug("Ignoring deliveryComplete for messages published with QoS == 0"); return; } } int id = token.getMessageId(); s_logger.debug("Delivery complete for message with ID: {}", id); // FIXME: We should be more selective here and only call the listener // that actually published the message. // Anyway we don't have such a mapping and so the publishers MUST track // their own // identifiers and filter confirms. // FIXME: it can happen that the listener that has published the message // has not come up yet. // This is the scenario: // * Paho has some in-flight messages. // * Kura gets stopped, crashes or the power is removed. // * Kura starts again, Paho connects and restores in-flight messages // from its persistence. // * These messages are delivered (this callback gets called) before the // publisher (also a DataPublisherListener) // * has come up (not yet tracked by the OSGi container). // These confirms will be lost! // notify the listeners DataTransportToken dataPublisherToken = new DataTransportToken(id, m_sessionId); m_dataTransportListeners.onMessageConfirmed(dataPublisherToken); } @Override public void messageArrived(String topic, MqttMessage message) throws Exception { s_logger.debug("Message arrived on topic: {}", topic); // FIXME: we should be more selective here and only call the listeners // actually subscribed to this topic. // Anyway we don't have such a mapping so the listeners are responsible // to filter messages. // FIXME: the same argument about lost confirms applies to arrived // messages. // notify the listeners m_dataTransportListeners.onMessageArrived(topic, message.getPayload(), message.getQos(), message.isRetained()); } private long getTimeToWaitMillis() { // We use the same value for every timeout return m_clientConf.getConnectOptions().getConnectionTimeout() * 1000L; } // SslServiceListener Overrides @Override public void onConfigurationUpdated() { // The SSL service was update, build a new socket connection update(); } /* * This method builds an internal configuration option needed by the client * to connect. The configuration is assembled from various sources: * component configuration, SystemService, NetworkService, etc. The returned * configuration is valid so no further validation is needed. If a valid * configuration cannot be assembled the method throws a RuntimeException * (assuming that this error is unrecoverable). */ private MqttClientConfiguration buildConfiguration(Map<String, Object> properties) { MqttClientConfiguration clientConfiguration; MqttConnectOptions conOpt = new MqttConnectOptions(); String clientId = null; String brokerUrl = null; try { // Configure the client ID clientId = (String) properties.get(MQTT_CLIENT_ID_PROP_NAME); if (clientId == null || clientId.trim().length() == 0) { clientId = m_systemService.getPrimaryMacAddress(); } ValidationUtil.notEmptyOrNull(clientId, "clientId"); // replace invalid token in the client ID as it is used as part of // the topicname space clientId = clientId.replace('/', '-'); clientId = clientId.replace('+', '-'); clientId = clientId.replace(' clientId = clientId.replace('.', '-'); // Configure the broker URL brokerUrl = (String) properties.get(MQTT_BROKER_URL_PROP_NAME); ValidationUtil.notEmptyOrNull(brokerUrl, MQTT_BROKER_URL_PROP_NAME); brokerUrl = brokerUrl.trim(); brokerUrl = brokerUrl.replaceAll("^" + MQTT_SCHEME, "tcp: brokerUrl = brokerUrl.replaceAll("^" + MQTTS_SCHEME, "ssl: brokerUrl = brokerUrl.replaceAll("/$", ""); ValidationUtil.notEmptyOrNull(brokerUrl, "brokerUrl"); ValidationUtil.notNegative((Integer) properties.get(MQTT_KEEP_ALIVE_PROP_NAME), MQTT_KEEP_ALIVE_PROP_NAME); ValidationUtil.notNegative((Integer) properties.get(MQTT_TIMEOUT_PROP_NAME), MQTT_TIMEOUT_PROP_NAME); ValidationUtil.notNull((Boolean) properties.get(MQTT_CLEAN_SESSION_PROP_NAME), MQTT_CLEAN_SESSION_PROP_NAME); String userName = (String) properties.get(MQTT_USERNAME_PROP_NAME); if (userName != null && !userName.isEmpty()) { conOpt.setUserName(userName); } Password password = (Password) properties.get(MQTT_PASSWORD_PROP_NAME); if (password != null && password.toString().length() != 0) { conOpt.setPassword(password.getPassword()); } conOpt.setKeepAliveInterval((Integer) properties.get(MQTT_KEEP_ALIVE_PROP_NAME)); conOpt.setConnectionTimeout((Integer) properties.get(MQTT_TIMEOUT_PROP_NAME)); conOpt.setCleanSession((Boolean) properties.get(MQTT_CLEAN_SESSION_PROP_NAME)); conOpt.setMqttVersion((Integer) properties.get(MQTT_DEFAULT_VERSION_PROP_NAME)); synchronized (m_topicContext) { m_topicContext.clear(); if (properties.get(CLOUD_ACCOUNT_NAME_PROP_NAME) != null) { m_topicContext.put(TOPIC_ACCOUNT_NAME_CTX_NAME, (String) properties.get(CLOUD_ACCOUNT_NAME_PROP_NAME)); } m_topicContext.put(TOPIC_DEVICE_ID_CTX_NAME, clientId); } String willTopic = (String) properties.get(MQTT_LWT_TOPIC_PROP_NAME); if (!(willTopic == null || willTopic.isEmpty())) { int willQos = 0; boolean willRetain = false; String willPayload = (String) properties.get(MQTT_LWT_PAYLOAD_PROP_NAME); if (properties.get(MQTT_LWT_QOS_PROP_NAME) != null) { willQos = (Integer) properties.get(MQTT_LWT_QOS_PROP_NAME); } if (properties.get(MQTT_LWT_RETAIN_PROP_NAME) != null) { willRetain = (Boolean) properties.get(MQTT_LWT_RETAIN_PROP_NAME); } willTopic = replaceTopicVariables(willTopic); byte[] payload = {}; if (willPayload != null && !willPayload.isEmpty()) { try { payload = willPayload.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { s_logger.error("Unsupported encoding", e); } } conOpt.setWill(willTopic, payload, willQos, willRetain); } } catch (KuraException e) { s_logger.error("Invalid configuration"); throw new IllegalStateException("Invalid MQTT client configuration", e); } // SSL if (brokerUrl.startsWith("ssl")) { try { String alias = (String) m_properties.get(SSL_CERT_ALIAS); if (alias == null || "".equals(alias.trim())) { alias = m_topicContext.get(TOPIC_ACCOUNT_NAME_CTX_NAME); } String protocol = (String) m_properties.get(SSL_PROTOCOL); String ciphers = (String) m_properties.get(SSL_CIPHERS); String hnVerification = (String) m_properties.get(SSL_HN_VERIFY); SSLSocketFactory ssf; if (SSL_DEFAULT_HN_VERIFY.equals(hnVerification)) { ssf = m_sslManagerService.getSSLSocketFactory(protocol, ciphers, null, null, null, alias); } else { ssf = m_sslManagerService.getSSLSocketFactory(protocol, ciphers, null, null, null, alias, Boolean.valueOf(hnVerification)); } conOpt.setSocketFactory(ssf); } catch (Exception e) { s_logger.error("SSL setup failed", e); throw new IllegalStateException("SSL setup failed", e); } } String sType = (String) properties.get(PERSISTENCE_TYPE_PROP_NAME); PersistenceType persistenceType = null; if ("file".equals(sType)) { persistenceType = PersistenceType.FILE; } else if ("memory".equals(sType)) { persistenceType = PersistenceType.MEMORY; } else { throw new IllegalStateException("Invalid MQTT client configuration: persistenceType: " + persistenceType); } clientConfiguration = new MqttClientConfiguration(brokerUrl, clientId, persistenceType, conOpt); return clientConfiguration; } private String replaceTopicVariables(String topic) { boolean found; Matcher topicMatcher = s_topicPattern.matcher(topic); StringBuffer sb = new StringBuffer(); do { found = topicMatcher.find(); if (found) { // By default replace #variable-name (group 0) with itself String replacement = topicMatcher.group(0); // TODO: Try to get variable-name (group 1) from the context String variableName = topicMatcher.group(1); synchronized (m_topicContext) { String value = m_topicContext.get(variableName); if (value != null) { replacement = value; } } // Replace #variable-name with the value of the variable topicMatcher.appendReplacement(sb, replacement); } } while (found); topicMatcher.appendTail(sb); String replacedTopic = sb.toString(); s_logger.debug("Replaced tokens in topic {} with: {}", topic, replacedTopic); return replacedTopic; } private String generateSessionId() { return m_clientConf.getClientId() + "-" + m_clientConf.getBrokerUrl(); } private void setupMqttSession() { if (m_clientConf == null) { throw new IllegalStateException("Invalid client configuration"); } // We need to construct a new client instance only if either the broker URL // or the client ID changes. // We also need to construct a new instance if the persistence type (file or memory) changes. // We MUST avoid to construct a new client instance every time because // in that case the MQTT message ID is reset to 1. if (m_mqttClient != null) { String brokerUrl = m_mqttClient.getServerURI(); String clientId = m_mqttClient.getClientId(); if (!(brokerUrl.equals(m_clientConf.getBrokerUrl()) && clientId.equals(m_clientConf.getClientId()) && m_persistenceType == m_clientConf .getPersistenceType())) { try { s_logger.info("Closing client..."); // prevent callbacks from a zombie client m_mqttClient.setCallback(null); m_mqttClient.close(); s_logger.info("Closed"); } catch (MqttException e) { s_logger.error("Cannot close client", e); } finally { m_mqttClient = null; } } } // Connecting with Clean Session flag set to true always starts // a new session. boolean newSession = m_clientConf.getConnectOptions().isCleanSession(); if (m_mqttClient == null) { s_logger.info("Creating a new client instance"); // Initialize persistence. This is only useful if the client // connects with // Clean Session flag set to false. // Note that when using file peristence, // Paho creates a subdirectory persistence whose name is encoded // like this: // cristiano-tcpbroker-stageeveryware-cloudcom1883/ // So the persistence is per client ID (cristiano) and broker URL. // If we are connecting to a different broker URL or with a // different client ID, // Paho will create a new subdirectory for this MQTT connection. // Closing the old client instance also deletes the associated // persistence subdirectory. // The lesson is: // Reconnecting to the same broker URL with the same client ID will // leverage // Paho persistence and the MQTT message ID is always increased (up // to the its maximum). // Connecting either to a different broker URL or with a different // client ID discards persisted // messages and the MQTT client ID is reset. // We have a problem here where the DataService needs to track // in-flight messages, possibly // across different MQTT connections. // These messages will never be confirmed on a different connection. // While we can assume that the client ID never changes because it's // typically auto-generated, // we cannot safely assume that the broker URL never changes. // The above leads to two problems: // The MQTT message ID alone is not sufficient to track an in-flight // message // because it can be reset on a different connection. // On a different connection the DataService should republish the // in-flight messages because // Paho won't do that. PersistenceType persistenceType = m_clientConf.getPersistenceType(); if (persistenceType == PersistenceType.MEMORY) { s_logger.info("Using memory persistence for in-flight messages"); m_persistence = new MemoryPersistence(); } else { StringBuffer sb = new StringBuffer(); sb.append(m_systemService.getKuraDataDirectory()).append(m_systemService.getFileSeparator()).append("paho-persistence"); String dir = sb.toString(); s_logger.info("Using file persistence for in-flight messages: {}", dir); // Look for "Close on CONNACK timeout" FIXME in this file. // Make sure persistence is closed. // This is needed if the previous connect attempt was // forcibly terminated by closing the client. if (m_persistence != null) { try { m_persistence.close(); } catch (MqttPersistenceException e) { s_logger.info("Failed to close persistence. Ignoring exception " + e.getMessage()); s_logger.debug("Failed to close persistence. Ignoring exception.", e); } } m_persistence = new MqttDefaultFilePersistence(dir); } // Construct the MqttClient instance MqttAsyncClient mqttClient = null; try { mqttClient = new MqttAsyncClient(m_clientConf.getBrokerUrl(), m_clientConf.getClientId(), m_persistence); } catch (MqttException e) { s_logger.error("Client instantiation failed", e); throw new IllegalStateException("Client instantiation failed", e); } mqttClient.setCallback(this); m_persistenceType = persistenceType; m_mqttClient = mqttClient; if (!m_clientConf.getConnectOptions().isCleanSession()) { // This is tricky. // The purpose of this code is to try to restore pending delivery tokens // from the MQTT client persistence and determine if the next connection // can be considered continuing an existing session. // This is needed to allow the upper layer deciding what to do with the // in-flight messages it is tracking (if any). // If pending delivery tokens are found we assume that the upper layer // is tracking them. In this case we set the newSession flag to false // and notify this in the onConnectionEstablished callback. // The upper layer shouldn't do anything special. // Otherwise the next upper layer should decide what to do with the // in-flight messages it is tracking (if any), either to republish or // drop them. IMqttDeliveryToken[] pendingDeliveryTokens = m_mqttClient.getPendingDeliveryTokens(); if (pendingDeliveryTokens != null && pendingDeliveryTokens.length != 0) { newSession = false; } } } m_newSession = newSession; m_sessionId = generateSessionId(); } private static String getMqttVersionLabel(int mqttVersion) { switch (mqttVersion) { case MqttConnectOptions.MQTT_VERSION_3_1: return "3.1"; case MqttConnectOptions.MQTT_VERSION_3_1_1: return "3.1.1"; default: return String.valueOf(mqttVersion); } } @Override public int getNotificationPriority() { return CloudConnectionStatusService.PRIORITY_MEDIUM; } @Override public CloudConnectionStatusEnum getNotificationStatus() { return m_notificationStatus; } @Override public void setNotificationStatus(CloudConnectionStatusEnum status) { m_notificationStatus = status; } }
package org.jivesoftware.smack; import org.jivesoftware.smack.packet.RosterPacket; import org.jivesoftware.smack.packet.IQ; import java.util.*; /** * Each user in your roster is represented by a roster entry, which contains the user's * JID and a name or nickname you assign. * * @author Matt Tucker */ public class RosterEntry { private String user; private String name; private RosterPacket.ItemType type; private XMPPConnection connection; /** * Creates a new roster entry. * * @param user the user. * @param name the nickname for the entry. * @param type the subscription type. * @param connection a connection to the XMPP server. */ RosterEntry(String user, String name, RosterPacket.ItemType type, XMPPConnection connection) { this.user = user; this.name = name; this.type = type; this.connection = connection; } /** * Returns the JID of the user associated with this entry. * * @return the user associated with this entry. */ public String getUser() { return user; } /** * Returns the name associated with this entry. * * @return the name. */ public String getName() { return name; } /** * Sets the name associated with this entry. * * @param name the name. */ public void setName(String name) { // Do nothing if the name hasn't changed. if (name != null && name.equals(this.name)) { return; } this.name = name; RosterPacket packet = new RosterPacket(); packet.setType(IQ.Type.SET); packet.addRosterItem(toRosterItem(this)); connection.sendPacket(packet); } /** * Returns an iterator for all the roster groups that this entry belongs to. * * @return an iterator for the groups this entry belongs to. */ public Iterator getGroups() { List results = new ArrayList(); // Loop through all roster groups and find the ones that contain this // entry. This algorithm should be fine for (Iterator i=connection.roster.getGroups(); i.hasNext(); ) { RosterGroup group = (RosterGroup)i.next(); if (group.contains(this)) { results.add(group); } } return results.iterator(); } /** * Returns the roster subscription type of the entry. When the type is * RosterPacket.ItemType.NONE, the subscription request is pending. * * @return the type. */ public RosterPacket.ItemType getType() { return type; } public String toString() { StringBuffer buf = new StringBuffer(); if (name != null) { buf.append(name).append(": "); } buf.append(user); Iterator groups = getGroups(); if (groups.hasNext()) { buf.append(" ["); RosterGroup group = (RosterGroup)groups.next(); buf.append(group.getName()); while (groups.hasNext()) { buf.append(", "); group = (RosterGroup)groups.next(); buf.append(group.getName()); } buf.append("]"); } return buf.toString(); } public boolean equals(Object object) { if (this == object) { return true; } if (object != null && object instanceof RosterEntry) { return user.equals(((RosterEntry)object).getUser()); } else { return false; } } static RosterPacket.Item toRosterItem(RosterEntry entry) { RosterPacket.Item item = new RosterPacket.Item(entry.getUser(), entry.getName()); item.setItemType(entry.getType()); // Set the correct group names for the item. for (Iterator j=entry.getGroups(); j.hasNext(); ) { RosterGroup group = (RosterGroup)j.next(); item.addGroupName(group.getName()); } return item; } }
package etomica.normalmode; import etomica.api.IAtomList; import etomica.api.IBoundary; import etomica.api.IBox; import etomica.api.ISpecies; import etomica.api.IVector; import etomica.api.IVectorMutable; import etomica.box.Box; import etomica.config.ConfigurationLatticeSimple; import etomica.lattice.BravaisLatticeCrystal; import etomica.lattice.crystal.Basis; import etomica.lattice.crystal.Primitive; import etomica.lattice.crystal.PrimitiveCubic; import etomica.simulation.Simulation; import etomica.space.BoundaryRectangularPeriodic; import etomica.space.ISpace; import etomica.species.SpeciesSpheresMono; public class BasisBigCell extends Basis { private static final long serialVersionUID = 1L; public BasisBigCell(ISpace space, Basis subBasis, int[] nSubCells) { super(makeScaledCoordinates(space, subBasis, nSubCells)); } protected static IVector[] makeScaledCoordinates(ISpace space, Basis subBasis, int[] nSubCells) { // make pretend sim, species and box so we can find the appropriate coordinates Simulation sim = new Simulation(space); ISpecies species = new SpeciesSpheresMono(sim, space); sim.addSpecies(species); // we might be used in the context of a deformable boundary (non-rectangular primitive) // but because we only care about scaled coordinates, the deformation doesn't // change what our result should be. so just pretend that it's rectangular. IBoundary boundary = new BoundaryRectangularPeriodic(space); Primitive primitive = new PrimitiveCubic(space); IBox box = new Box(boundary, space); sim.addBox(box); IVector vector = space.makeVector(nSubCells); box.getBoundary().setBoxSize(vector); int numMolecules = subBasis.getScaledCoordinates().length; for (int i=0; i<nSubCells.length; i++) { numMolecules *= nSubCells[i]; } box.setNMolecules(species, numMolecules); ConfigurationLatticeSimple configLattice = new ConfigurationLatticeSimple(new BravaisLatticeCrystal(primitive, subBasis), space); configLattice.initializeCoordinates(box); IVector boxSize = boundary.getBoxSize(); // retrieve real coordinates and scale them IAtomList atomList = box.getLeafList(); IVectorMutable[] pos = new IVectorMutable[atomList.getAtomCount()]; for (int i=0; i<atomList.getAtomCount(); i++) { pos[i] = space.makeVector(); pos[i].E(atomList.getAtom(i).getPosition()); pos[i].DE(boxSize); // coordinates now range from -0.5 to +0.5, we want 0.0 to 1.0 pos[i].PE(0.5); } return pos; } }
package datamanager.core.gui; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.*; import biomodelsim.core.gui.*; import buttons.core.gui.*; public class DataManager extends JPanel implements ActionListener, MouseListener { private static final long serialVersionUID = -2669704247953218544L; private String directory; private JList files; private JTable table; private JButton addData, removeData, editData, copyData; private JButton add, remove, rename, copy, copyFromView, importFile; private BioSim biosim; public DataManager(String directory, BioSim biosim) { this.biosim = biosim; this.directory = directory; try { Properties p = new Properties(); p.load(new FileInputStream(new File(directory + File.separator + ".lrn"))); String[] s = p.values().toArray(new String[0]); sort(s); files = new JList(s); } catch (Exception e) { files = new JList(); } JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(260, 200)); scroll.setPreferredSize(new Dimension(276, 132)); scroll.setViewportView(files); files.addMouseListener(this); files.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); add = new JButton("Add"); add.addActionListener(this); remove = new JButton("Remove"); remove.addActionListener(this); rename = new JButton("Rename"); rename.addActionListener(this); copy = new JButton("Copy"); copy.addActionListener(this); copyFromView = new JButton("Copy From View"); copyFromView.addActionListener(this); importFile = new JButton("Import"); importFile.addActionListener(this); JPanel buttons = new JPanel(new BorderLayout()); JPanel topButtons = new JPanel(); JPanel bottomButtons = new JPanel(); topButtons.add(add); topButtons.add(remove); topButtons.add(rename); bottomButtons.add(copy); bottomButtons.add(copyFromView); bottomButtons.add(importFile); buttons.add(topButtons, "North"); buttons.add(bottomButtons, "South"); table = new JTable(); table.addMouseListener(this); JScrollPane scroll1 = new JScrollPane(); scroll1.setMinimumSize(new Dimension(260, 200)); scroll1.setPreferredSize(new Dimension(276, 132)); scroll1.setViewportView(table); addData = new JButton("Add Data Point"); addData.addActionListener(this); removeData = new JButton("Remove Data Point"); removeData.addActionListener(this); editData = new JButton("Edit Data Point"); editData.addActionListener(this); copyData = new JButton("Copy Data Point"); copyData.addActionListener(this); JPanel dataButtons = new JPanel(); dataButtons.add(addData); dataButtons.add(removeData); dataButtons.add(editData); dataButtons.add(copyData); JPanel files = new JPanel(new BorderLayout()); files.add(scroll, "Center"); files.add(buttons, "South"); JPanel data = new JPanel(new BorderLayout()); data.add(scroll1, "Center"); data.add(dataButtons, "South"); this.setLayout(new BorderLayout()); this.add(files, "West"); this.add(data, "Center"); } public void actionPerformed(ActionEvent e) { if (e.getSource() == add) { } else if (e.getSource() == remove) { } else if (e.getSource() == rename) { try { String rename = JOptionPane.showInputDialog(biosim.frame(), "Please Enter New Name:", "Rename", JOptionPane.PLAIN_MESSAGE); if (rename != null) { rename = rename.trim(); } else { return; } Properties p = new Properties(); p.load(new FileInputStream(new File(directory + File.separator + ".lrn"))); int index = files.getSelectedIndex(); files.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); String[] list = Buttons.getList( new String[p.keySet().toArray(new String[0]).length], files); files.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); files.setSelectedIndex(index); for (String s : list) { if (s.equals(rename)) { JOptionPane.showMessageDialog(biosim.frame(), "A file with that description already exists.", "Description Must Be Unique", JOptionPane.ERROR_MESSAGE); return; } } for (String s : p.keySet().toArray(new String[0])) { if (p.getProperty(s).equals(files.getSelectedValue())) { p.setProperty(s, rename); } } p.store(new FileOutputStream(new File(directory + File.separator + ".lrn")), "Learn File Data"); String[] s = p.values().toArray(new String[0]); sort(s); files.setListData(s); } catch (Exception e1) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to rename.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == copy) { try { String copy = JOptionPane.showInputDialog(biosim.frame(), "Please Enter New Name:", "Copy", JOptionPane.PLAIN_MESSAGE); if (copy != null) { copy = copy.trim(); } else { return; } int run = 0; String[] list = new File(directory).list(); for (int i = 0; i < list.length; i++) { if (!(new File(directory + File.separator + list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; } } } } } Properties p = new Properties(); p.load(new FileInputStream(new File(directory + File.separator + ".lrn"))); int index = files.getSelectedIndex(); files.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); list = Buttons.getList(new String[p.keySet().toArray(new String[0]).length], files); files.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); files.setSelectedIndex(index); for (String s : list) { if (s.equals(copy)) { JOptionPane.showMessageDialog(biosim.frame(), "A file with that description already exists.", "Description Must Be Unique", JOptionPane.ERROR_MESSAGE); return; } } for (String s : p.keySet().toArray(new String[0])) { if (p.getProperty(s).equals(files.getSelectedValue())) { String end = "run-" + (run + 1) + ".tsd"; FileOutputStream out = new FileOutputStream(new File(directory + File.separator + end)); FileInputStream in = new FileInputStream(new File(directory + File.separator + s)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); p.setProperty(end, copy); } } p.store(new FileOutputStream(new File(directory + File.separator + ".lrn")), "Learn File Data"); String[] s = p.values().toArray(new String[0]); sort(s); files.setListData(s); } catch (Exception e1) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to copy.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == copyFromView) { String root = directory.substring(0, directory.length() - directory.split(File.separator)[directory.split(File.separator).length - 1] .length()); ArrayList<String> list = new ArrayList<String>(); for (String s : new File(root).list()) { if (new File(root + File.separator + s).isDirectory() && !s.equals(directory.split(File.separator)[directory .split(File.separator).length - 1])) { list.add(s); } } if (list.size() > 0) { String[] s = list.toArray(new String[0]); sort(s); JList sims = new JList(s); JScrollPane scroll = new JScrollPane(); scroll.setMinimumSize(new Dimension(260, 200)); scroll.setPreferredSize(new Dimension(276, 132)); scroll.setViewportView(sims); sims.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); sims.setSelectedIndex(0); Object[] options = { "Select", "Cancel" }; int value = JOptionPane.showOptionDialog(biosim.frame(), scroll, "Select View", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { int run = 0; String[] lists = new File(directory).list(); for (int i = 0; i < lists.length; i++) { if (!(new File(directory + File.separator + lists[i]).isDirectory()) && lists[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = lists[i].charAt(lists[i].length() - j) + end; } if (end.equals(".tsd")) { if (lists[i].contains("run-")) { int tempNum = Integer.parseInt(lists[i].substring(4, lists[i] .length() - end.length())); if (tempNum > run) { run = tempNum; } } } } } String[] list1 = new File(root + File.separator + sims.getSelectedValue()) .list(); Properties p = new Properties(); try { p.load(new FileInputStream(new File(directory + File.separator + ".lrn"))); } catch (Exception e1) { } for (int i = 0; i < list1.length; i++) { if (!(new File(root + File.separator + sims.getSelectedValue() + File.separator + list1[i]).isDirectory()) && list1[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list1[i].charAt(list1[i].length() - j) + end; } if (end.equals(".tsd")) { try { String last = "run-" + (run + 1) + ".tsd"; FileOutputStream out = new FileOutputStream(new File(directory + File.separator + last)); FileInputStream in = new FileInputStream(new File(root + File.separator + sims.getSelectedValue() + File.separator + list1[i])); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); p.setProperty(last, sims.getSelectedValue() + File.separator + list1[i]); run++; } catch (Exception e1) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to copy from view.", "Error", JOptionPane.ERROR_MESSAGE); } } } } try { String[] ss = p.values().toArray(new String[0]); sort(ss); files.setListData(ss); p .store(new FileOutputStream(new File(directory + File.separator + ".lrn")), "Learn File Data"); } catch (Exception e1) { } } } else { JOptionPane .showMessageDialog(biosim.frame(), "There are no views to copy data from.", "Error", JOptionPane.ERROR_MESSAGE); } } else if (e.getSource() == importFile) { String importFile = Buttons.browse(biosim.frame(), null, null, JFileChooser.FILES_AND_DIRECTORIES, "Import"); if (importFile != null && !importFile.trim().equals("")) { importFile = importFile.trim(); int run = 0; String[] list = new File(directory).list(); for (int i = 0; i < list.length; i++) { if (!(new File(directory + File.separator + list[i]).isDirectory()) && list[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list[i].charAt(list[i].length() - j) + end; } if (end.equals(".tsd")) { if (list[i].contains("run-")) { int tempNum = Integer.parseInt(list[i].substring(4, list[i] .length() - end.length())); if (tempNum > run) { run = tempNum; } } } } } if (new File(importFile).isDirectory()) { String[] list1 = new File(importFile).list(); Properties p = new Properties(); try { p.load(new FileInputStream(new File(directory + File.separator + ".lrn"))); } catch (Exception e1) { } for (int i = 0; i < list1.length; i++) { if (!(new File(importFile + File.separator + list1[i]).isDirectory()) && list1[i].length() > 4) { String end = ""; for (int j = 1; j < 5; j++) { end = list1[i].charAt(list1[i].length() - j) + end; } if (end.equals(".tsd")) { try { String last = "run-" + (run + 1) + ".tsd"; FileOutputStream out = new FileOutputStream(new File(directory + File.separator + last)); FileInputStream in = new FileInputStream(new File(importFile + File.separator + list1[i])); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); p.setProperty(last, importFile + File.separator + list1[i]); run++; } catch (Exception e1) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } } } try { String[] s = p.values().toArray(new String[0]); sort(s); files.setListData(s); p .store(new FileOutputStream(new File(directory + File.separator + ".lrn")), "Learn File Data"); } catch (Exception e1) { } } else { if (importFile.length() > 3 && importFile.substring(importFile.length() - 4, importFile.length()) .equals(".tsd")) { try { String end = "run-" + (run + 1) + ".tsd"; FileOutputStream out = new FileOutputStream(new File(directory + File.separator + end)); FileInputStream in = new FileInputStream(new File(importFile)); int read = in.read(); while (read != -1) { out.write(read); read = in.read(); } in.close(); out.close(); Properties p = new Properties(); p.load(new FileInputStream( new File(directory + File.separator + ".lrn"))); p.setProperty(end, importFile); p.store(new FileOutputStream(new File(directory + File.separator + ".lrn")), "Learn File Data"); String[] s = p.values().toArray(new String[0]); sort(s); files.setListData(s); } catch (Exception e1) { JOptionPane.showMessageDialog(biosim.frame(), "Unable to import file.", "Error", JOptionPane.ERROR_MESSAGE); } } else { JOptionPane.showMessageDialog(biosim.frame(), "Unable to import file." + "\nImported file must be a tsd file.", "Error", JOptionPane.ERROR_MESSAGE); } } } biosim .refreshLearn(directory.split(File.separator)[directory.split(File.separator).length - 1]); } else if (e.getSource() == addData) { } else if (e.getSource() == removeData) { } else if (e.getSource() == editData) { } else if (e.getSource() == copyData) { } } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } private void sort(String[] sort) { int i, j; String index; for (i = 1; i < sort.length; i++) { index = sort[i]; j = i; while ((j > 0) && sort[j - 1].compareToIgnoreCase(index) > 0) { sort[j] = sort[j - 1]; j = j - 1; } sort[j] = index; } } }
package radlab.rain.workload.rubbos; import java.io.IOException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import radlab.rain.IScoreboard; /** * The 'Search' operation. * * @author <a href="mailto:marco.guazzone@gmail.com">Marco Guazzone</a> */ public class SearchOperation extends RubbosOperation { public SearchOperation(boolean interactive, IScoreboard scoreboard) { super(interactive, scoreboard); this._operationName = "Search"; this._operationIndex = RubbosGenerator.SEARCH_OP; } @Override public void execute() throws Throwable { //StringBuilder response = null; //URIBuilder uri = new URIBuilder(this.getGenerator().getSearchURL()); //uri.setParameter("type", ""); //uri.setParameter("search", ""); //uri.setParameter("page", Integer.toString(0)); //uri.setParameter("nbOfStories", Integer.toString(0)); //HttpGet reqGet = new HttpGet(uri.build()); //response = this.getHttpTransport().fetch(reqGet); //this.trace(reqGet.getURI().toString()); StringBuilder response = this.getHttpTransport().fetchUrl(this.getGenerator().getSearchURL()); this.trace(this.getGenerator().getSearchURL()); if (!this.getGenerator().checkHttpResponse(response.toString())) { //this.getLogger().severe("Problems in performing request to URL: " + reqGet.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "). Server response: " + response); //throw new IOException("Problems in performing request to URL: " + reqGet.getURI() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")"); this.getLogger().severe("Problems in performing request to URL: " + this.getGenerator().getSearchURL() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + "). Server response: " + response); throw new IOException("Problems in performing request to URL: " + this.getGenerator().getSearchURL() + " (HTTP status code: " + this.getHttpTransport().getStatusCode() + ")"); } // Save session data this.getSessionState().setLastResponse(response.toString()); this.setFailed(!this.getUtility().checkRubbosResponse(response.toString())); } }
package embedding; //Java import java.io.File; import java.io.IOException; import java.io.OutputStream; //JAXP import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.DocumentBuilder; // DOM import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; // Avalon import org.apache.avalon.framework.ExceptionUtil; import org.apache.avalon.framework.logger.ConsoleLogger; import org.apache.avalon.framework.logger.Logger; //FOP import org.apache.fop.apps.Driver; import org.apache.fop.apps.FOPException; /** * This class demonstrates the conversion of a DOM Document to PDF * using JAXP (XSLT) and FOP (XSL-FO). */ public class ExampleDOM2PDF { /** xsl-fo namespace URI */ protected static String foNS = "http: /** * Converts a DOM Document to a PDF file using FOP. * @param xslfoDoc the DOM Document * @param pdf the target PDF file * @throws IOException In case of an I/O problem * @throws FOPException In case of a FOP problem */ public void convertDOM2PDF(Document xslfoDoc, File pdf) throws IOException, FOPException { //Construct driver Driver driver = new Driver(); //Setup logger Logger logger = new ConsoleLogger(ConsoleLogger.LEVEL_INFO); driver.enableLogging(logger); driver.initialize(); //Setup Renderer (output format) driver.setRenderer(Driver.RENDER_PDF); //Setup output OutputStream out = new java.io.FileOutputStream(pdf); out = new java.io.BufferedOutputStream(out); try { driver.setOutputStream(out); driver.render(xslfoDoc); } finally { out.close(); } } /** * Main method. * @param args command-line arguments */ public static void main(String[] args) { try { System.out.println("FOP ExampleDOM2PDF\n"); //Setup directories File baseDir = new File("."); File outDir = new File(baseDir, "out"); outDir.mkdirs(); //Setup output file File pdffile = new File(outDir, "ResultDOM2PDF.pdf"); System.out.println("PDF Output File: " + pdffile); System.out.println(); // Create a sample XSL-FO DOM document Document foDoc = null; Element root = null, ele1 = null, ele2 = null, ele3 = null; Text elementText = null; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); foDoc = db.newDocument(); root = foDoc.createElementNS(foNS, "fo:root"); foDoc.appendChild(root); ele1 = foDoc.createElementNS(foNS, "fo:layout-master-set"); root.appendChild(ele1); ele2 = foDoc.createElementNS(foNS, "fo:simple-page-master"); ele1.appendChild(ele2); ele2.setAttributeNS(null, "master-name", "letter"); ele2.setAttributeNS(null, "page-height", "11in"); ele2.setAttributeNS(null, "page-width", "8.5in"); ele2.setAttributeNS(null, "margin-top", "1in"); ele2.setAttributeNS(null, "margin-bottom", "1in"); ele2.setAttributeNS(null, "margin-left", "1in"); ele2.setAttributeNS(null, "margin-right", "1in"); ele3 = foDoc.createElementNS(foNS, "fo:region-body"); ele2.appendChild(ele3); ele1 = foDoc.createElementNS(foNS, "fo:page-sequence"); root.appendChild(ele1); ele1.setAttributeNS(null, "master-reference", "letter"); ele2 = foDoc.createElementNS(foNS, "fo:flow"); ele1.appendChild(ele2); ele2.setAttributeNS(null, "flow-name", "xsl-region-body"); addElement(ele2, "fo:block", "Hello World!"); ExampleDOM2PDF app = new ExampleDOM2PDF(); app.convertDOM2PDF(foDoc, pdffile); System.out.println("Success!"); } catch (Exception e) { System.err.println(ExceptionUtil.printStackTrace(e)); System.exit(-1); } } /** * Adds an element to the DOM. * @param parent parent node to attach the new element to * @param newNodeName name of the new node * @param textVal content of the element */ protected static void addElement(Node parent, String newNodeName, String textVal) { if (textVal == null) { return; } // use only with text nodes Element newElement = parent.getOwnerDocument().createElementNS( foNS, newNodeName); Text elementText = parent.getOwnerDocument().createTextNode(textVal); newElement.appendChild(elementText); parent.appendChild(newElement); } }
package jsettlers.graphics.swing; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; /** * This class loads the jogl libs * * @author michael */ public class JoglLoader { private static final String[] LIBNAMES = new String[] { "gluegen-rt", "jogl_desktop", "jogl_es1", "jogl_es2", "nativewindow_awt", "newt" }; private static Queue<File> loadFiles = null; public static void loadLibs() { if (loadFiles == null) { loadFiles = new ConcurrentLinkedQueue<File>(); for (String libname : LIBNAMES) { try { loadSingleLib(libname); } catch (IOException e) { System.err.println("Problems loading lib " + libname); } } } } private static void loadSingleLib(String file) throws IOException { File temporary = File.createTempFile("jogl-" + file, "." + getExtension()); String filename = getLibDir() + System.mapLibraryName(file); InputStream in = JoglLoader.class.getResourceAsStream(filename); if (in == null) { throw new IOException("could not load lib: not found"); } FileOutputStream out = new FileOutputStream(temporary); int n; byte buffer[] = new byte[4096]; while ((n = in.read(buffer)) != -1) { out.write(buffer, 0, n); } in.close(); out.close(); System.load(temporary.getAbsolutePath()); temporary.deleteOnExit(); } private static String getLibDir() { return "../../../libs/lib/"; } private static String getExtension() { return ".so"; } // private static void addUnloadTask() { // Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { // public void run() { // }, "jogl cleanup task")); }
package lv.ctco.cukesrest.api; import com.google.inject.Inject; import com.google.inject.Singleton; import com.jayway.restassured.http.ContentType; import cucumber.api.java.en.Given; import lv.ctco.cukesrest.CukesOptions; import lv.ctco.cukesrest.internal.RequestSpecificationFacade; import lv.ctco.cukesrest.internal.context.GlobalWorldFacade; import lv.ctco.cukesrest.internal.resources.ResourceFileReader; import java.io.File; @Singleton public class GivenSteps { @Inject RequestSpecificationFacade facade; @Inject GlobalWorldFacade world; @Inject ResourceFileReader reader; @Given("^let variable \"(.+)\" equal to \"(.+)\"$") public void var_assigned(String varName, String value) { this.world.put(varName, value); } @Given("^value assertions are case-insensitive$") public void val_caseInsensitive() { this.world.put("case-insensitive", "true"); } @Given("^baseUri is \"(.+)\"$") public void base_Uri_Is(String url) { this.facade.baseUri(url); } @Given("^resources root is \"(.+)\"$") public void resources_Root_Is(String url) { var_assigned(CukesOptions.RESOURCES_ROOT, url); } @Given("^proxy settings are \"(http|https): public void proxy(String scheme, String host, Integer port) { this.facade.proxy(scheme, host, port); } @Given("^param \"(.+)\" \"(.+)\"$") public void param(String key, String value) { this.facade.param(key, value); } @Given("^accept \"(.+)\" mediaTypes$") public void accept(String mediaTypes) { this.facade.accept(mediaTypes); } @Given("^accept mediaType is JSON$") public void acceptJson() { this.facade.accept(ContentType.JSON.toString()); } @Given("^content type is JSON$") public void content_Type_Json() { this.facade.contentType(ContentType.JSON.toString()); } @Given("^content type is \"(.+)\"$") public void content_Type(String contentType) { this.facade.contentType(contentType); } @Given("^queryParam \"(.+)\" is \"(.+)\"$") public void query_Param(String key, String value) { this.facade.queryParam(key, value); } @Given("^formParam \"(.+)\" is \"(.+)\"$") public void form_Param(String key, String value) { this.facade.formParam(key, value); } @Given("^request body \"(.+)\"$") public void request_Body(String body) { this.facade.body(body); } @Given("^request body:$") public void request_Body_From_Object(String body) { this.facade.body(body); } @Given("^request body from file \"(.+)\"$") public void request_Body_From_File(String path) { this.facade.body(this.reader.read(path)); } @Given("^request body is a multipart file \"(.+)\"$") public void request_Body_Is_A_Multipart_File(String path) { this.facade.multiPart(new File(path)); } @Given("^session ID is \"(.+)\"$") public void session_ID(String sessionId) { this.facade.sessionId(sessionId); } @Given("^session ID \"(.+)\" with value \"(.+)\"$") public void session_ID_With_Value(String sessionId, String value) { this.facade.sessionId(sessionId, value); } @Given("^cookie \"(.+)\" with value \"(.+)\"$") public void cookie_With_Value(String cookie, String value) { this.facade.cookie(cookie, value); } @Given("^header ([^\"]+) with value \"(.+)\"$") public void header_With_Value(String name, String value) { this.facade.header(name, value); } @Given("^username \"(.+)\" and password \"(.+)\"$") public void authentication(String username, String password) { this.facade.authentication(username, password); } @Given("^authentication type is \"(.+)\"$") public void authentication(String authenticationType) { this.facade.authenticationType(authenticationType); } }
package fi.evident.dalesbred; import fi.evident.dalesbred.dialects.PostgreSQLDialect; import fi.evident.dalesbred.results.ResultSetProcessor; import fi.evident.dalesbred.results.RowMapper; import org.jetbrains.annotations.NotNull; import org.junit.Rule; import org.junit.Test; import java.math.BigDecimal; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.util.Map; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.*; public class DatabaseTest { private final Database db = TestDatabaseProvider.createTestDatabase(); @Rule public final TransactionalTestsRule rule = new TransactionalTestsRule(db); @Test public void meaningfulToString() { db.setDefaultIsolation(Isolation.READ_UNCOMMITTED); db.setAllowImplicitTransactions(true); assertEquals("Database [dialect=" + new PostgreSQLDialect().toString() + ", allowImplicitTransactions=true, defaultIsolation=READ_UNCOMMITTED, defaultPropagation=DEFAULT]", db.toString()); } @Test public void primitivesQueries() { assertThat(db.findUniqueInt("select 42"), is(42)); assertThat(db.findUnique(Integer.class, "select 42"), is(42)); assertThat(db.findUnique(Long.class, "select 42::int8"), is(42L)); assertThat(db.findUnique(Float.class, "select 42.0::float4"), is(42.0f)); assertThat(db.findUnique(Double.class, "select 42.0::float8"), is(42.0)); assertThat(db.findUnique(String.class, "select 'foo'"), is("foo")); assertThat(db.findUnique(Boolean.class, "select true"), is(true)); assertThat(db.findUnique(Boolean.class, "select null::boolean"), is(nullValue())); } @Test public void bigNumbers() { assertThat(db.findUnique(BigDecimal.class, "select 4242242848428484848484848"), is(new BigDecimal("4242242848428484848484848"))); } @Test public void autoDetectingTypes() { assertThat(db.findUnique(Object.class, "select 42"), is((Object) 42)); assertThat(db.findUnique(Object.class, "select 'foo'"), is((Object) "foo")); assertThat(db.findUnique(Object.class, "select true"), is((Object) true)); } @Test public void constructorRowMapping() { db.update("drop table if exists department"); db.update("create table department (id serial primary key, name varchar(64) not null)"); int id1 = db.findUniqueInt("insert into department (name) values ('foo') returning id"); int id2 = db.findUniqueInt("insert into department (name) values ('bar') returning id"); List<Department> departments = db.findAll(Department.class, "select id, name from department"); assertThat(departments.size(), is(2)); assertThat(departments.get(0).id, is(id1)); assertThat(departments.get(0).name, is("foo")); assertThat(departments.get(1).id, is(id2)); assertThat(departments.get(1).name, is("bar")); } @Test public void map() { db.update("drop table if exists department"); db.update("create table department (id serial primary key, name varchar(64) not null)"); int id1 = db.findUnique(Integer.class, "insert into department (name) values ('foo') returning id"); int id2 = db.findUnique(Integer.class, "insert into department (name) values ('bar') returning id"); Map<Integer, String> map = db.findMap(Integer.class, String.class, "select id, name from department"); assertThat(map.size(), is(2)); assertThat(map.get(id1), is("foo")); assertThat(map.get(id2), is("bar")); } @Test public void enumsAsPrimitives() { db.update("drop type if exists mood cascade"); db.update("create type mood as enum ('SAD', 'HAPPY')"); db.findUnique(Mood.class, "select 'SAD'::mood").getClass(); assertThat(db.findUnique(Mood.class, "select 'SAD'::mood"), is(Mood.SAD)); assertThat(db.findUnique(Mood.class, "select null::mood"), is(nullValue())); } @Test public void enumsAsConstructorParameters() { db.update("drop type if exists mood cascade"); db.update("create type mood as enum ('SAD', 'HAPPY')"); db.update("drop table if exists movie"); db.update("create table movie (name varchar(64) primary key, mood mood not null)"); db.update("insert into movie (name, mood) values (?, ?)", "Amélie", Mood.HAPPY); Movie movie = db.findUnique(Movie.class, "select name, mood from movie"); assertThat(movie.name, is("Amélie")); assertThat(movie.mood, is(Mood.HAPPY)); } @Test public void findUnique_singleResult() { assertThat(db.findUnique(Integer.class, "select 42"), is(42)); } @Test(expected = NonUniqueResultException.class) public void findUnique_nonUniqueResult() { db.findUnique(Integer.class, "select generate_series(1, 2)"); } @Test(expected = NonUniqueResultException.class) public void findUnique_emptyResult() { db.findUnique(Integer.class, "select generate_series(0,-1)"); } @Test public void findUniqueOrNull_singleResult() { assertThat(db.findUniqueOrNull(Integer.class, "select 42"), is(42)); } @Test(expected = NonUniqueResultException.class) public void findUniqueOrNull_nonUniqueResult() { db.findUniqueOrNull(Integer.class, "select generate_series(1, 2)"); } @Test public void findUniqueOrNull_emptyResult() { assertThat(db.findUniqueOrNull(Integer.class, "select generate_series(0,-1)"), is(nullValue())); } @Test public void rowMapper() { RowMapper<Integer> squaringRowMapper = new RowMapper<Integer>() { @NotNull @Override public Integer mapRow(@NotNull ResultSet resultSet) throws SQLException { int value = resultSet.getInt(1); return value*value; } }; assertThat(db.findAll(squaringRowMapper, "select generate_series(1, 3)"), is(asList(1, 4, 9))); assertThat(db.findUnique(squaringRowMapper, "select 7"), is(49)); assertThat(db.findUniqueOrNull(squaringRowMapper, "select generate_series(0,-1)"), is(nullValue())); } @Test public void customResultProcessor() { ResultSetProcessor<Integer> rowCounter = new ResultSetProcessor<Integer>() { @Override public Integer process(@NotNull ResultSet resultSet) throws SQLException { int rows = 0; while (resultSet.next()) rows++; return rows; } }; assertThat(db.executeQuery(rowCounter, "select generate_series(1, 10)"), is(10)); } @Test(expected = DatabaseException.class) public void creatingDatabaseWithJndiDataSourceThrowsExceptionWhenContextIsNotConfigured() { Database.forJndiDataSource("foo"); } @Test public void isolation() { assertSame(Isolation.DEFAULT, db.getDefaultIsolation()); db.setDefaultIsolation(Isolation.REPEATABLE_READ); assertSame(Isolation.REPEATABLE_READ, db.getDefaultIsolation()); } @Test public void propagation() { assertSame(Propagation.DEFAULT, db.getDefaultPropagation()); db.setDefaultPropagation(Propagation.NESTED); assertSame(Propagation.NESTED, db.getDefaultPropagation()); } @Test public void implicitTransactions() { db.setAllowImplicitTransactions(false); assertFalse(db.isAllowImplicitTransactions()); db.setAllowImplicitTransactions(true); assertTrue(db.isAllowImplicitTransactions()); } enum Mood { SAD, HAPPY } public static class Department { final int id; final String name; @Reflective public Department(int id, String name) { this.id = id; this.name = name; } } public static class Movie { final String name; final Mood mood; @Reflective public Movie(String name, Mood mood) { this.name = name; this.mood = mood; } } }
package com.continuuity.api.data; /** * This is the abstract base class for all data sets. A data set is an * implementation of a data pattern that can be reused across programs and * applications. The life cycle of a data set is as follows: * <li>An application declares the data sets that its programs use.</li> * <li>When the application is deployed, the DataSet object is created and * its configure() method is called. This method returns a specification * that contains all information needed to instantiate the data set at * runtime.</li> * <li>At runtime (in a flow or procedure) the data set is instantiated * by dependency injection using @UseDataSet annotation. This uses the * constructor of the the data set that takes the above specification * as argument. It is important that the data set is instantiated through * the context: This also makes sure that the data fabric runtime is * properly injected into the data set. * </li> * <li>Hence every DataSet must implement a configure() method and a * constructor from DataSetSpecification.</li> */ public abstract class DataSet { // the name of the data set (instance) private final String name; /** * Get the name of this data set. * @return the name of the data set */ public final String getName() { return this.name; } /** * Base constructor that only sets the name of the data set. * @param name the name of the data set */ public DataSet(String name) { this.name = name; } /** * Constructor to instantiate the data set at runtime. * @param spec the data set specification for this data set */ public DataSet(DataSetSpecification spec) { this(spec.getName()); } /** * This method is called at deployment time and must return the complete * specification that is needed to instantiate the data set at runtime * (@see #DataSet(DataSetSpecification)). * @return a data set spec that has all meta data needed for runtime * instantiation */ public abstract DataSetSpecification configure(); /** * This method is called at runtime to release all resources that the dataset may have acquired. * After this is called, it is guaranteed that this instance of the dataset will not be used any more. * The base implementation is to do nothing. */ public void close() { } }
package com.veil.ai; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.ObjectStreamException; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.math.MathUtils; import com.veil.game.element.DynamicEntity; import com.veil.game.element.Player; public class BattleProfile { private class EnemyLog implements Serializable { private static final long serialVersionUID = -8664985101334101023L; private Player player; private DynamicEntity entity; private boolean isMainAgent; private int maxHP, lastHP; private int startFrame, lifetime; //The first frame of profiling is 0 private List<Integer> distSq; private List<Integer> hitPlayerFrame; private List<Integer> damagedFrame; private boolean shouldNotUpdate, updated; public EnemyLog(Player player, DynamicEntity entity, boolean isMainAgent, int startFrame){ this.player = player; this.entity = entity; this.isMainAgent = isMainAgent; maxHP = entity.getBaseHP(); lastHP = entity.getBaseHP(); this.startFrame = startFrame; this.lifetime = 0; distSq = new LinkedList<Integer>(); hitPlayerFrame = new LinkedList<Integer>(); damagedFrame = new LinkedList<Integer>(); shouldNotUpdate = false; } public void onPreupdate(){ if(shouldNotUpdate) return; lifetime++; updated = true; } public void postUpdateCheck(){ if(shouldNotUpdate) return; distSq.add( (int)player.getCenteredPositionCorrespondToRF().dst2(entity.getCenteredPositionCorrespondToRF()) ); if(lastHP > entity.getBaseHP()){ lastHP = entity.getBaseHP(); damagedFrame.add(lifetime-1); } if(!updated){ shouldNotUpdate = true; entity = null; } } public void hitPlayer(){ hitPlayerFrame.add(lifetime-1); } public void clearUpdateFlag(){ updated = false; } public boolean everCloseToPlayer(int distance){ distance = distance*distance; for(Integer d : distSq){ if(d <= distance) return true; } return false; } private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.writeBoolean(isMainAgent); out.writeInt(startFrame); out.writeInt(maxHP); out.writeInt(lifetime); out.writeInt(distSq.size()); for(int data : distSq){ out.writeInt(data); } out.writeInt(hitPlayerFrame.size()); for(int data : hitPlayerFrame){ out.writeInt(data); } if(isMainAgent){ out.writeInt(lastHP); out.writeInt(damagedFrame.size()); for(int data : damagedFrame){ out.writeInt(data); } } } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { isMainAgent = in.readBoolean(); startFrame = in.readInt(); maxHP = in.readInt(); lifetime = in.readInt(); distSq = new LinkedList<Integer>(); int listSize = in.readInt(); for(int i=0; i<listSize; i++){ distSq.add(in.readInt()); } hitPlayerFrame = new LinkedList<Integer>(); listSize = in.readInt(); for(int i=0; i<listSize; i++){ hitPlayerFrame.add(in.readInt()); } if(isMainAgent){ lastHP = in.readInt(); damagedFrame = new LinkedList<Integer>(); listSize = in.readInt(); for(int i=0; i<listSize; i++){ damagedFrame.add(in.readInt()); } } } @SuppressWarnings("unused") private void readObjectNoData() throws ObjectStreamException { isMainAgent = false; startFrame = -1; hitPlayerFrame = new LinkedList<Integer>(); } @Override public String toString(){ StringBuilder strb = new StringBuilder(); if(entity != null){ strb.append(entity.identifier); strb.append(" (").append(entity.hashCode()).append(") "); }else{ strb.append("entity "); } strb.append("start "+startFrame+" lifetime "+lifetime+" "); strb.append("[ "); for(int i : hitPlayerFrame){ strb.append(i).append(" "); } strb.append("]"); if(isMainAgent){ strb.append("{ "); for(int i : damagedFrame){ strb.append(i).append(" "); } strb.append("}"); } return strb.toString(); } } public static BattleProfile instance = new BattleProfile(); private boolean startProfile; private String name; private boolean unbeatable, playerDead; private int playerRemainingHP = -1; //This field may be inaccurate (if battle is skipped during the frame the player loses HP) private HashMap<Integer,EnemyLog> logs = new HashMap<Integer,EnemyLog>(); private int frameCounter = 0; public BattleProfile(){ saveAndReset(null,BattleSessionEndReason.InitialSession,null); } /** * Save previous profile (if available) to target directory and reset with new profile name ready to be updated */ public void saveAndReset(String newProfileName, BattleSessionEndReason endReason, FileHandle dir){ if(name != null && dir != null){ unbeatable = endReason == BattleSessionEndReason.Unbeatable; playerDead = endReason == BattleSessionEndReason.PlayerDead; //Should save profile before resetting String filename = name+".txt"; if(unbeatable) filename = "_"+filename; if(playerDead) filename = "-"+filename; save(dir.child(filename)); } startProfile = false; name = newProfileName; unbeatable = false; playerDead = false; playerRemainingHP = -1; logs.clear(); frameCounter = 0; } public boolean isStart(){ return startProfile; } //Update profile with pre-update snapshot public void preUpdate(LevelSnapshot snapshot){ if(!startProfile){ if(snapshot.playerOnFloor){ startProfile = true; }else{ return; } } for(EnemyLog log : logs.values()){ log.clearUpdateFlag(); } if(snapshot.enemy != null){ if(!logs.containsKey(snapshot.enemy.hashCode())){ logs.put(snapshot.enemy.hashCode(), new EnemyLog(snapshot.player, snapshot.enemy, true, frameCounter)); } logs.get(snapshot.enemy.hashCode()).onPreupdate(); } for(DynamicEntity dyn : snapshot.tempRect.keySet()){ if(!logs.containsKey(dyn.hashCode())){ logs.put(dyn.hashCode(), new EnemyLog(snapshot.player, dyn, false, frameCounter)); } logs.get(dyn.hashCode()).onPreupdate(); } playerRemainingHP = snapshot.player.getBaseHP(); } public void hitPlayer(DynamicEntity attacker){ if(!startProfile) return; logs.get(attacker.hashCode()).hitPlayer(); } public void postUpdate(){ if(!startProfile) return; for(EnemyLog log : logs.values()){ log.postUpdateCheck(); } frameCounter++; } public String getName(){ return name; } public void print(){ System.out.println(name); for(EnemyLog log : logs.values()){ System.out.println(log); } System.out.println(">>>>>>>>>>>>>>>>>>>>>>"); } public void save(FileHandle fh){ ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = null; try { out = new ObjectOutputStream(bos); out.writeBoolean(unbeatable); out.writeBoolean(playerDead); out.writeInt(playerRemainingHP); out.writeInt(logs.size()); for(EnemyLog log : logs.values()){ out.writeObject(log); } out.close(); bos.close(); byte[] bytes = bos.toByteArray(); fh.writeBytes(bytes, false); } catch (IOException e) { e.printStackTrace(); } } /** * Calculate necessary parameters required to evaluate battle profile from existing profiles in specified directory. <br/> * Return length-3 array <br/> * [0] = (int) Battle duration (used to set battle timelimit for AI) <br/> * [1] = (float) Good miss rate (AI must perform at similar rate) <br/> * [2] = (float) Good remaining HP percentage (AI must perform at similar percentage) <br/> * if battleDuration is higher than 0, the value is used when calculating remaining HP instead of average battle duration in [0]. */ public static float[] calculateEvaluationParameter(FileHandle dir, int relevantRange, int battleDurationCap, HashSet<String> durationExlusion, HashSet<String> missRateExclusion, HashSet<String> hpExclusion){ float[] params = new float[3]; int sampleSize = calculateTotalBattleDuration(dir, params, durationExlusion); params[0] /= sampleSize; sampleSize = calculateMissRate(dir, params, relevantRange, missRateExclusion); params[1] /= sampleSize; sampleSize = calculateHPPercent(dir, params, battleDurationCap > 0 ? battleDurationCap : (int)params[0], hpExclusion); params[2] /= sampleSize; return params; } private static int calculateTotalBattleDuration(FileHandle dir, float[] out, HashSet<String> exclusionList){ int sampleSize = 0; for(FileHandle fh : dir.list()){ if(!fh.isDirectory()){ if(exclusionList != null && exclusionList.contains(fh.nameWithoutExtension())){ continue; } //System.out.println(fh.nameWithoutExtension()+" "+fh.pathWithoutExtension()); BattleProfile profile = new BattleProfile(); profile.load(fh); if(profile.isValidForBattleDuration()){ out[0] += profile.getBattleDuration(); sampleSize++; if(EvaluationApp.durationTable != null) EvaluationApp.durationTable.setCell(fh, ""+profile.getBattleDuration()); }else{ //System.out.println("time invalid"); if(EvaluationApp.durationTable != null) EvaluationApp.durationTable.setCell(fh, "invalid"); } }else{ sampleSize += calculateTotalBattleDuration(fh, out, exclusionList); } } return sampleSize; } private static int calculateMissRate(FileHandle dir, float[] out, int relevantRange, HashSet<String> exclusionList){ int sampleSize = 0; for(FileHandle fh : dir.list()){ if(!fh.isDirectory()){ if(exclusionList != null && exclusionList.contains(fh.nameWithoutExtension())){ continue; } EvaluationApp.fhTemp = fh; //System.out.println(fh.nameWithoutExtension()+" "+fh.pathWithoutExtension()); BattleProfile profile = new BattleProfile(); profile.load(fh); float missRate = profile.getMissRate(relevantRange, -1); //Use 0 if no close up, will this cause bias? out[1] += (missRate < 0 ? 0 : missRate); sampleSize++; }else{ sampleSize += calculateMissRate(fh, out, relevantRange, exclusionList); } } return sampleSize; } private static int calculateHPPercent(FileHandle dir, float[] out, int averageTimelimit, HashSet<String> exclusionList){ int sampleSize = 0; for(FileHandle fh : dir.list()){ if(!fh.isDirectory()){ if(exclusionList != null && exclusionList.contains(fh.nameWithoutExtension())){ continue; } //System.out.println(fh.nameWithoutExtension()+" "+fh.pathWithoutExtension()); BattleProfile profile = new BattleProfile(); profile.load(fh); if(profile.isValidForRemainingHP()){ out[2] += profile.getRemainingHPPercent(averageTimelimit); sampleSize++; if(EvaluationApp.hpPercentTable != null) EvaluationApp.hpPercentTable.setCell(fh, ""+profile.getRemainingHPPercent(averageTimelimit)); }else{ if(EvaluationApp.hpPercentTable != null) EvaluationApp.hpPercentTable.setCell(fh, "invalid"); } }else{ sampleSize += calculateHPPercent(fh, out, averageTimelimit, exclusionList); } } return sampleSize; } /** * Load battle profile. Not everything is saved, so it is expected that only methods below are invoked on the loaded version * of profile */ public void load(FileHandle fh){ byte[] data = fh.readBytes(); ByteArrayInputStream bis = new ByteArrayInputStream(data); ObjectInput in = null; try { name = fh.nameWithoutExtension(); in = new ObjectInputStream(bis); unbeatable = in.readBoolean(); playerDead = in.readBoolean(); playerRemainingHP = in.readInt(); int remaining = in.readInt(); logs.clear(); while(remaining > 0){ logs.put(remaining, (EnemyLog)in.readObject()); remaining } } catch (Exception e) { //e.printStackTrace(); //System.err.println("Error loading battle profile "+fh.nameWithoutExtension()); System.err.println(fh.nameWithoutExtension()); } } public boolean isValidForBattleDuration(){ if(unbeatable) return false; if(playerDead){ for(EnemyLog log : logs.values()){ if(log.isMainAgent){ return log.lastHP < log.maxHP; } } } return true; } public boolean everCloseUp(int relevantRange, int battleDurationCap){ return getMissRate(relevantRange, battleDurationCap) > -1; } private boolean isValidForRemainingHP(){ return isValidForBattleDuration(); } public int getBattleDuration(){ int timelimit = 0; EnemyLog mainAgent = null; for(EnemyLog log : logs.values()){ int afterLastFrame = log.startFrame+log.lifetime; if(afterLastFrame > timelimit){ timelimit = afterLastFrame; } if(log.isMainAgent){ mainAgent = log; } } if(playerDead && mainAgent.lastHP > 0){ //Extrapolate timelimit based on main agent's remaining HP in case player is dead int damageDealtToEnemy = mainAgent.maxHP - mainAgent.lastHP; timelimit = (int)(timelimit * mainAgent.maxHP * 1f / damageDealtToEnemy); } //System.out.println("time "+name+" "+timelimit); return timelimit; } public float getMissRate(int relevantRange, int battleDurationCap){ //Filter only entities that ever gets close to player HashSet<EnemyLog> set = new HashSet<EnemyLog>(); set.addAll(logs.values()); set.removeIf(log -> !log.everCloseToPlayer(relevantRange)); if(set.size() == 0){ //System.out.println("\thit 0 of 0 (Never close up)"); if(EvaluationApp.missCountTable != null) EvaluationApp.missCountTable.setCell(EvaluationApp.fhTemp, "NoCloseUp"); return -1; } float sumMissRate = 0; for(EnemyLog log : set){ //Calculate miss rate against individual entity int maxHitCount = MathUtils.ceil(log.lifetime / 60f); // ceil(EntityLifetime/InvulFrame) int hitCount = 0; int lastHitFrame = -1; Collections.sort(log.hitPlayerFrame); for(int frame : log.hitPlayerFrame){ if(battleDurationCap > 0 && frame > battleDurationCap) break; if(lastHitFrame < 0 || frame - lastHitFrame >= 60){ hitCount++; lastHitFrame = frame; } } //System.out.println("\thit "+hitCount+" of "+maxHitCount); sumMissRate += hitCount*1f/maxHitCount; } if(EvaluationApp.missCountTable != null) EvaluationApp.missCountTable.setCell(EvaluationApp.fhTemp, ""+sumMissRate/set.size()); //System.out.println("miss "+name+" "+set.size()); return Math.min(1, sumMissRate/set.size()); } public float getRemainingHPPercent(int timeLimit){ for(EnemyLog log : logs.values()){ if(log.isMainAgent){ int remainingHp = log.maxHP; for(int damagedFrame : log.damagedFrame){ if(timeLimit > 0 && damagedFrame >= timeLimit){ break; } remainingHp } if(remainingHp < 0){ remainingHp = 0; } //System.out.println("hp "+name+" "+remainingHp+"("+log.lastHP+") /"+log.maxHP); return remainingHp*1f/log.maxHP; } } //The only case here is player takes too long to land first strike on enemy return 1; } public int getBulletCount(){ return logs.size()-1; } }
package net.sf.flatpack; import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.function.Supplier; import net.sf.flatpack.structure.ColumnMetaData; import net.sf.flatpack.structure.Row; import net.sf.flatpack.util.FPConstants; import net.sf.flatpack.util.FPStringUtils; import net.sf.flatpack.util.ParserUtils; import net.sf.flatpack.xml.MetaData; public class RowRecord implements Record { private final Row row; private final boolean columnCaseSensitive; private final MetaData metaData; private Properties pzConvertProps = null; private final boolean strictNumericParse; private final boolean upperCase; private final boolean lowerCase; private final boolean nullEmptyString; public RowRecord(final Row row, final MetaData metaData, final boolean columnCaseSensitive, final Properties pzConvertProps, final boolean strictNumericParse, final boolean upperCase, final boolean lowerCase, final boolean nullEmptyString) { super(); this.row = row; this.metaData = metaData; this.columnCaseSensitive = columnCaseSensitive; this.pzConvertProps = pzConvertProps; this.strictNumericParse = strictNumericParse; this.upperCase = upperCase; this.lowerCase = lowerCase; this.nullEmptyString = nullEmptyString; } @Override public boolean isRecordID(final String recordID) { String rowID = row.getMdkey(); if (rowID == null) { rowID = FPConstants.DETAIL_ID; } return rowID.equals(recordID); } @Override public int getRowNo() { return row.getRowNumber(); } @Override public boolean isRowEmpty() { return row.isEmpty(); } @Override public boolean contains(final String column) { final Iterator<ColumnMetaData> cmds = ParserUtils.getColumnMetaData(row.getMdkey(), metaData).iterator(); while (cmds.hasNext()) { final ColumnMetaData cmd = cmds.next(); if (cmd.getColName().equalsIgnoreCase(column)) { return true; } } return false; } /* * (non-Javadoc) * * @see net.sf.flatpack.DataSet#getColumns() */ @Override public String[] getColumns() { ColumnMetaData column = null; String[] array = null; if (/* columnMD != null || */metaData != null) { final List cmds = metaData.getColumnsNames(); array = new String[cmds.size()]; for (int i = 0; i < cmds.size(); i++) { column = (ColumnMetaData) cmds.get(i); array[i] = column.getColName(); } } return array; } /* * (non-Javadoc) * * @see net.sf.flatpack.DataSet#getColumns(java.lang.String) */ @Override public String[] getColumns(final String recordID) { String[] array = null; if (metaData != null) { final List cmds = ParserUtils.getColumnMetaData(recordID, metaData); array = new String[cmds.size()]; for (int i = 0; i < cmds.size(); i++) { final ColumnMetaData column = (ColumnMetaData) cmds.get(i); array[i] = column.getColName(); } } return array; } @Override public Date getDate(final String column, final SimpleDateFormat sdf, final Supplier<Date> defaultSupplier) throws ParseException { final Date d = getDate(column, sdf); if (d == null) { return defaultSupplier.get(); } return d; } @Override public Date getDate(final String column, final Supplier<Date> defaultSupplier) throws ParseException { final Date d = getDate(column); if (d == null) { return defaultSupplier.get(); } return d; } @Override public Date getDate(final String column) throws ParseException { return getDate(column, new SimpleDateFormat("yyyyMMdd")); } @Override public Date getDate(final String column, final SimpleDateFormat sdf) throws ParseException { final String s = getStringValue(column); if (FPStringUtils.isBlank(s)) { // don't do the parse on empties return null; } return sdf.parse(s); } @Override public LocalDate getLocalDate(final String column, final String dateFormat, final Supplier<LocalDate> defaultSupplier) throws ParseException { final LocalDate d = getLocalDate(column, dateFormat); if (d == null) { return defaultSupplier.get(); } return d; } @Override public LocalDate getLocalDate(final String column, final Supplier<LocalDate> defaultSupplier) throws ParseException { final LocalDate d = getLocalDate(column); if (d == null) { return defaultSupplier.get(); } return d; } @Override public LocalDate getLocalDate(final String column) throws ParseException { return getLocalDate(column, "yyyy-mm-dd"); } @Override public LocalDate getLocalDate(final String column, final String dateFormat) throws ParseException { final String s = getStringValue(column); if (FPStringUtils.isBlank(s)) { // don't do the parse on empties return null; } return LocalDate.parse(s, DateTimeFormatter.ofPattern(dateFormat)); } @Override public double getDouble(final String column, final Supplier<Double> defaultSupplier) { final String s = getStringValue(column); if (FPStringUtils.isBlank(s)) { return defaultSupplier.get(); } return getDouble(column); } @Override public double getDouble(final String column) { final StringBuilder newString = new StringBuilder(); final String s = getStringValue(column); if (!strictNumericParse) { newString.append(ParserUtils.stripNonDoubleChars(s)); } else { newString.append(s); } return Double.parseDouble(newString.toString()); } @Override public int getInt(final String column, final Supplier<Integer> defaultSupplier) { final String s = getStringValue(column); if (FPStringUtils.isBlank(s)) { return defaultSupplier.get(); } return getInt(column); } @Override public int getInt(final String column) { final String s = getStringValue(column); if (!strictNumericParse) { return Integer.parseInt(ParserUtils.stripNonLongChars(s)); } return Integer.parseInt(s); } @Override public long getLong(final String column, final Supplier<Long> defaultSupplier) { final String s = getStringValue(column); if (FPStringUtils.isBlank(s)) { return defaultSupplier.get(); } return getLong(column); } @Override public long getLong(final String column) { final String s = getStringValue(column); if (!strictNumericParse) { return Long.parseLong(ParserUtils.stripNonLongChars(s)); } return Long.parseLong(s); } private String getStringValue(final String column) { return row.getValue(ParserUtils.getColumnIndex(row.getMdkey(), metaData, column, columnCaseSensitive)); } @Override public Object getObject(final String column, final Class<?> classToConvertTo) { final String s = getStringValue(column); return ParserUtils.runPzConverter(pzConvertProps, s, classToConvertTo); } @Override public BigDecimal getBigDecimal(final String column, final Supplier<BigDecimal> defaultSupplier) { final BigDecimal bd = getBigDecimal(column); if (bd == null) { return defaultSupplier.get(); } return bd; } @Override public BigDecimal getBigDecimal(final String column) { String s = getStringValue(column); if (FPStringUtils.isBlank(s)) { // don't do the parse on empties return null; } s = s.replace(",", "").trim(); if (FPStringUtils.isBlank(s)) { // don't do the parse on empties return null; } return new BigDecimal(s); } @Override public String getString(final String column, final Supplier<String> defaultSupplier) { final String s = getString(column); if (FPStringUtils.isBlank(s)) { return defaultSupplier.get(); } return s; } @Override public String getString(final String column) { String s = getStringValue(column); if (nullEmptyString && FPStringUtils.isBlank(s)) { s = null; } else if (upperCase) { s = s.toUpperCase(Locale.getDefault()); } else if (lowerCase) { s = s.toLowerCase(Locale.getDefault()); } // return value as how it is in the file return s; } @Override public String getRawData() { return row.getRawData(); } }
package org.radargun.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.radargun.stages.GenerateChartStage; /** * @author Mircea.Markus@jboss.com */ public class Utils { private static Log log = LogFactory.getLog(Utils.class); public static final String PLUGINS_DIR = "plugins"; private static final NumberFormat NF = new DecimalFormat(" private static final NumberFormat MEM_FMT = new DecimalFormat(" public static String getMillisDurationString(long millis) { long secs = millis / 1000; long mins = secs / 60; long remainingSecs = secs % 60; if (mins > 0) { return String.format("%d mins %d secs", mins, remainingSecs); } else { return String.format("%.3f secs", millis / 1000.0); } } public static String getNanosDurationString(long nanos) { return getMillisDurationString(nanos / 1000000); } public static String fileName2Config(String fileName) { int index = fileName.indexOf('.'); if (index > 0) { fileName = fileName.substring(0, index); index = fileName.indexOf(File.separator); if (index > 0) { fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1); } } return fileName; } public static String printMemoryFootprint(boolean before) { Runtime run = Runtime.getRuntime(); String memoryInfo = "Memory - free: " + kbString(run.freeMemory()) + " - max:" + kbString(run.maxMemory()) + "- total:" + kbString(run.totalMemory()); if (before) { return "Before executing clear, memory looks like this: " + memoryInfo; } else { return "After executing cleanup, memory looks like this: " + memoryInfo; } } public static long getFreeMemoryKb() { return kb(Runtime.getRuntime().freeMemory()); } private static String format(long bytes) { double val = bytes; int mag = 0; while (val > 1024) { val = val / 1024; mag++; } String formatted = MEM_FMT.format(val); switch (mag) { case 0: return formatted + " bytes"; case 1: return formatted + " kb"; case 2: return formatted + " Mb"; case 3: return formatted + " Gb"; default: return "WTF?"; } } public static long kb(long memBytes) { return memBytes / 1024; } public static String kbString(long memBytes) { return MEM_FMT.format(memBytes / 1024) + " kb"; } public static String memString(long mem, String suffix) { return MEM_FMT.format(mem) + " " + suffix; } public static String memString(long memInBytes) { return format(memInBytes); } public static URLClassLoader buildProductSpecificClassLoader(String productName, ClassLoader parent) throws Exception { log.trace("Using smart class loading"); File libFolder = new File(PLUGINS_DIR + File.separator + productName + File.separator + "lib"); List<URL> jars = new ArrayList<URL>(); if (!libFolder.isDirectory()) { log.info("Could not find lib directory: " + libFolder.getAbsolutePath()); } else { String[] jarsSrt = libFolder.list(new FilenameFilter() { public boolean accept(File dir, String name) { String fileName = name.toUpperCase(); if (fileName.endsWith("JAR") || fileName.toUpperCase().endsWith("ZIP")) { if (log.isTraceEnabled()) { log.trace("Accepting file: " + fileName); } return true; } else { if (log.isTraceEnabled()) { log.trace("Rejecting file: " + fileName); } return false; } } }); for (String file : jarsSrt) { File aJar = new File(libFolder, file); if (!aJar.exists() || !aJar.isFile()) { throw new IllegalStateException(); } jars.add(aJar.toURI().toURL()); } } File confDir = new File(PLUGINS_DIR + File.separator + productName + File.separator + "conf/"); jars.add(confDir.toURI().toURL()); return new URLClassLoader(jars.toArray(new URL[jars.size()]), parent); } public static String getCacheProviderProperty(String productName, String propertyName) { File file = new File(PLUGINS_DIR + File.separator + productName + File.separator + "conf" + File.separator + "cacheprovider.properties"); if (!file.exists()) { log.warn("Could not find a plugin descriptor : " + file); return null; } Properties properties = new Properties(); FileInputStream inStream = null; try { inStream = new FileInputStream(file); properties.load(inStream); return properties.getProperty(propertyName); } catch (IOException e) { throw new RuntimeException(e); } finally { if (inStream != null) try { inStream.close(); } catch (IOException e) { log.warn(e); } } } public static String getCacheWrapperFqnClass(String productName) { return getCacheProviderProperty(productName, "org.radargun.wrapper"); } public static File createOrReplaceFile(File parentDir, String actualFileName) throws IOException { File outputFile = new File(parentDir, actualFileName); backupFile(outputFile); if (outputFile.createNewFile()) { log.info("Successfully created report file:" + outputFile.getAbsolutePath()); } else { log.warn("Failed to create the report file!"); } return outputFile; } public static void backupFile(File outputFile) { if (outputFile.exists()) { int lastIndexOfDot = outputFile.getName().lastIndexOf('.'); String extension = lastIndexOfDot > 0 ? outputFile.getName().substring(lastIndexOfDot) : ""; File old = new File(outputFile.getParentFile(), "old"); if (!old.exists()) { if (old.mkdirs()) { log.warn("Issues whilst creating dir: " + old); } } String fileName = outputFile.getName() + ".old." + System.currentTimeMillis() + extension; File newFile = new File(old, fileName); log.info("A file named: '" + outputFile.getAbsolutePath() + "' already exists. Moving it to '" + newFile + "'"); if (!outputFile.renameTo(newFile)) { log.warn("Could not rename!!!"); } } } public static String prettyPrintTime(long time, TimeUnit unit) { return prettyPrintMillis(unit.toMillis(time)); } /** * Prints a time for display * * @param millis time in millis * @return the time, represented as millis, seconds, minutes or hours as appropriate, with suffix */ public static String prettyPrintMillis(long millis) { if (millis < 1000) return millis + " milliseconds"; NumberFormat nf = NumberFormat.getNumberInstance(); nf.setMaximumFractionDigits(2); double toPrint = ((double) millis) / 1000; if (toPrint < 300) { return nf.format(toPrint) + " seconds"; } toPrint = toPrint / 60; if (toPrint < 120) { return nf.format(toPrint) + " minutes"; } toPrint = toPrint / 60; return nf.format(toPrint) + " hours"; } public static void seep(long duration) { try { Thread.sleep(duration); } catch (InterruptedException e) { throw new IllegalStateException(e); } } public static String numberFormat(int i) { return NF.format(i); } public static String numberFormat(double d) { return NF.format(d); } public static Object instantiate(String name) { try { return Class.forName(name).newInstance(); } catch (Exception e) { throw new IllegalStateException(e); } } public static long string2Millis(String duration) { long durationMillis; try { durationMillis = Long.parseLong(duration); } catch (NumberFormatException nfe) { int indexOfM = duration.toUpperCase().indexOf('M'); if (indexOfM > 0) { durationMillis = Long.parseLong(duration.substring(0, indexOfM)); durationMillis = TimeUnit.MINUTES.toMillis(durationMillis); } else { int indexOfS = duration.toUpperCase().indexOf('S'); if (indexOfS > 0) { durationMillis = Long.parseLong(duration.substring(0, indexOfS)); durationMillis = TimeUnit.SECONDS.toMillis(durationMillis); } else { throw new IllegalArgumentException("Cannot parse string: '" + duration + "' Supported formats: '321321' (millis), '3m' (minutes) or '75s' (seconds)"); } } } return durationMillis; } public static void createOutputFile(String fileName, String fileContent) throws IOException { createOutputFile(fileName, fileContent, true); } public static void createOutputFile(String fileName, String fileContent, boolean doBackup) throws IOException { File parentDir = new File(GenerateChartStage.REPORTS); if (!parentDir.exists() && !parentDir.mkdirs()) { // Try again if (!parentDir.exists() && !parentDir.mkdirs()) { log.error("Directory '" + parentDir.getAbsolutePath() + "' could not be created"); /* * If parentDir is <code>null</code>, the file will still be created in the current * directory */ parentDir = null; } } File reportFile = new File(parentDir, fileName); if (!reportFile.exists() || doBackup) { reportFile = Utils.createOrReplaceFile(parentDir, fileName); } if (!reportFile.exists()) { throw new IllegalStateException(reportFile.getAbsolutePath() + " was deleted? Not allowed to delete report file during test run!"); } else { log.info("Report file '" + reportFile.getAbsolutePath() + "' created"); } FileWriter writer = null; try { writer = new FileWriter(reportFile, !doBackup); writer.append(fileContent); } finally { if (writer != null) writer.close(); } } /** * * Parse a string containing method names and String parameters. Multiple method names and * parameters are separated by a ';'. Method names and parameters are separated by a ':'. * * @return a Map with the method name as the key, and the String parameter as the value, or an * empty Map if <code>parameterString</code> is <code>null</code> */ public static Map<String, String> parseParams(String parameterString) { Map<String, String> result = new HashMap<String, String>(); if (parameterString != null) { for (String propAndValue : parameterString.split(";")) { String[] values = propAndValue.split(":"); result.put(values[0].trim(), values[1].trim()); } } return result; } /** * * Invoke a public method with a String argument on an Object * * @param object * the Object where the method is invoked * @param properties * a Map where the public method name is the key, and the String parameter is the value * @return the modified Object, or <code>null</code> if the field can't be changed */ public static Object invokeMethodWithString(Object object, Map<String, String> properties) { Class<? extends Object> clazz = object.getClass(); for (Entry<String, String> entry : properties.entrySet()) { try { Method method = clazz.getDeclaredMethod(entry.getKey(), String.class); method.invoke(object, entry.getValue()); } catch (Exception e) { log.error("Error invoking method named " + entry.getKey() + " with value " + entry.getValue(), e); return null; } } return object; } }
package hudson.scm; import hudson.model.AbstractProject; import hudson.model.Descriptor.FormException; import hudson.util.DescriptorList; import hudson.Extension; import java.util.List; import org.kohsuke.stapler.StaplerRequest; import javax.servlet.ServletException; /** * List of all installed SCMs. * * @author Kohsuke Kawaguchi */ public class SCMS { /** * List of all installed SCMs. * @deprecated as of 1.286 * Use {@link SCM#all()} for read access and {@link Extension} for registration. */ @Deprecated public static final List<SCMDescriptor<?>> SCMS = (List)new DescriptorList<SCM>(SCM.class); /** * Parses {@link SCM} configuration from the submitted form. * * @param target * The project for which this SCM is configured to. */ @SuppressWarnings("deprecation") public static SCM parseSCM(StaplerRequest req, AbstractProject target) throws FormException, ServletException { SCM scm = SCM.all().newInstanceFromRadioList(req.getSubmittedForm().getJSONObject("scm")); if (scm == null) { scm = new NullSCM(); // JENKINS-36043 workaround for AbstractMultiBranchProject.submit } scm.getDescriptor().generation++; return scm; } /** * @deprecated as of 1.294 * Use {@link #parseSCM(StaplerRequest, AbstractProject)} and pass in the caller's project type. */ @Deprecated public static SCM parseSCM(StaplerRequest req) throws FormException, ServletException { return parseSCM(req,null); } }
package hudson; import junit.framework.TestCase; import java.util.Map; import java.util.HashMap; import java.util.Locale; import java.io.ByteArrayOutputStream; import java.io.File; import hudson.util.StreamTaskListener; /** * @author Kohsuke Kawaguchi */ public class UtilTest extends TestCase { public void testReplaceMacro() { Map<String,String> m = new HashMap<String,String>(); m.put("A","a"); m.put("AA","aa"); m.put("B","B"); m.put("DOLLAR", "$"); m.put("ENCLOSED", "a${A}"); // longest match assertEquals("aa",Util.replaceMacro("$AA",m)); // invalid keys are ignored assertEquals("$AAB",Util.replaceMacro("$AAB",m)); assertEquals("aaB",Util.replaceMacro("${AA}B",m)); assertEquals("${AAB}",Util.replaceMacro("${AAB}",m)); // $ escaping assertEquals("asd$${AA}dd", Util.replaceMacro("asd$$$${AA}dd",m)); assertEquals("$", Util.replaceMacro("$$",m)); assertEquals("$$", Util.replaceMacro("$$$$",m)); // test that more complex scenarios work assertEquals("/a/B/aa", Util.replaceMacro("/$A/$B/$AA",m)); assertEquals("a-aa", Util.replaceMacro("$A-$AA",m)); assertEquals("/a/foo/can/B/you-believe_aa~it?", Util.replaceMacro("/$A/foo/can/$B/you-believe_$AA~it?",m)); assertEquals("$$aa$Ba${A}$it", Util.replaceMacro("$$$DOLLAR${AA}$$B${ENCLOSED}$it",m)); } public void testTimeSpanString() { // Check that amounts less than 365 days are not rounded up to a whole year. // In the previous implementation there were 360 days in a year. // We're still working on the assumption that a month is 30 days, so there will // be 5 days at the end of the year that will be "12 months" but not "1 year". // First check 359 days. assertEquals(Messages.Util_month(11), Util.getTimeSpanString(31017600000L)); // And 362 days. assertEquals(Messages.Util_month(12), Util.getTimeSpanString(31276800000L)); // 11.25 years - Check that if the first unit has 2 or more digits, a second unit isn't used. assertEquals(Messages.Util_year(11), Util.getTimeSpanString(354780000000L)); // 9.25 years - Check that if the first unit has only 1 digit, a second unit is used. assertEquals(Messages.Util_year(9)+ " " + Messages.Util_month(3), Util.getTimeSpanString(291708000000L)); // 67 seconds assertEquals(Messages.Util_minute(1) + " " + Messages.Util_second(7), Util.getTimeSpanString(67000L)); // 17 seconds - Check that times less than a minute only use seconds. assertEquals(Messages.Util_second(17), Util.getTimeSpanString(17000L)); // 1712ms -> 1.7sec assertEquals(Messages.Util_second(1.7), Util.getTimeSpanString(1712L)); // 171ms -> 0.17sec assertEquals(Messages.Util_second(0.17), Util.getTimeSpanString(171L)); // 101ms -> 0.10sec assertEquals(Messages.Util_second(0.1), Util.getTimeSpanString(101L)); // 17ms assertEquals(Messages.Util_millisecond(17), Util.getTimeSpanString(17L)); // 1ms assertEquals(Messages.Util_millisecond(1), Util.getTimeSpanString(1L)); // Test HUDSON-2843 (locale with comma as fraction separator got exception for <10 sec) Locale saveLocale = Locale.getDefault(); Locale.setDefault(Locale.GERMANY); try { // Just verifying no exception is thrown: assertNotNull("German locale", Util.getTimeSpanString(1234)); assertNotNull("German locale <1 sec", Util.getTimeSpanString(123)); } finally { Locale.setDefault(saveLocale); } } /** * Test that Strings that contain spaces are correctly URL encoded. */ public void testEncodeSpaces() { final String urlWithSpaces = "http://hudson/job/Hudson Job"; String encoded = Util.encode(urlWithSpaces); assertEquals(encoded, "http://hudson/job/Hudson%20Job"); } /** * Test the rawEncode() method. */ public void testRawEncode() { String[] data = { // Alternating raw,encoded "abcdefghijklmnopqrstuvwxyz", "abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "01234567890!@$&*()-_=+',.", "01234567890!@$&*()-_=+',.", " \"#%/:;<>?", "%20%22%23%25%2F%3A%3B%3C%3E%3F", "[\\]^`{|}~", "%5B%5C%5D%5E%60%7B%7C%7D%7E", "d\u00E9velopp\u00E9s", "d%C3%A9velopp%C3%A9s", }; for (int i = 0; i < data.length; i += 2) { assertEquals("test " + i, data[i + 1], Util.rawEncode(data[i])); } } /** * Test the tryParseNumber() method. */ public void testTryParseNumber() { assertEquals("Successful parse did not return the parsed value", 20, Util.tryParseNumber("20", 10).intValue()); assertEquals("Failed parse did not return the default value", 10, Util.tryParseNumber("ss", 10).intValue()); assertEquals("Parsing empty string did not return the default value", 10, Util.tryParseNumber("", 10).intValue()); assertEquals("Parsing null string did not return the default value", 10, Util.tryParseNumber(null, 10).intValue()); } public void testSymlink() throws Exception { if (Functions.isWindows()) return; ByteArrayOutputStream baos = new ByteArrayOutputStream(); StreamTaskListener l = new StreamTaskListener(baos); File d = Util.createTempDir(); try { new FilePath(new File(d, "a")).touch(0); Util.createSymlink(d,"a","x", l); assertEquals("a",Util.resolveSymlink(new File(d,"x"),l)); // test a long name StringBuilder buf = new StringBuilder(768); for( int i=0; i<768; i++) buf.append('0'+(i%10)); Util.createSymlink(d,buf.toString(),"x", l); String log = baos.toString(); if (log.length() > 0) { System.err.println("log output: " + log); if (s.contains("ln failed: 78" /*ENAMETOOLONG*/)) { buf.setLength(0); // Try again with shorter name for this system for( int i=0; i<254; i++) buf.append('0'+(i%10)); Util.createSymlink(d,buf.toString(),"x", l); } } assertEquals(buf.toString(),Util.resolveSymlink(new File(d,"x"),l)); } finally { Util.deleteRecursive(d); } } }
package main.chess.controller; import main.chess.structure.*; import java.util.ArrayList; public class MoveGenerator { public ArrayList<Square> generateMoves(Board board, Square start) { ArrayList<Square> moves = new ArrayList<>(); Piece p = start.getPiece(); if(p.getType() == Type.PAWN) return pawnIterate(board, start); Group g = p.getType().getGroup(); int[] signature = {0,0}; for (Translation t : g) { if(checkTranslation(board, t, start,signature)){ moves.add(board.translateSquare(start ,t)); } } return moves; } /** * * @param t the translation being checked * @param start the square the piece is starting from * @param board the board the game is being played on * @param signature the signature of the translation * @return whether that translation is valid on that board * @see Translation#getSignature() */ public boolean checkTranslation(Board board, Translation t, Square start, int[] signature) { if (start.translate(t).inBounds()) { Square s = board.translateSquare(start, t); if (!t.isSignature(signature) || start.getPiece().getType() == Type.KNIGHT) { if (s.isOccupied()) { signature[0] = t.getSignature()[0]; signature[1] = t.getSignature()[1]; if (s.getPiece().getColor() != start.getPiece().getColor()) { return true; } } else { return true; } } } return false; } /** * * @param start the square the pawn is starting on * @param board the board the game is being played on * @return the list of squares the pawn can move to * @see MoveGenerator#checkPawnTranslation(Board, Square,Translation) * @see MoveGenerator#getEnPassanteMoves(Board, Square) */ public ArrayList<Square> pawnIterate(Board board, Square start){ ArrayList<Square> moves = new ArrayList<>(); for (Translation t : Type.PAWN.getGroup()) { if(!start.translate(t).inBounds()) continue; if(checkPawnTranslation(board, start, t)){ moves.add(board.translateSquare(start, t)); } } moves.addAll(getEnPassanteMoves(board, start)); return moves; } /** * TODO: MAKE THIS PAWN TRANSLATION CHECKING METHOD EASIER TO UNDERSTAND! */ /** * * @param board the board the game is being played on * @param start the square the pawn is starting from * @param t the translation being checked * @return whether that translation is valid for the pawn */ public boolean checkPawnTranslation(Board board, Square start, Translation t){ Square end = board.translateSquare(start, t); // row pawn is initialized int startingRow = start.getPiece().getColor() == Color.WHITE? 1 : 6; // correct y signature of given pawn int y = start.getPiece().getColor() == Color.WHITE? 1 : -1; // not correct direction if(t.getSignature()[1] != y) return false; // if 1 square move if(t.getY() == 1 * y){ // if also lateral if(t.getX() == 1 || t.getX() == -1){ if(!end.isOccupied()) return false; if(end.getPiece().getColor() == start.getPiece().getColor()) return false; }else{ if(end.isOccupied()) return false; } } // if 2 square move if(t.getY() == 2 * y){ if(start.getRow() != startingRow) return false; if(end.isOccupied()) return false; } return true; } /** * * @param start the square which the pawn in question is on * @param last the last move on the board * @return whether the pawn on the given square can en passante * */ public boolean canEnPassante(Square start, Move last){ // if first move of game if(last == null) return false; // if last move is not a pawn move if(last.getEnd().getPiece().getType() != Type.PAWN) return false; // if last pawn move and current pawn move are not adjacent if(Math.abs(start.getCol() - last.getStart().getCol()) != 1) return false; int row = start.getRow(); // if pawn in question is white if(start.getPiece().getColor() == Color.WHITE){ // white pawn must be on 5th rank if(row != 4) return false; // black pawn must have moved 2 squares from 7th to 5th rank if(last.getStart().getRow() != 6 || last.getEnd().getRow() != 4) return false; }else{ // black pawn must be on 4th rank if(row != 3) return false; // white pawn must have moved 2 squares from 2nd to 4th rank if(last.getStart().getRow() != 1 || last.getEnd().getRow() != 3) return false; } // if all conditions passed return true; } /** * * @param start the square which the pawn is on * @param board the board the game is being played on * @return the square the pawn can en passante to. Null is returned * if the pawn cannot en passante. * @see MoveGenerator#canEnPassante(Square, Move) */ public ArrayList<Square> getEnPassanteMoves(Board board, Square start){ ArrayList<Square> enpassantMoves = new ArrayList<>(); Move last = board.getLastMove(); // if can en passant if(canEnPassante(start, last)){ // move on to the same column int endCol = last.getEnd().getCol(); // move between last pawn move start row and end row int endRow = (last.getStart().getRow() + last.getEnd().getRow())/2; enpassantMoves.add(board.getSquare(endRow, endCol)); } return enpassantMoves; } }
// SiteSystemState.java package ed.lang.python; import org.python.expose.*; import org.python.Version; import org.python.expose.generate.*; import java.io.*; import java.util.*; import org.python.core.*; import ed.appserver.*; import ed.log.*; import ed.js.*; import ed.log.*; import ed.js.engine.*; import ed.lang.*; import ed.util.*; import ed.appserver.jxp.*; /** * 10gen-specific Python system state. * * Originally this was going to be a subclass of PySystemState, but * this lead to exciting breakage in calls to sys.getEnviron(). It * seems that Python introspects for method calls on whatever object * is used as Py.getSystemState(), and this introspection isn't very * smart -- specifically, it doesn't pick up on methods inherited from * a superclass. As a result, sys.getEnviron() can't be found and * everything breaks. This even happens in modules like os. * * This is our new approach. Instead of re-wrapping all those method * calls, we just store a PySystemState and hopefully do all the * 10gen-specific munging here. Our caller should pass * SiteSystemState.getPyState() to Py.setSystemState as needed. */ public class SiteSystemState { static final boolean DEBUG = Boolean.getBoolean( "DEBUG.SITESYSTEMSTATE" ); SiteSystemState( AppContext ac , PyObject newGlobals , Scope s){ pyState = new PySystemState(); globals = newGlobals; _scope = s; _context = ac; setupModules(); ensureMetaPathHook( pyState , s ); replaceOutput(); ensurePath( Config.get().getProperty("ED_HOME", "/data/ed")+"/src/main/ed/lang/python/lib" , 0 ); // Careful -- this is static PySystemState.builtins. We modify // it once to intercept imports for all sites. TrackImport // then looks at the execution environment and figures out which site // needs to track the import. PyObject builtins = PySystemState.builtins; PyObject pyImport = builtins.__finditem__( "__import__" ); if( ! ( pyImport instanceof TrackImport ) ) builtins.__setitem__( "__import__" , new TrackImport( pyImport ) ); } public PySystemState getPyState(){ return pyState; } void ensurePath( String myPath ){ ensurePath( myPath , -1 ); } void ensurePath( String myPath , int location ){ for ( Object o : pyState.path ) if ( o.toString().equals( myPath ) ) return; if( location == -1 ) pyState.path.append( Py.newString( myPath ) ); else pyState.path.insert( location , Py.newString( myPath ) ); } /** * Set up module interception code. * * We replace sys.modules with a subclass of PyDictionary so we * can intercept calls to import and flush old versions of modules * when needed. */ public void setupModules(){ if( ! ( pyState.modules instanceof PythonModuleTracker ) ){ if( pyState.modules instanceof PyStringMap) pyState.modules = new PythonModuleTracker( (PyStringMap)pyState.modules ); else { // You can comment out this exception, it shouldn't // break anything beyond reloading python modules throw new RuntimeException("couldn't intercept modules " + pyState.modules.getClass()); } } String modName = "_10gen".intern(); if( pyState.modules.__finditem__( modName ) == null ){ PyModule xgenMod = new PyModule( modName , globals ); pyState.modules.__setitem__( modName , xgenMod ); } // This allows you to do import sitename // We handle import sitename.foo in the __import__ handler. if( _context != null ){ modName = _context.getName().intern(); if( pyState.modules.__finditem__( modName ) == null ){ PyModule siteMod = new PyModule( modName ); pyState.modules.__setitem__( modName , siteMod ); // Make sure it's not a real package module that can // actually cause imports. This should only happen virtually. siteMod.__dict__.__setitem__( "__path__", Py.None ); } } } private void _checkModules(){ if( ! ( pyState.modules instanceof PythonModuleTracker ) ){ throw new RuntimeException( "i'm not sufficiently set up yet" ); } } /** * Flush old modules that have been imported by Python code but * whose source is now newer. */ public Set<File> flushOld(){ return ((PythonModuleTracker)pyState.modules).flushOld(); } private void ensureMetaPathHook( PySystemState ss , Scope scope ){ boolean foundMetaPath = false; for( Object m : ss.meta_path ){ if( ! ( m instanceof PyObject ) ) continue; PyObject p = (PyObject)m; if( p instanceof ModuleFinder ) return; } ss.meta_path.append( new ModuleFinder( scope ) ); } public void addDependency( PyObject to, PyObject importer ){ _checkModules(); ((PythonModuleTracker)pyState.modules).addDependency( to , importer ); } public AppContext getContext(){ return _context; } /** * Set output to an AppRequest. * * Replace the Python sys.stdout with a file-like object which * actually prints to an AppRequest stream. */ public void replaceOutput(){ PyObject out = pyState.stdout; if ( ! ( out instanceof MyStdoutFile ) ){ pyState.stdout = new MyStdoutFile(); } } @ExposedType(name="_10gen_stdout") public static class MyStdoutFile extends PyFile { static PyType TYPE = Python.exposeClass(MyStdoutFile.class); MyStdoutFile(){ super( TYPE ); } @ExposedMethod public void flush(){} @ExposedMethod public void _10gen_stdout_write( PyObject o ){ if ( o instanceof PyUnicode ){ _10gen_stdout_write(o.__str__().toString()); } else if ( o instanceof PyString ){ _10gen_stdout_write(o.toString()); } else { throw Py.TypeError("write requires a string as its argument"); } } @ExposedMethod(names={"__str__", "__repr__"}) public String toString(){ return "<open file '_10gen.apprequest', mode 'w'>"; } final public void _10gen_stdout_write( String s ){ AppRequest request = AppRequest.getThreadLocal(); if( request == null ) // Log _log.info( s ); else{ request.print( s ); } } public void write( String s ){ _10gen_stdout_write( s ); } } class TrackImport extends PyObject { PyObject _import; TrackImport( PyObject importF ){ _import = importF; } public PyObject __call__( PyObject args[] , String keywords[] ){ int argc = args.length; // Second argument is the dict of globals. Mostly this is helpful // for getting context -- file or module *doing* the import. PyObject globals = ( argc > 1 ) ? args[1] : null; PyObject fromlist = (argc > 3) ? args[3] : null; SiteSystemState sss = Python.getSiteSystemState( null , Scope.getThreadLocal() ); if( DEBUG ){ PySystemState current = Py.getSystemState(); PySystemState sssPy = sss.getPyState(); System.out.println("Overrode import importing. import " + args[0]); System.out.println("globals? " + (globals == null ? "null" : "not null, file " + globals.__finditem__("__file__"))); System.out.println("Scope : " + Scope.getThreadLocal() + " PyState: " + sssPy + " id: " + __builtin__.id(sssPy) + " current id: " + __builtin__.id(current) ); System.out.println("Modules are " + sssPy.modules); } AppContext ac = sss.getContext(); PyObject targetP = args[0]; if( ! ( targetP instanceof PyString ) ) throw new RuntimeException( "first argument to __import__ must be a string, not a "+ targetP.getClass()); String target = targetP.toString(); PyObject siteModule = null; PyObject m = null; if( target.indexOf('.') != -1 ){ String firstPart = target.substring( 0 , target.indexOf('.')); if( ac != null && firstPart.equals( ac.getName() ) ){ siteModule = sss.getPyState().modules.__finditem__( firstPart.intern() ); if( siteModule == null ){ siteModule = new PyModule( firstPart ); sss.getPyState().modules.__setitem__( firstPart.intern() , siteModule ); } target = target.substring( target.indexOf('.') + 1 ); args[0] = new PyString( target ); // Don't recur -- just allow one replacement // This'll still do meta_path stuff, but at least it won't // let you do import sitename.sitename.sitename.foo.. } } PySystemState oldPyState = Py.getSystemState(); try { Py.setSystemState( sss.getPyState() ); m = _import.__call__( args, keywords ); } finally { Py.setSystemState( oldPyState ); } if( globals == null ){ // Only happens (AFAICT) from within Java code. // For example, Jython's codecs.java calls // __builtin__.__import__("encodings"); // Python calls to __import__ provide an empty Python dict. return _finish( target , siteModule , m ); } // gets the module name -- __file__ is the file PyObject importer = globals.__finditem__( "__name__".intern() ); if( importer == null ){ // Globals was empty? Maybe we were called "manually" with // __import__, or maybe import is happening from an exec() // or something. // Let's try to get the place that called the import manually // and hope for the best. PyFrame f = Py.getFrame(); if( f == null ){ // No idea what this means System.err.println("Can't figure out where the call to import " + args[0] + " came from! Import tracking is going to be screwed up!"); return _finish( target, siteModule, m ); } globals = f.f_globals; importer = globals.__finditem__( "__name__".intern() ); if( importer == null ){ // Probably an import from within an exec("foo", {}). // Let's go for broke and try to get the filename from // the PyFrame. This won't be tracked any further, // but that's fine -- at least we'll know which file // needs to be re-exec'ed (e.g. for modjy). // FIXME: exec('import foo', {}) ??? // -- filename is <string> or what? PyTableCode code = f.f_code; // FIXME: wrap just to unwrap later importer = new PyString( code.co_filename ); } if( importer == null ){ // Still?? System.err.println("Totally unable to figure out how import to " + args[0] + " came about. Import tracking is going to be screwed up."); } } // We have to return m, but that might not be the module itself. // If we got "import foo.bar", m = foo, but we want to get // bar.__name__. So we have to search through modules to get to the // innermost. // But if we got "from foo import bar", m = bar, and we don't want // to do anything. Ahh, crappy __import__ semantics.. PyObject innerMod = null; if( fromlist != null && fromlist.__len__() > 0 ) innerMod = m; else { innerMod = m; String [] modNames = target.split("\\."); for( int i = 1; i < modNames.length; ++i ){ innerMod = innerMod.__findattr__( modNames[i].intern() ); } } PyObject to = innerMod.__findattr__( "__name__".intern() ); if( to == null ) return _finish( target , siteModule , m ); // Add a plain old JXP dependency on the file that was imported // Not sure if this is helpful or not // Can't do this right now -- one TrackImport is created for all // PythonJxpSources. FIXME. //addDependency( to.toString() ); // Add a module dependency -- module being imported was imported by // the importing module sss.addDependency( to , importer ); return _finish( target , siteModule , m ); //PythonJxpSource foo = PythonJxpSource.this; } public PyObject _finish( String target , PyObject siteModule , PyObject result ){ if( siteModule == null ) return result; // We got an import for sitename.foo, and result is <module foo>. // siteModule is <module sitename>. target is "foo". int dot = target.indexOf( '.' ); String firstPart = target; if( dot != -1 ) firstPart = target.substring( 0 , dot ); siteModule.__setattr__( firstPart , result ); return siteModule; } } /** * sys.meta_path hook to deal with core/core-modules and local/local-modules * imports. * * Python meta_path hooks are one of many ways a program can * customize how/where modules are loaded. They have two parts, * finders and loaders. This is the finder class, whose API * consists of one method, find_module. * * For more details on the meta_path hooks, check PEP 302. */ @ExposedType(name="_10gen_module_finder") public class ModuleFinder extends PyObject { Scope _scope; JSLibrary _coreModules; JSLibrary _core; JSLibrary _local; JSLibrary _localModules; ModuleFinder( Scope s ){ _scope = s; Object core = s.get( "core" ); if( core instanceof JSLibrary ) _core = (JSLibrary)core; if( core instanceof JSObject ){ Object coreModules = ((JSObject)core).get( "modules" ); if( coreModules instanceof JSLibrary ) _coreModules = (JSLibrary)coreModules; } Object local = s.get( "local" ); if( local instanceof JSLibrary ) _local = (JSLibrary)local; if( local instanceof JSObject ){ Object localModules = ((JSObject)local).get( "modules" ); if( localModules instanceof JSLibrary ) _localModules = (JSLibrary)localModules; } } /** * The sole interface to a finder. We create virtual modules * for "core" and "core.modules", and any relative import * within a core module has to be handled specially. * Specifically, an import for baz from within * core.modules.foo.bar comes out as an import for * core.modules.foo.bar.baz (with __path__ = * ['/data/core-modules/foo/bar']) and if we can't find it, we * try core.modules.foo.baz (simulating core.modules.foo being * on the module search path). * * Alternately, we could just add core.modules.foo to sys.path * when it gets imported, but Geir says we should make it like * JS, which means ugly and painful. * * find_module returns a "loader", as specified by PEP 302. * * @param fullname {PyString} name of the module to find * @param path {PyList} optional; the __path__ of the module */ @ExposedMethod(names={"find_module"}) public PyObject find_module( PyObject args[] , String keywords[] ){ int argc = args.length; assert argc >= 1; assert args[0] instanceof PyString; String modName = args[0].toString(); if( DEBUG ){ System.out.println( "meta_path " + __builtin__.id(this) + " looking for " + modName ); } if( modName.equals("core.modules") ){ return new LibraryModuleLoader( _coreModules ); } if( modName.startsWith("core.modules.") ){ // look for core.modules.foo.bar...baz // and try core.modules.foo.baz // Should confirm that this is from within core.modules.foo.bar... using __path__ int period = modName.indexOf('.') + 1; // core. period = modName.indexOf( '.' , period ) + 1; // modules. int next = modName.indexOf( '.' , period ); // foo if( next != -1 && modName.indexOf( '.' , next + 1 ) != -1 ){ String foo = modName.substring( period , next ); File fooF = new File( _coreModules.getRoot() , foo ); String baz = modName.substring( modName.lastIndexOf( '.' ) + 1 ); File bazF = new File( fooF , baz ); File bazPyF = new File( fooF , baz + ".py" ); if( bazF.exists() || bazPyF.exists() ){ return new RewriteModuleLoader( modName.substring( 0 , next ) + "." + baz ); } } } if( modName.equals("core") ){ return new LibraryModuleLoader( _core ); } if( modName.startsWith("core.") ){ int period = modName.indexOf('.'); String path = modName.substring( period + 1 ); path = path.replaceAll( "\\." , "/" ); return new JSLibraryLoader( _core, path ); } if( DEBUG ){ System.out.println( "meta_path hook didn't match " + modName ); } return Py.None; } } /** * A module loader for core, core.modules, etc. * * Basically this wraps a JSLibrary in such a way that when the * module is loaded, sub-modules can be found by the default * Python search. (Specifically we set the __path__ to the root * of the library.) This obviates the need for putting __init__.py * files throughout corejs and core-modules. */ @ExposedType(name="_10gen_module_library_loader") public class LibraryModuleLoader extends PyObject { JSLibrary _root; LibraryModuleLoader( Object start ){ assert start instanceof JSLibrary; _root = (JSLibrary)start; } public JSLibrary getRoot(){ return _root; } /** * The load_module method specified in PEP 302. * * @param fullname {PyString} the full name of the module * @return PyModule */ @ExposedMethod(names={"load_module"}) public PyModule load_module( String name ){ PyModule mod = imp.addModule( name ); PyObject __path__ = mod.__findattr__( "__path__".intern() ); if( __path__ != null ) return mod; // previously imported mod.__setattr__( "__file__".intern() , new PyString( "<10gen_virtual>" ) ); mod.__setattr__( "__loader__".intern() , this ); PyList pathL = new PyList( PyString.TYPE ); pathL.append( new PyString( _root.getRoot().toString() ) ); mod.__setattr__( "__path__".intern() , pathL ); return mod; } } @ExposedType(name="_10gen_module_js_loader") public class JSLibraryLoader extends PyObject { JSLibrary _root; String _path; public JSLibraryLoader( JSLibrary root , String path ){ _root = root; _path = path; } @ExposedMethod public PyModule load_module( String name ){ PyModule mod = imp.addModule( name ); PyObject __path__ = mod.__findattr__( "__path__".intern() ); if( __path__ != null ) return mod; PyObject pyName = mod.__findattr__( "__name__" ); Object o = _root.getFromPath( _path , true ); PyList pathL = new PyList( ); if( o instanceof JSFileLibrary ){ JSFileLibrary lib = (JSFileLibrary)o; pathL.append( new PyString( lib.getRoot().toString() ) ); } if( o instanceof JSFunction && ((JSFunction)o).isCallable() ){ run( mod , (JSFunction)o ); } mod.__setattr__( "__file__".intern() , new PyString( _root + ":" + _path ) ); mod.__setattr__( "__path__".intern() , pathL ); mod.__setattr__( "__name__".intern() , pyName ); return mod; } public void run( PyModule mod , JSFunction f ){ Scope pref = _scope.getTLPreferred(); Scope s = _scope.child(); s.setGlobal( true ); try { _scope.setTLPreferred( null ); f.call( s ); mod.__dict__ = new PyJSObjectWrapper( s ); } finally { _scope.setTLPreferred( pref ); } } } /** * Module loader that loads a module different than specified. * We use this when a core-module imports a file that exists at the top * of the core-module. This way, core-modules can pretend they're on * sys.path, but without actually being sys.path. (Don't want life to be * too easy for people on our platform.) */ @ExposedType(name="_10gen_module_rewrite_loader") public class RewriteModuleLoader extends PyObject { String _realName; RewriteModuleLoader( String real ){ _realName = real; } /** * The load_module method specified in PEP 302. * * @param fullname {PyString} the full name of the module * @return PyModule */ @ExposedMethod(names={"load_module"}) public PyObject load_module( String name ){ PyObject m = __builtin__.__import__(_realName); String components = _realName.substring( _realName.indexOf('.') + 1 ); while( components.indexOf('.') != -1 ){ String component = components.substring( 0 , components.indexOf('.') ); m = m.__findattr__( component.intern() ); components = components.substring( components.indexOf('.') + 1 ); } m = m.__findattr__( components.intern() ); return m; } } final static Logger _log = Logger.getLogger( "python" ); final public PyObject globals; private PySystemState pyState; private AppContext _context; private Scope _scope; }
package com.izforge.izpack.panels; import java.io.BufferedReader; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.Properties; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableModel; import tigase.db.DBInitException; import tigase.db.RepositoryFactory; import tigase.db.TigaseDBException; import tigase.db.UserAuthRepository; import tigase.db.UserExistsException; import com.izforge.izpack.gui.IzPanelLayout; import com.izforge.izpack.installer.InstallData; import com.izforge.izpack.installer.InstallerFrame; import com.izforge.izpack.installer.IzPanel; import com.izforge.izpack.installer.ResourceManager; import com.izforge.izpack.panels.TigaseDBHelper.MsgTarget; import com.izforge.izpack.panels.TigaseDBHelper.ResultMessage; import com.izforge.izpack.panels.TigaseDBHelper.TigaseDBTask; import com.izforge.izpack.util.Debug; import com.izforge.izpack.util.VariableSubstitutor; /** * The Hello panel class. * * @author <a href="mailto:artur.hefczyc@tigase.org">Artur Hefczyc</a> * @version $Rev$ */ public class TigaseDBCheckPanel extends IzPanel { private static final long serialVersionUID = 1L; private JTable table = null; private Timer delayedTasks = new Timer("DelayedTasks", true); private final InstallData idata; /** * The constructor. * * @param parent The parent. * @param idata The installation data. */ public TigaseDBCheckPanel(InstallerFrame parent, InstallData idata) { super(parent, TigaseInstallerCommon.init(idata), new IzPanelLayout()); this.idata = idata; // The config label. String msg = parent.langpack.getString("TigaseDBCheckPanel.info"); add(createMultiLineLabel(msg)); add(IzPanelLayout.createParagraphGap()); final String[] columnNames = new String[] {"Action", "Result"}; TigaseDBTask[] tasks = TigaseDBHelper.Tasks.getTasksInOrder(); final String[][] data = new String[tasks.length][]; for (int i = 0 ; i < tasks.length ; i++) { TigaseDBTask task = tasks[i]; data[i] = new String[] { task.getDescription(), "" }; } TableModel dataModel = new AbstractTableModel() { // private String[] columnNames = names; // private Object[][] data = datas; public int getColumnCount() { return columnNames.length; } public int getRowCount() { return data.length; } public String getColumnName(int col) { return columnNames[col]; } public Object getValueAt(int row, int col) { return data[row][col]; } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } public boolean isCellEditable(int row, int col) { return false; } public void setValueAt(Object value, int row, int col) { data[row][col] = value.toString(); fireTableCellUpdated(row, col); } }; // The table area which shows the info. table = new JTable(dataModel); // table.setEditable(false); //add(table, NEXT_LINE); JScrollPane scroller = new JScrollPane(table); table.setFillsViewportHeight(true); add(scroller, NEXT_LINE); // At end of layouting we should call the completeLayout // method also they do nothing. getLayoutHelper().completeLayout(); } public void panelActivate() { super.panelActivate(); parent.lockNextButton(); final TigaseDBHelper dbHelper = new TigaseDBHelper(); delayedTasks.schedule(new TimerTask() { public void run() { TigaseDBTask[] tasks = TigaseDBHelper.Tasks.getTasksInOrder(); for (int i = 0 ; i < tasks.length ; i++) { TigaseDBTask task = tasks[i]; final int row = i; MsgTarget msgTarget = new MsgTarget() { public ResultMessage addResultMessage() { return new ResultMessage() { private String fullMsg = ""; public void append(String msg) { fullMsg += msg; SwingUtilities.invokeLater(new Runnable() { public void run() { table.getModel().setValueAt(fullMsg, row, 1); } }); } }; } }; task.execute(dbHelper, idata.getVariables(), msgTarget); } parent.unlockNextButton(); } }, 500); } /** * Indicates wether the panel has been validated or not. * * @return Always true. */ public boolean isValidated() { return true; } } class TigaseDBHelper { private boolean schema_ok = false; private boolean connection_ok = false; private boolean db_ok = false; private String schema_ver_query = TigaseConfigConst.DERBY_GETSCHEMAVER_QUERY; private String res_prefix = ""; private boolean schema_exists = false; static final int DB_CONNEC_POS = 0; static final int DB_EXISTS_POS = 1; static final int DB_SCHEMA_POS = 2; static final int DB_CONVER_POS = 3; enum SQL_LOAD_STATE { INIT, IN_SQL; } private ArrayList<String> loadSQLQueries( String resource, String res_prefix, Properties variables) throws Exception { ArrayList<String> results = new ArrayList<String>(); VariableSubstitutor vs = new VariableSubstitutor(variables); BufferedReader br = new BufferedReader(new InputStreamReader(ResourceManager.getInstance().getInputStream(resource))); String line = null; String sql_query = ""; SQL_LOAD_STATE state = SQL_LOAD_STATE.INIT; while ((line = br.readLine()) != null) { switch (state) { case INIT: if (line.startsWith("-- QUERY START:")) { sql_query = ""; state = SQL_LOAD_STATE.IN_SQL; } if (line.startsWith("-- LOAD SCHEMA:")) { results.addAll(loadSchemaQueries(res_prefix, variables)); } break; case IN_SQL: if (line.startsWith("-- QUERY END:")) { state = SQL_LOAD_STATE.INIT; sql_query = sql_query.trim(); if (sql_query.endsWith(";")) { sql_query = sql_query.substring(0, sql_query.length()-1); } if (sql_query.endsWith(" sql_query = sql_query.substring(0, sql_query.length()-2); } results.add(vs.substitute(sql_query, null)); } if (line.isEmpty() || line.trim().startsWith(" continue; } else { sql_query += " " + line.trim(); } break; default: break; } } br.close(); return results; } private ArrayList<String> loadSchemaQueries( String res_prefix, Properties variables) throws Exception { ArrayList<String> queries = loadSQLQueries(res_prefix + ".schema", res_prefix, variables); queries.addAll(loadSQLQueries(res_prefix + ".sp", res_prefix, variables)); queries.addAll(loadSQLQueries(res_prefix + ".props", res_prefix, variables)); return queries; } public void validateDBConnection(MsgTarget msgTarget) { connection_ok = false; String db_conn = TigaseConfigConst.props.getProperty("root-db-uri"); if (db_conn == null) { msgTarget.addResultMessage().append("Missing DB connection URL"); return; } else { selectDatabase(db_conn); try { Connection conn = DriverManager.getConnection(db_conn); conn.close(); connection_ok = true; msgTarget.addResultMessage().append("Connection OK"); return; } catch (Exception e) { //e.printStackTrace(); msgTarget.addResultMessage().append(e.getMessage()); return; } } } private void selectDatabase(String db_uri) { schema_ver_query = TigaseConfigConst.JDBC_GETSCHEMAVER_QUERY; if (db_uri.startsWith("jdbc:postgresql")) { System.setProperty("jdbc.drivers", TigaseConfigConst.PGSQL_DRIVER); res_prefix = "pgsql"; } if (db_uri.startsWith("jdbc:mysql")) { System.setProperty("jdbc.drivers", TigaseConfigConst.MYSQL_DRIVER); res_prefix = "mysql"; } if (db_uri.startsWith("jdbc:derby")) { System.setProperty("jdbc.drivers", TigaseConfigConst.DERBY_DRIVER); res_prefix = "derby"; schema_ver_query = TigaseConfigConst.DERBY_GETSCHEMAVER_QUERY; } } public void validateDBExists(Properties variables, MsgTarget msgTarget) { if (!connection_ok) { msgTarget.addResultMessage().append("Connection not validated"); return; } db_ok = false; String db_conn = TigaseConfigConst.props.getProperty("--user-db-uri"); if (db_conn == null) { msgTarget.addResultMessage().append("Missing DB connection URL"); return; } else { Connection conn = null; try { conn = DriverManager.getConnection(db_conn); conn.close(); db_ok = true; msgTarget.addResultMessage().append("Exists OK"); return; } catch (Exception e) { ResultMessage resulMessage = msgTarget.addResultMessage(); resulMessage.append("Doesn't exist"); resulMessage.append(", creating..."); db_conn = TigaseConfigConst.props.getProperty("root-db-uri"); try { conn = DriverManager.getConnection(db_conn); ArrayList<String> queries = loadSQLQueries(res_prefix + ".create", res_prefix, variables); for (String query: queries) { Debug.trace("Executing query: " + query); Statement stmt = conn.createStatement(); // Some queries may fail and this is still fine // the user or the database may already exist try { stmt.execute(query); stmt.close(); } catch (Exception ex) { Debug.trace("Query failed: " + ex.getMessage()); } } conn.close(); resulMessage.append(" OK"); db_ok = true; } catch (Exception ex) { resulMessage.append(ex.getMessage()); } } } } public void validateDBConversion(Properties variables, MsgTarget msgTarget) { if (!connection_ok) { msgTarget.addResultMessage().append("Connection not validated"); return; } if (!db_ok) { msgTarget.addResultMessage().append("Database not validated"); return; } if (schema_ok) { msgTarget.addResultMessage().append("Conversion not needed"); return; } if (!schema_exists) { msgTarget.addResultMessage().append("Something wrong, the schema still is not loaded..."); return; } String db_conn = TigaseConfigConst.props.getProperty("root-tigase-db-uri"); try { //conn.close(); ResultMessage resultMessage = msgTarget.addResultMessage(); resultMessage.append("Converting..."); Connection conn = DriverManager.getConnection(db_conn); Statement stmt = conn.createStatement(); ArrayList<String> queries = loadSQLQueries(res_prefix + ".upgrade", res_prefix, variables); for (String query: queries) { Debug.trace("Executing query: " + query); stmt.execute(query); } stmt.close(); conn.close(); schema_ok = true; resultMessage.append(" completed OK"); } catch (Exception ex) { msgTarget.addResultMessage().append("Can't upgrade schema: " + ex.getMessage()); return; } } public void validateDBSchema(Properties variables, MsgTarget msgTarget) { if (!connection_ok) { msgTarget.addResultMessage().append("Connection not validated"); return; } if (!db_ok) { msgTarget.addResultMessage().append("Database not validated"); return; } schema_exists = false; schema_ok = false; Connection conn = null; String db_conn = TigaseConfigConst.props.getProperty("--user-db-uri"); long users = 0; try { conn = DriverManager.getConnection(db_conn); Statement stmt = conn.createStatement(); String query = TigaseConfigConst.JDBC_CHECKUSERTABLE_QUERY; ResultSet rs = stmt.executeQuery(query); if (rs.next()) { users = rs.getLong(1); schema_exists = true; Debug.trace("Schema exists, users: " + users); } query = schema_ver_query; rs = stmt.executeQuery(query); if (rs.next()) { String schema_version = rs.getString(1); if ("4.0".equals(schema_version)) { schema_ok = true; } } } catch (Exception e) { Debug.trace("Exception, posibly schema hasn't been loaded yet: " + e); } if (schema_ok) { msgTarget.addResultMessage().append("Schema OK, accounts number: " + users); return; } if (!schema_exists) { Debug.trace("DB schema doesn't exists, creating one..."); db_conn = TigaseConfigConst.props.getProperty("root-tigase-db-uri"); try { //conn.close(); conn = DriverManager.getConnection(db_conn); Statement stmt = conn.createStatement(); ArrayList<String> queries = loadSchemaQueries(res_prefix, variables); for (String query: queries) { Debug.trace("Executing query: " + query); stmt.execute(query); } stmt.close(); conn.close(); schema_ok = true; msgTarget.addResultMessage().append("New schema loaded OK"); return; } catch (Exception ex) { msgTarget.addResultMessage().append("Can't load schema: " + ex.getMessage()); return; } } else { msgTarget.addResultMessage().append("Old schema, accounts number: " + users); return; } } protected void addXmppAdminAccount(Properties variables, MsgTarget msgTarget) { // part 1, check db preconditions if (!connection_ok) { msgTarget.addResultMessage().append("Connection not validated"); return; } if (!db_ok) { msgTarget.addResultMessage().append("Database not validated"); return; } if (!schema_ok) { msgTarget.addResultMessage().append("Database schema is invalid"); return; } // part 2, acquire reqired fields and validate them Object admins = variables.get("admins"); Set<String> jids = new LinkedHashSet<String>(); if (admins != null) { String[] adminsStr = admins.toString().split(","); for (String adminStr : adminsStr) { String jid = adminStr.trim(); if (jid != null && jid != "") { jids.add(jid); } } } if (jids.size() < 1) { msgTarget.addResultMessage().append("Error: No admin users entered"); return; } Object pwdObj = variables.get("adminsPwd"); if (pwdObj == null) { msgTarget.addResultMessage().append("Error: No admin password enetered"); return; } String pwd = pwdObj.toString(); String className = TigaseConfigConst.props.getProperty("--auth-db"); if (className == null) className = TigaseConfigConst.props.getProperty("--user-db");; String resource = TigaseConfigConst.props.getProperty("--auth-db-uri"); if (resource == null) resource = TigaseConfigConst.props.getProperty("--user-db-uri"); try { UserAuthRepository repo = RepositoryFactory.getAuthRepository( "installer", className, resource, null); for (String jid : jids) { try { repo.addUser(jid, pwd); } catch (UserExistsException e) { // user is already there, we swallow the exception } } msgTarget.addResultMessage().append("All users added"); } catch (DBInitException e) { msgTarget.addResultMessage().append("Error initializing DB"); } catch (TigaseDBException e) { msgTarget.addResultMessage().append("DB error: " + e.getMessage()); } catch (ClassNotFoundException e) { msgTarget.addResultMessage().append("Error locating connector"); } catch (InstantiationException e) { msgTarget.addResultMessage().append("Error initializing connector"); } catch (IllegalAccessException e) { msgTarget.addResultMessage().append("Illegal access"); } } enum Tasks implements TigaseDBTask { VALIDATE_CONNECTION("Checking connection to the database") { public void execute(TigaseDBHelper helper, Properties variables, MsgTarget msgTarget) { helper.validateDBConnection(msgTarget); } }, VALIDATE_DB_EXISTS("Checking if the database exists") { public void execute(TigaseDBHelper helper, Properties variables, MsgTarget msgTarget) { helper.validateDBExists(variables, msgTarget); } }, VALIDATE_DB_SCHEMA("Checking the database schema") { public void execute(TigaseDBHelper helper, Properties variables, MsgTarget msgTarget) { helper.validateDBSchema(variables, msgTarget); } }, VALIDATE_DB_CONVERSION("Checking whether the database needs conversion") { public void execute(TigaseDBHelper helper, Properties variables, MsgTarget msgTarget) { helper.validateDBConversion(variables, msgTarget); } }, ADD_ADMIN_XMPP_ACCOUNT("Adding XMPP admin accounts") { public void execute(TigaseDBHelper helper, Properties variables, MsgTarget msgTarget) { helper.addXmppAdminAccount(variables, msgTarget); } }; private final String description; private Tasks(String description) { this.description = description; } public String getDescription() { return description; } // override to change order public static TigaseDBTask[] getTasksInOrder() { return values(); } } static interface TigaseDBTask { String getDescription(); abstract void execute(TigaseDBHelper helper, Properties variables, MsgTarget msgTarget); } static interface MsgTarget { abstract ResultMessage addResultMessage(); } static interface ResultMessage { void append(String msg); } }
package apostov; import static apostov.Value.ACE; import static apostov.Value.TWO; import static com.google.common.collect.ImmutableList.copyOf; import static com.google.common.collect.ImmutableMap.copyOf; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.mapping; import static java.util.stream.Collectors.toCollection; import java.util.ArrayList; import java.util.EnumSet; import java.util.Iterator; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.function.Supplier; import java.util.stream.Collectors; import com.google.common.collect.ImmutableCollection; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import strength.FlushRanking; import strength.FullHouseRanking; import strength.HighCardRanking; import strength.PairRanking; import strength.PokerHandRanking; import strength.QuadRanking; import strength.SetRanking; import strength.StraightFlushRanking; import strength.StraightRanking; import strength.TwoPairsRanking; public class ShowdownEvaluator { public void evaluateShowdown(final ImmutableList<HolecardHand> candidates, final Board board) { throw new UnsupportedOperationException("Not implemented yet"); } public PokerHandRanking selectBestCombination(final ImmutableCollection<Card> cards) { assert cards.size() >= 5; /* Build a Map where each map-key is a Suit, and each map-value is a sorted Set of card Values */ final ImmutableMap<Suit, EnumSet<Value>> valuesBySuit = mapValuesBySuit(cards); /* Build a Map where each map-key is a card Value, and each map-value is a set of card Suits */ final ImmutableMap<Value, EnumSet<Suit>> suitsByValue = mapSuitsByValues(cards); /* Search for Straight-Flushes * This works by assuming that there can not be two straight-flushes * in different suits, which is true for Texas Holdem. */ for (final Suit suit : Suit.values()) { final EnumSet<Value> mutableValues = valuesBySuit.get(suit); if (mutableValues == null) continue; if (mutableValues.size() < 5) continue; final Optional<Value> optionalStraightFlushHighValue = searchFiveConsecutiveValues(mutableValues); if (optionalStraightFlushHighValue.isPresent()) { final Value straightFlushHighValue = optionalStraightFlushHighValue.get(); return new StraightFlushRanking(straightFlushHighValue, suit); } } /* Search for quads */ for (int i = ACE.ordinal(); TWO.ordinal() <= i; --i) { final Value value = Value.values()[i]; final EnumSet<Suit> suitsForCurrentValue = suitsByValue.get(value); if (suitsForCurrentValue == null) continue; if (suitsForCurrentValue.size() == 4) { final Card kicker = findKicker(suitsByValue, ImmutableSet.of(value)); return new QuadRanking(value, kicker); } } /* Search for full-houses */ for (int i = ACE.ordinal(); TWO.ordinal() <= i; --i) { final Value possibleSetValue = Value.values()[i]; final EnumSet<Suit> suitsForPossibleSetValue = suitsByValue.get(possibleSetValue); if (suitsForPossibleSetValue == null) continue; assert suitsForPossibleSetValue.size() < 4; if (suitsForPossibleSetValue.size() < 3) continue; assert suitsForPossibleSetValue.size() == 3; for (int j = ACE.ordinal(); j <= TWO.ordinal(); --j) { final Value possiblePairValue = Value.values()[j]; if (possibleSetValue == possiblePairValue) continue; final EnumSet<Suit> suitsForPossiblePairValue = suitsByValue.get(possiblePairValue); if (suitsForPossiblePairValue == null) continue; assert suitsForPossiblePairValue.size() < 3; if (suitsForPossiblePairValue.size() == 2) { final Iterator<Suit> setSuits = suitsForPossibleSetValue.iterator(); final Iterator<Suit> pairSuits = suitsForPossiblePairValue.iterator(); final FullHouseRanking fullHouseRanking = new FullHouseRanking( new Card(possibleSetValue, setSuits.next()), new Card(possibleSetValue, setSuits.next()), new Card(possibleSetValue, setSuits.next()), new Card(possiblePairValue, pairSuits.next()), new Card(possiblePairValue, pairSuits.next())); assert !setSuits.hasNext(); assert !pairSuits.hasNext(); return fullHouseRanking; } } } /* Search for flushes * This works by assuming that there can not be two flushes * in different suits, which is true for Texas Holdem. */ for (final Suit suit : Suit.values()) { final EnumSet<Value> mutableValues = valuesBySuit.get(suit); if (mutableValues == null) continue; if (mutableValues.size() < 5) continue; final ImmutableList<Value> flushValues = copyOf( copyOf(Value.values()) .reverse() .stream() .filter(v -> mutableValues.contains(v)) .limit(5) .iterator() ); assert flushValues.size() == 5; return new FlushRanking( suit, flushValues.get(0), flushValues.get(1), flushValues.get(2), flushValues.get(3), flushValues.get(4)); } /* Search for Straights */ final EnumSet<Value> allValues = cards .stream() .map(c -> c.value) .collect(Collectors.toCollection(() -> EnumSet.noneOf(Value.class))); final Optional<Value> optionalStraightStrength = searchFiveConsecutiveValues(allValues); if (optionalStraightStrength.isPresent()) { final Value straightTopValue = optionalStraightStrength.get(); final Value secondHighestCardValue = Value.values()[straightTopValue.ordinal() - 1]; final Value middleCardValue = Value.values()[straightTopValue.ordinal() - 2]; final Value fourthCardValue = Value.values()[straightTopValue.ordinal() - 3]; final Value bottomCardValue = Value.values()[straightTopValue.ordinal() - 4]; final Card highestCard = new Card( straightTopValue, Iterables.get(suitsByValue.get(straightTopValue), 0)); final Card secondHighestCard = new Card( secondHighestCardValue, Iterables.get(suitsByValue.get(secondHighestCardValue), 0) ); final Card middleCard = new Card( middleCardValue, Iterables.get(suitsByValue.get(middleCardValue), 0) ); final Card fourthCard = new Card( fourthCardValue, Iterables.get(suitsByValue.get(fourthCardValue), 0) ); final Card bottomCard = new Card( bottomCardValue, Iterables.get(suitsByValue.get(bottomCardValue), 0) ); return StraightRanking.create( highestCard, secondHighestCard, middleCard, fourthCard, bottomCard); } /* Search for Sets */ for (int i = ACE.ordinal(); TWO.ordinal() <= i; --i) { final Value possibleSetValue = Value.values()[i]; final EnumSet<Suit> suitsForPossibleSetValue = suitsByValue.get(possibleSetValue); if (suitsForPossibleSetValue == null) continue; assert suitsForPossibleSetValue.size() < 4; if (suitsForPossibleSetValue.size() < 3) continue; assert suitsForPossibleSetValue.size() == 3; final Card firstKicker = findKicker(suitsByValue, ImmutableSet.of(possibleSetValue)); final Card secondKicker = findKicker(suitsByValue, ImmutableSet.of(possibleSetValue, firstKicker.value)); final Suit firstSuit, secondSuit, thirdSuit; { final Iterator<Suit> setSuits = suitsForPossibleSetValue.iterator(); firstSuit = setSuits.next(); secondSuit = setSuits.next(); thirdSuit = setSuits.next(); assert !setSuits.hasNext(); } return new SetRanking(possibleSetValue, firstSuit, secondSuit, thirdSuit, firstKicker, secondKicker); } /* Search for Two-Pairs and Pairs */ for (int i = ACE.ordinal(); TWO.ordinal() <= i; --i) { final Value possibleHighPairValue = Value.values()[i]; final EnumSet<Suit> suitsForPossibleHighPairValue = suitsByValue.get(possibleHighPairValue); if (suitsForPossibleHighPairValue == null) continue; if (suitsForPossibleHighPairValue.size() < 2) continue; assert suitsForPossibleHighPairValue.size() == 2; final Card firstCardOfHighestPair, secondCardOfHighestPair; { final Iterator<Suit> highPairSuits = suitsForPossibleHighPairValue.iterator(); firstCardOfHighestPair = new Card(possibleHighPairValue, highPairSuits.next()); secondCardOfHighestPair = new Card(possibleHighPairValue, highPairSuits.next()); assert !highPairSuits.hasNext(); } for (int j = i - 1; TWO.ordinal() <= j; --j) { final Value possibleLowPairValue = Value.values()[i]; final EnumSet<Suit> suitsForPossibleLowPairValue = suitsByValue.get(possibleLowPairValue); if (suitsForPossibleLowPairValue == null) continue; if (suitsForPossibleLowPairValue.size() < 2) continue; assert suitsForPossibleLowPairValue.size() == 2; final Card kicker = findKicker(suitsByValue, ImmutableSet.of(possibleHighPairValue, possibleLowPairValue)); final Card firstCardOfLowestPair, secondCardOfLowestPair; { final Iterator<Suit> lowPairSuits = suitsForPossibleLowPairValue.iterator(); firstCardOfLowestPair = new Card(possibleLowPairValue, lowPairSuits.next()); secondCardOfLowestPair = new Card(possibleLowPairValue, lowPairSuits.next()); assert !lowPairSuits.hasNext(); } return new TwoPairsRanking( firstCardOfHighestPair, secondCardOfHighestPair, firstCardOfLowestPair, secondCardOfLowestPair, kicker); } final Card firstKicker = findKicker( suitsByValue, ImmutableSet.of(possibleHighPairValue)); final Card secondKicker = findKicker( suitsByValue, ImmutableSet.of(possibleHighPairValue, firstKicker.value)); final Card thirdKicker = findKicker( suitsByValue, ImmutableSet.of(possibleHighPairValue, firstKicker.value, secondKicker.value)); return new PairRanking( possibleHighPairValue, firstCardOfHighestPair.suit, secondCardOfHighestPair.suit, firstKicker, secondKicker, thirdKicker); } /* Finally, build a ranking for high-card hands */ final List<Card> bestCards = new ArrayList<>(5); for (int i = ACE.ordinal(); TWO.ordinal() <= i; --i) { final Value value = Value.values()[i]; final Set<Suit> suits = suitsByValue.get(value); if (suits == null) continue; if (suits.isEmpty()) continue; final Suit suit = Iterables.get(suits, 0); bestCards.add(new Card(value, suit)); if (bestCards.size() == 5) break; } assert bestCards.size() == 5; return new HighCardRanking( bestCards.get(0), bestCards.get(1), bestCards.get(2), bestCards.get(3), bestCards.get(4)); } private Card findKicker( final ImmutableMap<Value, EnumSet<Suit>> suitsByValue, final ImmutableSet<Value> excludedValues) { for (int j = ACE.ordinal(); j <= TWO.ordinal(); --j) { final Value possibleKickerValue = Value.values()[j]; if (excludedValues.contains(possibleKickerValue)) continue; final EnumSet<Suit> suitsForThisPossibleKicker = suitsByValue.get(possibleKickerValue); if (suitsForThisPossibleKicker != null && suitsForThisPossibleKicker.size() > 0) return new Card(possibleKickerValue, Iterables.get(suitsForThisPossibleKicker, 0)); } throw new RuntimeException("Failed to find a kicker"); } private ImmutableMap<Suit, EnumSet<Value>> mapValuesBySuit(final ImmutableCollection<Card> cards) { final Supplier<EnumSet<Value>> enumSetSupplier = () -> EnumSet.noneOf(Value.class); final ImmutableMap<Suit, EnumSet<Value>> valuesBySuit = copyOf(cards.stream().collect(groupingBy( c -> c.suit, mapping(c -> c.value, toCollection(enumSetSupplier)) ))); return valuesBySuit; } private ImmutableMap<Value, EnumSet<Suit>> mapSuitsByValues(final ImmutableCollection<Card> cards) { final Supplier<EnumSet<Suit>> enumSetSupplier = () -> EnumSet.noneOf(Suit.class); final ImmutableMap<Value, EnumSet<Suit>> valuesBySuit = copyOf(cards.stream().collect(groupingBy( c -> c.value, mapping(c -> c.suit, toCollection(enumSetSupplier)) ))); return valuesBySuit; } private Optional<Value> searchFiveConsecutiveValues(final Set<Value> values) { if (values.size() < 5) throw new RuntimeException("Programming error: trying to find a straight with less than five card values"); int consecutiveCardsCount = 0; for (int i = ACE.ordinal(); i >= TWO.ordinal(); --i) { if (values.contains(i)) ++consecutiveCardsCount; else consecutiveCardsCount = 0; if (consecutiveCardsCount == 5) return Optional.of(Value.values()[i + 5]); } if (consecutiveCardsCount == 4) if (values.contains(ACE)) return Optional.of(Value.FIVE); return Optional.empty(); } }
package arez.dom; import arez.ComputableValue; import arez.Disposable; import arez.annotations.Action; import arez.annotations.ArezComponent; import arez.annotations.ComputableValueRef; import arez.annotations.DepType; import arez.annotations.Feature; import arez.annotations.Memoize; import arez.annotations.Observable; import arez.annotations.OnActivate; import arez.annotations.OnDeactivate; import elemental2.dom.Event; import elemental2.dom.EventListener; import elemental2.dom.EventTarget; import java.util.Objects; import javax.annotation.Nonnull; import jsinterop.annotations.JsFunction; /** * An observable component that exposes a value provided by a lambda as observable where the value can * change in response to a browser event. A typical example is making the value of <code>window.innerWidth</code> * observable by listening to <code>"resize"</code> events on the window. This could be achieved with code such * as: * * <pre>{@code * EventDrivenValue&lt;Window, Integer&gt; innerWidth = EventDrivenValue.create( window, "resize", () -> window.innerWidth ) * }</pre> * * <p>It is important that the code not add a listener to the underlying event source until there is an * observer accessing the <code>"value"</code> observable defined by the EventDrivenValue class. The first * observer that observes the observable will result in an event listener being added to the event source * and this listener will not be removed until there is no observers left observing the value. This means * that a component that is not being used has very little overhead.</p> * * @param <SourceType> the type of the DOM element that generates events of interest. * @param <ValueType> the type of the value returned by the "value" observable. */ @ArezComponent( requireEquals = Feature.DISABLE, requireId = Feature.DISABLE, disposeTrackable = Feature.DISABLE ) public abstract class EventDrivenValue<SourceType extends EventTarget, ValueType> { /** * The functional interface defining accessor. * * @param <SourceType> the type of the DOM element that generates events of interest. * @param <ValueType> the type of the value returned by the "value" observable. */ @FunctionalInterface @JsFunction public interface Accessor<SourceType extends EventTarget, ValueType> { /** * Return the value. * * @param source the source that drives the access. * @return the value */ ValueType get( @Nonnull SourceType source ); } /** * The */ @Nonnull private final EventListener _listener = this::onEvent; @Nonnull private SourceType _source; @Nonnull private final String _event; @Nonnull private final Accessor<SourceType, ValueType> _getter; private boolean _active; /** * Create the component. * * @param <SourceType> the type of the DOM element that generates events of interest. * @param <ValueType> the type of the value returned by the "value" observable. * @param source the DOM element that generates events of interest. * @param event the event type that could result in changes to the observed value. The event type is expected to be generated by the source element. * @param getter the function that retrieves the observed value from the platform. * @return the new component. */ @Nonnull public static <SourceType extends EventTarget, ValueType> EventDrivenValue<SourceType, ValueType> create( @Nonnull final SourceType source, @Nonnull final String event, @Nonnull final Accessor<SourceType, ValueType> getter ) { return new Arez_EventDrivenValue<>( source, event, getter ); } EventDrivenValue( @Nonnull final SourceType source, @Nonnull final String event, @Nonnull final Accessor<SourceType, ValueType> getter ) { _source = Objects.requireNonNull( source ); _event = Objects.requireNonNull( event ); _getter = Objects.requireNonNull( getter ); } /** * Return the element that generates the events that report potential changes to the observed value. * * @return the associated element. */ @Nonnull @Observable public SourceType getSource() { return _source; } /** * Set the element that generates events. * This ensures that the event listeners are managed correctly if the source is currently being observed. * * @param source the the event source. */ public void setSource( @Nonnull final SourceType source ) { if ( _active ) { unbindListener(); } _source = source; if ( _active ) { bindListener(); } } /** * Return the value. * * @return the value. */ @Memoize( depType = DepType.AREZ_OR_EXTERNAL ) public ValueType getValue() { // Deliberately observing source via getSource() so that this method re-runs // when source changes return _getter.get( getSource() ); } @ComputableValueRef abstract ComputableValue getValueComputableValue(); /** * Hook invoked when the value moves from unobserved to observed. * Adds underlying listener. */ @OnActivate final void onValueActivate() { _active = true; bindListener(); } /** * Hook invoked when value is no longer observed. * Removes underlying listener. */ @OnDeactivate final void onValueDeactivate() { _active = false; unbindListener(); } private void onEvent( final Event e ) { // Due to bugs (?) or perhaps "implementation choices" in some browsers, an event can be delivered // Safari doesn't clear up listener queue on MediaQueryList when removeListener is called if there // is already waiting in the internal event queue. // To avoid a potential crash when invariants are enabled or indeterminate behaviour when invariants // are not enabled, a guard has been added. if ( Disposable.isNotDisposed( this ) ) { notifyOnChange(); } } /** * Hook invoked from listener to indicate memoized value should be recomputed. */ @Action void notifyOnChange() { getValueComputableValue().reportPossiblyChanged(); } /** * Add underlying listener to source. */ private void bindListener() { _source.addEventListener( _event, _listener ); } /** * Remove underlying listener from source. */ private void unbindListener() { _source.removeEventListener( _event, _listener ); } }
package dnss.tools.pak; import dnss.tools.commons.DNSS; import dnss.tools.commons.Properties; import dnss.tools.commons.ReadStream; import org.apache.log4j.Logger; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.concurrent.Semaphore; import java.util.regex.Pattern; import java.util.zip.DataFormatException; import java.util.zip.Inflater; public class PakFile implements Runnable { private final static Logger logger = Logger.getLogger(PakFile.class); private Properties properties; private int streamOffset; private int compressedSize; private int fileSize; private String filePath; private File file; private static Object LOCK = new Object(); public PakFile(Properties properties) { this.properties = properties; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath.substring(0, filePath.indexOf('\0')).trim(); } public int getStreamOffset() { return streamOffset; } public void setStreamOffset(int streamOffset) { this.streamOffset = streamOffset; } public int getCompressedSize() { return compressedSize; } public void setCompressedSize(int compressedSize) { this.compressedSize = compressedSize; } public int getFileSize() { return fileSize; } public void setFileSize(int fileSize) { this.fileSize = fileSize; } public File getFile() { return file; } public void setFile(File file) { this.file = file; } public Properties getProperties() { return properties; } public void setProperties(Properties properties) { this.properties = properties; } public boolean isExtractAllowed() { boolean allowed = false, ignored = false; // global check first if (DNSS.has("allowPatterns")) { ArrayList<Pattern> allowPatterns = DNSS.get("allowPatterns", ArrayList.class); for (Pattern pattern : allowPatterns) { allowed |= pattern.matcher(filePath).find(); } } if (properties.has("allowPatterns")) { ArrayList<Pattern> allowPatterns = properties.get("allowPatterns", ArrayList.class); for (Pattern pattern : allowPatterns) { allowed |= pattern.matcher(filePath).find(); } } if (! DNSS.has("allowPatterns") && ! properties.has("allowPatterns")) { allowed = true; } if (DNSS.has("ignorePatterns")) { ArrayList<Pattern> ignorePatterns = DNSS.get("ignorePatterns", ArrayList.class); for (Pattern pattern : ignorePatterns) { ignored |= pattern.matcher(filePath).find(); } } if (properties.has("ignorePatterns")) { ArrayList<Pattern> ignorePatterns = properties.get("ignorePatterns", ArrayList.class); for (Pattern pattern : ignorePatterns) { ignored |= pattern.matcher(filePath).find(); } } if (! DNSS.has("ignorePatterns") && ! properties.has("ignorePatterns")) { ignored = false; } return allowed && ! ignored; } public void extract() throws IOException, DataFormatException { File absoluteFile = new File(properties.get("output", String.class), filePath); if (! properties.get("extractDeleted", Boolean.TYPE) && fileSize == 0) { logger.info("[d] " + absoluteFile.getPath()); return; } else if (! isExtractAllowed()) { logger.info("[ ] " + absoluteFile.getPath()); return; } ReadStream readStream = new ReadStream(properties.get("file", String.class)); synchronized (LOCK) { File dir = absoluteFile.getParentFile(); if (! dir.exists() && ! dir.mkdirs()) { logger.error("Could not create directory " + dir.getPath()); } } byte[] pakContents = new byte[compressedSize]; readStream.seek(streamOffset).readFully(pakContents); readStream.close(); synchronized (file) { int i = 1; File outputFile = absoluteFile; while (outputFile.exists()) { int extPos = filePath.lastIndexOf('.'); if (extPos == -1) { extPos = filePath.length(); } String newPath = filePath.substring(0, extPos) + i++ + filePath.substring(extPos); outputFile = new File(properties.get("output", String.class), newPath); } byte[] inflatedPakContents = new byte[8192]; FileOutputStream fileOutputStream = new FileOutputStream(outputFile); Inflater inflater = new Inflater(); inflater.setInput(pakContents); while (! inflater.finished()) { int inflatedSize = inflater.inflate(inflatedPakContents); fileOutputStream.write(inflatedPakContents, 0, inflatedSize); } inflater.end(); fileOutputStream.close(); logger.info("[x] " + outputFile.getPath()); } synchronized (properties) { properties.set("extractCount", properties.get("extractCount", Integer.TYPE) + 1); } } public void run() { PakAccumulator accumulator = properties.get("accumulator", PakAccumulator.class); Semaphore semaphore = DNSS.get("semaphore", Semaphore.class); try { semaphore.acquireUninterruptibly(); extract(); } catch(IOException e) { logger.error("Could not extract " + filePath + " from " + properties.get("file", String.class), e); } catch (DataFormatException e) { logger.error("Could not extract zipped content " + filePath + " from " + properties.get("file", String.class), e); } finally { accumulator.dissipate(); semaphore.release(); } } }
package main.java.author.view; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JTabbedPane; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import main.java.author.controller.MainController; import main.java.author.controller.tabbed_controllers.EnemyController; import main.java.author.controller.tabbed_controllers.GameSettingsController; import main.java.author.controller.tabbed_controllers.ItemController; import main.java.author.controller.tabbed_controllers.TerrainController; import main.java.author.controller.tabbed_controllers.TowerController; import main.java.author.controller.tabbed_controllers.WaveController; import main.java.author.view.menubar.BasicMenuBar; import main.java.author.view.tabs.EditorTab; import main.java.author.view.tabs.GameSettingsEditorTab; import main.java.author.view.tabs.enemy.EnemyEditorTab; import main.java.author.view.tabs.terrain.TerrainEditorTab; import main.java.author.view.tabs.tower.TowerEditorTab; import main.java.author.view.tabs.wave_editor.WaveEditorTab; import main.java.exceptions.data.InvalidGameBlueprintException; /** * Frame that represents the GUI for the Authoring environment. Holds references * to the Main Controller and holds the tabs * */ public class AuthoringView extends JFrame { private MainController myController; private JButton finalizeGameButton; private EnemyEditorTab enemyEditorTab; private TowerEditorTab towerEditorTab; private JTabbedPane tabbedPane = new JTabbedPane(); private static final String GAME_SETTINGS_EDITOR_STRING = "Game Settings Editor"; private static final String TOWER_EDITOR_STRING = "Tower Editor"; private static final String ENEMY_EDITOR_STRING = "Enemy Editor"; private static final String ITEM_EDITOR_STRING = "Item Editor"; private static final String TERRAIN_EDITOR_STRING = "Terrain Editor"; private static final String WAVE_EDITOR_STRING = "Wave Editor"; public AuthoringView(MainController mainController) { super("OOGASalad Authoring Environment"); myController = mainController; myController.setView(this); } /** * Creates the Editor Tabs for the tower, enemy, wave, terrain, etc. */ public void createEditorTabs() { final EnemyController enemyController = new EnemyController(myController); final TowerController towerController = new TowerController(myController); final WaveController waveController = new WaveController(myController); final GameSettingsController gameSettingsController = new GameSettingsController(myController); final TerrainController terrainController = new TerrainController(myController); final ItemController itemController = new ItemController(myController); myController.addTabController(enemyController); myController.addTabController(towerController); myController.addTabController(waveController); myController.addTabController(gameSettingsController); myController.addTabController(terrainController); myController.addTabController(itemController); tabbedPane.add(GAME_SETTINGS_EDITOR_STRING, new GameSettingsEditorTab( gameSettingsController)); tabbedPane.add(TOWER_EDITOR_STRING, new TowerEditorTab(towerController, "Tower")); enemyEditorTab = new EnemyEditorTab(enemyController, "Monster"); tabbedPane .add(ENEMY_EDITOR_STRING, enemyEditorTab); // tabbedPane // .add(ITEM_EDITOR_STRING, // new ItemEditorTab(itemController, "Item")); tabbedPane .add(TERRAIN_EDITOR_STRING, new TerrainEditorTab(terrainController)); tabbedPane .add(WAVE_EDITOR_STRING, new WaveEditorTab(waveController)); tabbedPane.addChangeListener(new ChangeListener(){ @Override public void stateChanged(ChangeEvent e) { // TODO Auto-generated method stub if (tabbedPane.getSelectedComponent() instanceof WaveEditorTab) { waveController.updateEnemyList(); } } }); } /** * Creates the GUI and sets initial constraints */ public void createAndShowGUI() { createEditorTabs(); add(tabbedPane, BorderLayout.CENTER); add(createFinalizeGameButton(), BorderLayout.SOUTH); setJMenuBar(new BasicMenuBar()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setResizable(true); pack(); setVisible(true); addActionListeners(); } /** * Adds an action listener to the finalize game button which, when clicked, * saves the game blueprint so the data team can begin serializing * information */ private void addActionListeners() { finalizeGameButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int editorTabCount = tabbedPane.getTabCount(); for (int count = 0; count < editorTabCount; count++) { EditorTab tab = (EditorTab) tabbedPane .getComponentAt(count); tab.saveTabData(); } if (myController.isGameValid()) { try { myController.saveBlueprint(); } catch (InvalidGameBlueprintException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }); } /** * Constructs a JButton which allows the user to finalize the game that they * made */ private JButton createFinalizeGameButton() { finalizeGameButton = new JButton("Finalize Game"); return finalizeGameButton; } /** * Shifts to the Enemy Tab */ public void shiftToEnemyTab() { tabbedPane.setSelectedComponent(enemyEditorTab); } public void shiftToTowerTab() { tabbedPane.setSelectedComponent(towerEditorTab); } }
package com.sometrik.framework; import android.content.Context; import android.view.View; import android.widget.RadioButton; import android.widget.RadioGroup; public class FWRadioGroup extends RadioGroup implements NativeCommandHandler { private Context context; public FWRadioGroup(Context context){ super(context); this.context = context; } @Override public void addChild(View view) { // TODO Auto-generated method stub } @Override public void removeChild(int id) { // TODO Auto-generated method stub } @Override public void showView() { // TODO Auto-generated method stub } @Override public void addOption(int optionId, String text) { RadioButton button = new RadioButton(context); button.setId(optionId); button.setText(text); addView(button); } @Override public void setValue(String v) { // TODO Auto-generated method stub } @Override public void setValue(int v) { // TODO Auto-generated method stub } @Override public int getElementId() { return getId(); } }
package Cache; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import com.csvreader.CsvWriter; import Util.CmdLineParser; import Cache.CacheItem.CacheReason; import Database.DatabaseManager; public class Simulator { /** * Database prepared sql statements. */ static final String findCommit = "select id, date, is_bug_fix from scmlog " + "where repository_id =? and date between ? and ? order by date ASC"; static final String findFile = "select actions.file_id, type from actions, content_loc " + "where actions.file_id=content_loc.file_id " + "and actions.commit_id=? and content_loc.commit_id=? " + "and actions.file_id in( " + "select file_id from file_types where type='code') order by loc DESC"; static final String findHunkId = "select id from hunks where file_id =? and commit_id =?"; static final String findBugIntroCdate = "select date from hunk_blames, scmlog " + "where hunk_id =? and hunk_blames.bug_commit_id=scmlog.id"; static final String findPid = "select id from repositories where id=?"; static final String findFileCount = "select count(files.id) from files, file_types " + "where files.id = file_types.file_id and type = 'code' and repository_id=?"; private static PreparedStatement findCommitQuery; private static PreparedStatement findFileQuery; private static PreparedStatement findHunkIdQuery; static PreparedStatement findBugIntroCdateQuery; static PreparedStatement findPidQuery; static PreparedStatement findFileCountQuery; public enum FileType { A, M, D, V, C, R } /** * Member fields */ final int blocksize; // number of co-change files to import final int prefetchsize; // number of (new or modified but not buggy) files // to import final int cachesize; // size of cache final int pid; // project (repository) id final boolean saveToFile; // whether there should be csv output final CacheReplacement.Policy cacheRep; // cache replacement policy final Cache cache; // the cache final static Connection conn = DatabaseManager.getConnection(); // for database int hit; int miss; private int commits; // For output // XXX separate class to manage output String outputDate; int outputSpacing = 3; // output the hit rate every 3 months int month = outputSpacing; CsvWriter csvWriter; int fileCount; // XXX where is this set? why static? String filename; public Simulator(int bsize, int psize, int csize, int projid, CacheReplacement.Policy rep, String start, String end, Boolean save) { pid = projid; int onepercent = getPercentOfFiles(pid); if (bsize == -1) blocksize = onepercent*5; else blocksize = bsize; if (csize == -1) cachesize = onepercent*10; else cachesize = csize; if (psize == -1) prefetchsize = onepercent; else prefetchsize = psize; cacheRep = rep; start = findFirstDate(start, pid); end = findLastDate(end, pid); cache = new Cache(cachesize, new CacheReplacement(rep), start, end, projid); outputDate = cache.startDate; hit = 0; miss = 0; this.saveToFile = save; if (saveToFile == true) { filename = pid + "_" + cachesize + "_" + blocksize + "_" + prefetchsize + "_" + cacheRep; csvWriter = new CsvWriter("Results/" + filename + "_hitrate.csv"); csvWriter.setComment(' try { csvWriter.writeComment("hitrate for every 3 months, " + "used to describe the variation of hit rate with time"); csvWriter.writeComment("project: " + pid + ", cachesize: " + cachesize + ", blocksize: " + cachesize + ", prefetchsize: " + prefetchsize + ", cache replacement policy: " + cacheRep); csvWriter.write("Month"); //csvWriter.write("Range"); csvWriter.write("HitRate"); csvWriter.write("NumCommits"); csvWriter.endRecord(); } catch (IOException e) { e.printStackTrace(); } } try { findFileQuery = conn.prepareStatement(findFile); findCommitQuery = conn.prepareStatement(findCommit); findHunkIdQuery = conn.prepareStatement(findHunkId); findBugIntroCdateQuery = conn.prepareStatement(findBugIntroCdate); } catch (SQLException e) { e.printStackTrace(); } } private static int getFileCount(int projid) { int ret = 0; try { findFileCountQuery = conn.prepareStatement(findFileCount); findFileCountQuery.setInt(1, projid); ret = Util.Database.getIntResult(findFileCountQuery); } catch (SQLException e1) { e1.printStackTrace(); } return ret; } /** * Prints out the command line options */ private static void printUsage() { System.err .println("Example Usage: FixCache -b=10000 -c=500 -f=600 -r=\"LRU\" -p=1"); System.err.println("Example Usage: FixCache --blksize=10000 " + "--csize=500 --pfsize=600 --cacherep=\"LRU\" --pid=1"); System.err.println("-p/--pid option is required"); } /** * Loads an entity containing a bug into the cache. * * @param fileId * @param cid * -- commit id * @param commitDate * -- commit date * @param intro_cdate * -- bug introducing commit date */ // XXX move hit and miss to the cache? // could add if (reas == BugEntity) logic to add() code public void loadBuggyEntity(int fileId, int cid, String commitDate, String intro_cdate) { if (cache.contains(fileId)) hit++; else miss++; cache.add(fileId, cid, commitDate, CacheItem.CacheReason.BugEntity); // add the co-changed files as well ArrayList<Integer> cochanges = CoChange.getCoChangeFileList(fileId, cache.startDate, intro_cdate, blocksize); cache.add(cochanges, cid, commitDate, CacheItem.CacheReason.CoChange); } /** * The main simulate loop. This loop processes all revisions starting at * cache.startDate * */ public void simulate() { final ResultSet allCommits; int cid;// means commit_id in actions String cdate = null; boolean isBugFix; int file_id; FileType type; int numprefetch = 0; // iterate over the selection try { findCommitQuery.setInt(1, pid); findCommitQuery.setString(2, cache.startDate); findCommitQuery.setString(3, cache.endDate); // returns all commits to pid after cache.startDate allCommits = findCommitQuery.executeQuery(); while (allCommits.next()) { commits++; cid = allCommits.getInt(1); cdate = allCommits.getString(2); isBugFix = allCommits.getBoolean(3); findFileQuery.setInt(1, cid); findFileQuery.setInt(2, cid); final ResultSet files = findFileQuery.executeQuery(); // loop through those file ids while (files.next()) { file_id = files.getInt(1); type = FileType.valueOf(files.getString(2)); numprefetch = processOneFile(cid, cdate, isBugFix, file_id, type, numprefetch); } numprefetch = 0; if (saveToFile == true) { if (Util.Dates.getMonthDuration(outputDate, cdate) > outputSpacing || cdate.equals(cache.endDate)) { outputHitRate(cdate); } } } } catch (Exception e) { System.out.println(e); e.printStackTrace(); } } private void outputHitRate(String cdate) { // XXX what if commits are more than 3 months apart? // XXX eliminate range? //final String formerOutputDate = outputDate; if (!cdate.equals(cache.endDate)) { outputDate = Util.Dates.monthsLater(outputDate, outputSpacing); } else { outputDate = cdate; } try { csvWriter.write(Integer.toString(month)); //csvWriter.write(Util.Dates.getRange(formerOutputDate, outputDate)); csvWriter.write(Double.toString(getHitRate())); csvWriter.write(Integer.toString(getCommitCount())); csvWriter.endRecord(); } catch (IOException e) { e.printStackTrace(); } month += outputSpacing; if (Util.Dates.getMonthDuration(outputDate, cdate) > outputSpacing){ outputHitRate(cdate); } } private int processOneFile(int cid, String cdate, boolean isBugFix, int file_id, FileType type, int numprefetch) { switch (type) { case V: break; case R: case C: case A: if (numprefetch < prefetchsize) { numprefetch++; cache.add(file_id, cid, cdate, CacheItem.CacheReason.Prefetch); } break; case D: if(cache.contains(file_id)){ this.cache.remove(file_id, cdate); } break; case M: // modified if (isBugFix) { String intro_cdate = this.getBugIntroCdate(file_id, cid); this.loadBuggyEntity(file_id, cid, cdate, intro_cdate); } else if (numprefetch < prefetchsize) { numprefetch++; cache.add(file_id, cid, cdate, CacheItem.CacheReason.Prefetch); } } return numprefetch; } /** * Gets the current hit rate of the cache * * @return hit rate of the cache */ public double getHitRate() { double hitrate = (double) hit / (hit + miss); return (double) Math.round(hitrate * 10000) / 100; } /** * Database accessors */ /** * Fills cache with pre-fetch size number of top-LOC files from initial * commit. Only called once per simulation // implicit input: initial commit * ID // implicit input: LOC for every file in initial commit ID // implicit * input: pre-fetch size */ public void initialPreLoad() { final String findInitialPreload = "select content_loc.file_id, content_loc.commit_id " + "from content_loc, scmlog, actions, file_types " + "where repository_id=? and content_loc.commit_id = scmlog.id and date =? " + "and content_loc.file_id=actions.file_id " + "and content_loc.commit_id=actions.commit_id and actions.type!='D' " + "and file_types.file_id=content_loc.file_id and file_types.type='code' order by loc DESC"; final PreparedStatement findInitialPreloadQuery; ResultSet r = null; int fileId = 0; int commitId = 0; try { findInitialPreloadQuery = conn.prepareStatement(findInitialPreload); findInitialPreloadQuery.setInt(1, pid); findInitialPreloadQuery.setString(2, cache.startDate); r = findInitialPreloadQuery.executeQuery(); } catch (SQLException e1) { e1.printStackTrace(); } for (int size = 0; size < prefetchsize; size++) { try { if (r.next()) { fileId = r.getInt(1); commitId = r.getInt(2); cache.add(fileId, commitId, cache.startDate, CacheItem.CacheReason.Prefetch); } } catch (SQLException e) { e.printStackTrace(); } } } /** * Finds the first date after the startDate with repository entries. Only * called once per simulation. * * @return The date for the prefetch. */ private static String findFirstDate(String start, int pid) { String findFirstDate = ""; final PreparedStatement findFirstDateQuery; String firstDate = ""; try { if (start == null) { findFirstDate = "select min(date) from scmlog where repository_id=?"; findFirstDateQuery = conn.prepareStatement(findFirstDate); findFirstDateQuery.setInt(1, pid); } else { findFirstDate = "select min(date) from scmlog where repository_id=? and date >=?"; findFirstDateQuery = conn.prepareStatement(findFirstDate); findFirstDateQuery.setInt(1, pid); findFirstDateQuery.setString(2, start); } firstDate = Util.Database.getStringResult(findFirstDateQuery); if (firstDate == null) { System.out.println("Can not find any commit after " + start); System.exit(2); } } catch (SQLException e) { e.printStackTrace(); } return firstDate; } /** * Finds the last date before the endDate with repository entries. Only * called once per simulation. * * @return The date for the the simulator. */ private static String findLastDate(String end, int pid) { String findLastDate = null; final PreparedStatement findLastDateQuery; String lastDate = null; try { if (end == null) { findLastDate = "select max(date) from scmlog where repository_id=?"; findLastDateQuery = conn.prepareStatement(findLastDate); findLastDateQuery.setInt(1, pid); } else { findLastDate = "select max(date) from scmlog where repository_id=? and date <=?"; findLastDateQuery = conn.prepareStatement(findLastDate); findLastDateQuery.setInt(1, pid); findLastDateQuery.setString(2, end); } lastDate = Util.Database.getStringResult(findLastDateQuery); } catch (SQLException e) { e.printStackTrace(); } if (lastDate == null) { System.out.println("Can not find any commit before " + end); System.exit(2); } return lastDate; } /** * use the fileId and commitId to get a list of changed hunks from the hunk * table. for each changed hunk, get the blamedHunk from the hunk_blame * table; get the commit id associated with this blamed hunk take the * maximum (in terms of date?) commit id and return it * */ public String getBugIntroCdate(int fileId, int commitId) { // XXX optimize this code? String bugIntroCdate = ""; int hunkId; ResultSet r = null; ResultSet r1 = null; try { findHunkIdQuery.setInt(1, fileId); findHunkIdQuery.setInt(2, commitId); r = findHunkIdQuery.executeQuery(); while (r.next()) { hunkId = r.getInt(1); findBugIntroCdateQuery.setInt(1, hunkId); r1 = findBugIntroCdateQuery.executeQuery(); while (r1.next()) { if (r1.getString(1).compareTo(bugIntroCdate) > 0) { bugIntroCdate = r1.getString(1); } } } } catch (Exception e) { System.out.println(e); System.exit(0); } return bugIntroCdate; } /** * Closes the database connection */ private void close() { DatabaseManager.close(); } /** * For Debugging */ public int getHit() { return hit; } public int getMiss() { return miss; } public Cache getCache() { return cache; } public void add(int eid, int cid, String cdate, CacheReason reas) { cache.add(eid, cid, cdate, reas); } // XXX move to a different part of the file public static void checkParameter(String start, String end, int pid) { if (start != null && end != null) { if (start.compareTo(end) > 0) { System.err .println("Error:Start date must be earlier than end date"); printUsage(); System.exit(2); } } try { findPidQuery = conn.prepareStatement(findPid); findPidQuery.setInt(1, pid); if (Util.Database.getIntResult(findPidQuery) == -1) { System.out.println("There is no project whose id is " + pid); System.exit(2); } } catch (SQLException e) { e.printStackTrace(); } } public static void main(String args[]) { /** * Command line parsing */ CmdLineParser parser = new CmdLineParser(); CmdLineParser.Option blksz_opt = parser.addIntegerOption('b', "blksize"); CmdLineParser.Option csz_opt = parser.addIntegerOption('c', "csize"); CmdLineParser.Option pfsz_opt = parser.addIntegerOption('f', "pfsize"); CmdLineParser.Option crp_opt = parser.addStringOption('r', "cacherep"); CmdLineParser.Option pid_opt = parser.addIntegerOption('p', "pid"); CmdLineParser.Option sd_opt = parser.addStringOption('s', "start"); CmdLineParser.Option ed_opt = parser.addStringOption('e', "end"); CmdLineParser.Option save_opt = parser.addBooleanOption('o',"save"); CmdLineParser.Option tune_opt = parser.addBooleanOption('u', "tune"); // CmdLineParser.Option sCId_opt = parser.addIntegerOption('s',"start"); // CmdLineParser.Option eCId_opt = parser.addIntegerOption('e',"end"); try { parser.parse(args); } catch (CmdLineParser.OptionException e) { System.err.println(e.getMessage()); printUsage(); System.exit(2); } Integer blksz = (Integer) parser.getOptionValue(blksz_opt, -1); Integer csz = (Integer) parser.getOptionValue(csz_opt, -1); Integer pfsz = (Integer) parser.getOptionValue(pfsz_opt, -1); String crp_string = (String) parser.getOptionValue(crp_opt, CacheReplacement.REPDEFAULT.toString()); Integer pid = (Integer) parser.getOptionValue(pid_opt); String start = (String) parser.getOptionValue(sd_opt, null); String end = (String) parser.getOptionValue(ed_opt, null); Boolean saveToFile = (Boolean) parser.getOptionValue(save_opt, false); Boolean tune = (Boolean)parser.getOptionValue(tune_opt, false); CacheReplacement.Policy crp; try { crp = CacheReplacement.Policy.valueOf(crp_string); } catch (Exception e) { System.err.println(e.getMessage()); System.err.println("Must specify a valid cache replacement policy"); printUsage(); crp = CacheReplacement.REPDEFAULT; } // startCId = (Integer)parser.getOptionValue(sCId_opt, STARTIDDEFAULT); // endCId = (Integer)parser.getOptionValue(eCId_opt, Integer.MAX_VALUE); if (pid == null) { System.err.println("Error: must specify a Project Id"); printUsage(); System.exit(2); } checkParameter(start, end, pid); /** * Create a new simulator and run simulation. */ Simulator sim; if(tune) { System.out.println("tuning..."); sim = tune(pid); System.out.println(".... finished tuning!"); System.out.println("highest hitrate:"+sim.getHitRate()); } else { sim = new Simulator(blksz, pfsz, csz, pid, crp, start, end, saveToFile); sim.initialPreLoad(); sim.simulate(); if(sim.saveToFile==true) { sim.csvWriter.close(); sim.outputFileDist(); } } // should always happen sim.close(); printSummary(sim); } private static void printSummary(Simulator sim) { System.out.println("Simulator specs:"); System.out.print("Project...."); System.out.println(sim.pid); System.out.print("Cache size...."); System.out.println(sim.cachesize); System.out.print("Blk size...."); System.out.println(sim.blocksize); System.out.print("Prefetch size...."); System.out.println(sim.prefetchsize); System.out.print("Start date...."); System.out.println(sim.cache.startDate); System.out.print("End date...."); System.out.println(sim.cache.endDate); System.out.print("Cache Replacement Policy ...."); System.out.println(sim.cacheRep.toString()); System.out.print("saving to file...."); System.out.println(sim.saveToFile); System.out.println("\nResults:"); System.out.print("Hit rate..."); System.out.println(sim.getHitRate()); System.out.print("Num commits processed..."); System.out.println(sim.getCommitCount()); System.out.print("Num bug fixes..."); System.out.println(sim.getHit() + sim.getMiss()); } private static Simulator tune(int pid) { Simulator sim; Simulator maxsim = null; double maxhitrate = 0; int blksz; int pfsz; int onepercent = getPercentOfFiles(pid); final int UPPER = 22*onepercent; for(blksz=onepercent;blksz<UPPER;blksz+=onepercent*3){ for(pfsz=onepercent;pfsz<UPPER;pfsz+=onepercent*3){ for(CacheReplacement.Policy crp:CacheReplacement.Policy.values()){ sim = new Simulator(blksz, pfsz,-1, pid, crp, null, null, false); sim.initialPreLoad(); sim.simulate(); if(sim.getHitRate()>maxhitrate) { maxhitrate = sim.getHitRate(); maxsim = sim; } } } } maxsim.close(); return maxsim; } private static int getPercentOfFiles(int pid) { int ret = (int) Math.round(getFileCount(pid)*0.01); if (ret == 0) return 1; else return ret; } public void outputFileDist() { csvWriter = new CsvWriter("Results/" + filename + "_filedist.csv"); csvWriter.setComment(' try { // csvWriter.write("# number of hit, misses and time stayed in Cache for every file"); csvWriter.writeComment("number of hit, misses and time stayed in Cache for every file"); csvWriter.writeComment("project: " + pid + ", cachesize: " + cachesize + ", blocksize: " + cachesize + ", prefetchsize: " + prefetchsize + ", cache replacement policy: " + cacheRep); csvWriter.write("file_id"); csvWriter.write("loc"); csvWriter.write("num_load"); csvWriter.write("num_hits"); csvWriter.write("num_misses"); csvWriter.write("duration"); csvWriter.endRecord(); csvWriter.write("0"); csvWriter.write("0"); csvWriter.write("0"); csvWriter.write("0"); csvWriter.write("0"); csvWriter.write(Integer.toString(cache.getTotalDuration())); csvWriter.endRecord(); // else assume that the file already has the correct header line // write out record //XXX rewrite with built in iteratable for (CacheItem ci : cache){ csvWriter.write(Integer.toString(ci.getEntityId())); csvWriter.write(Integer.toString(ci.getLOC())); // LOC at time of last update csvWriter.write(Integer.toString(ci.getLoadCount())); csvWriter.write(Integer.toString(ci.getHitCount())); csvWriter.write(Integer.toString(ci.getMissCount())); csvWriter.write(Integer.toString(ci.getDuration())); csvWriter.endRecord(); } csvWriter.close(); } catch (IOException e) { e.printStackTrace(); } } private int getCommitCount() { return commits; } public CsvWriter getCsvWriter() { return csvWriter; } }
package com.appstax; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.Map; public final class AppstaxObject { private static final String KEY_OBJECTS = "objects"; private static final String KEY_CREATED = "sysCreated"; private static final String KEY_UPDATED = "sysUpdated"; private static final String KEY_ID = "sysObjectId"; private static final String OPERATOR = " and "; private String collection; private JSONObject properties; public AppstaxObject(String collection) { this(collection, new JSONObject()); } protected AppstaxObject(String collection, JSONObject properties) { this.collection = collection; this.properties = properties; } public String getId() { return this.properties.has(KEY_ID) ? this.properties.getString(KEY_ID) : null; } public String getCollection() { return this.collection; } public void put(String key, Object val) { this.properties.put(key, val); } public Object get(String key) { return this.properties.has(key) ? this.properties.get(key) : null; } protected AppstaxObject save() { return this.getId() == null ? this.post() : this.put(); } protected AppstaxObject post() { String path = AppstaxPaths.collection(this.getCollection()); JSONObject meta = AppstaxClient.request(AppstaxClient.Method.POST, path, this.properties); this.put(KEY_CREATED, meta.get(KEY_CREATED)); this.put(KEY_UPDATED, meta.get(KEY_UPDATED)); this.put(KEY_ID, meta.get(KEY_ID)); return this; } protected AppstaxObject put() { String path = AppstaxPaths.object(this.getCollection(), this.getId()); JSONObject meta = AppstaxClient.request(AppstaxClient.Method.PUT, path, this.properties); this.put(KEY_UPDATED, meta.get(KEY_UPDATED)); return this; } protected AppstaxObject remove() { String path = AppstaxPaths.object(this.getCollection(), this.getId()); this.properties = AppstaxClient.request(AppstaxClient.Method.DELETE, path, this.properties); return this; } protected AppstaxObject refresh() { String path = AppstaxPaths.object(this.getCollection(), this.getId()); this.properties = AppstaxClient.request(AppstaxClient.Method.GET, path, this.properties); return this; } protected static AppstaxObject find(String collection, String id) { String path = AppstaxPaths.object(collection, id); JSONObject properties = AppstaxClient.request(AppstaxClient.Method.GET, path); return new AppstaxObject(collection, properties); } protected static List<AppstaxObject> find(String collection) { String path = AppstaxPaths.collection(collection); return objects(collection, AppstaxClient.request(AppstaxClient.Method.GET, path)); } protected static List<AppstaxObject> filter(String collection, String filter) { String path = AppstaxPaths.filter(collection, filter); return objects(collection, AppstaxClient.request(AppstaxClient.Method.GET, path)); } protected static List<AppstaxObject> filter(String collection, Map<String, String> properties) { StringBuilder builder = new StringBuilder(); for (Map.Entry<String, String> entry : properties.entrySet()) { builder.append(OPERATOR + entry.getKey() + "='" + entry.getValue() + "'"); } return filter(collection, builder.toString().replaceFirst(OPERATOR, "")); } protected static List<AppstaxObject> objects(String collection, JSONObject json) { ArrayList<AppstaxObject> objects = new ArrayList<AppstaxObject>(); JSONArray array = json.getJSONArray(KEY_OBJECTS); for(int i = 0; i < array.length(); i++) { objects.add(new AppstaxObject(collection, array.getJSONObject(i))); } return objects; } }
package de.learnlib.algorithms.angluin; import de.learnlib.algorithms.angluin.oracles.SimpleOracle; import de.learnlib.api.LearningAlgorithm; import de.learnlib.api.Query; import net.automatalib.automata.fsa.DFA; import net.automatalib.words.Alphabet; import net.automatalib.words.Word; import net.automatalib.words.impl.ArrayWord; import net.automatalib.words.impl.FastAlphabet; import net.automatalib.words.impl.Symbol; import net.automatalib.words.util.Words; import org.junit.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestSimpleAutomaton { private Symbol zero; private Symbol one; private LearningAlgorithm<DFA, Symbol, Boolean> angluin; @BeforeClass public void setup() { Alphabet<Symbol> alphabet = new FastAlphabet<>(); zero = new Symbol(0); one = new Symbol(1); alphabet.add(zero); alphabet.add(one); angluin = new Angluin<>(alphabet, new SimpleOracle()); } @Test(expectedExceptions = IllegalStateException.class) public void testGetHypothesisBeforeLearnIteration() { angluin.getHypothesisModel(); } @Test(expectedExceptions = IllegalStateException.class) public void testRefinementBeforeLearnIteration() { angluin.refineHypothesis(createCounterExample()); } @Test(dependsOnMethods = "testGetHypothesisBeforeLearnIteration") public void testFirstHypothesis() { angluin.startLearning(); DFA hypothesis = angluin.getHypothesisModel(); Assert.assertEquals(hypothesis.getStates().size(), 2); } @Test(dependsOnMethods = "testFirstHypothesis", expectedExceptions = IllegalStateException.class) public void testDuplicateLearnInvocation() { angluin.startLearning(); } @Test(dependsOnMethods = "testFirstHypothesis") public void testCounterExample() { angluin.refineHypothesis(createCounterExample()); DFA hypothesis = angluin.getHypothesisModel(); Assert.assertEquals(hypothesis.getStates().size(), 4); } private Query<Symbol, Boolean> createCounterExample() { Word<Symbol> counterExample = new ArrayWord<>(); counterExample = Words.append(counterExample, one, one, zero); Query<Symbol, Boolean> query = new Query<>(counterExample); query.setOutput(false); return query; } }
package com.csforge.sstable; import com.google.common.base.Charsets; import com.google.common.base.Strings; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.io.Resources; import jline.console.ConsoleReader; import jline.console.UserInterruptException; import jline.console.completer.FileNameCompleter; import jline.console.history.FileHistory; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.cql3.QueryProcessor; import org.apache.cassandra.cql3.statements.CreateTableStatement; import org.apache.cassandra.cql3.statements.CreateTypeStatement; import org.apache.cassandra.cql3.statements.ParsedStatement; import org.apache.cassandra.cql3.statements.SelectStatement; import org.apache.cassandra.db.rows.UnfilteredRowIterator; import org.apache.cassandra.exceptions.SyntaxException; import org.apache.commons.cli.*; import java.io.*; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.Collections; import java.util.List; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; /** * This is just an early hacking - proof of concept (don't judge) * * - TODO : REWRITE EVERYTHING FROM SCRATCH * * - TODO : UDTs, and UDFs * - TODO : EXPAND ON; like cqlsh for wide rows/tiny consoles * - TODO : File completer on sstable use/select */ public class Cqlsh { private static final Options options = new Options(); private static final String SCHEMA_OPTION = "s"; private static final String FILE_OPTION = "f"; private static final String MISSING_SSTABLES = errorMsg("No sstables set. Set the sstables using the 'USE pathToSSTable' command."); private static final String QUERY_PAGING_ALREADY_ENABLED = errorMsg("Query paging is already enabled. Use PAGING OFF to disable."); private static final String QUERY_PAGING_ALREADY_DISABLED = errorMsg("Query paging is not enabled."); private static final String IMPROPER_PAGING_COMMAND = errorMsg("Improper PAGING command."); private static final String QUERY_PAGING_ENABLED = "Now Query paging is enabled%nPage size: %d%n"; private static final String QUERY_PAGING_DISABLED = "Disabled Query paging."; private static final String PAGING_IS_ENABLED = "Query paging is currently enabled. Use PAGING OFF to disable%nPage size: %d%n"; private static final String PAGING_IS_DISABLED = "Query paging is currently disabled. Use PAGING ON to enable."; static String errorMsg(String msg) { return TableTransformer.ANSI_RED + msg + TableTransformer.ANSI_RESET; } static { Option schemaOption = new Option(SCHEMA_OPTION, true, "Schema file to use."); schemaOption.setRequired(false); Option fileOption = new Option(FILE_OPTION, true, "Execute commands from FILE, then exit."); options.addOption(schemaOption); options.addOption(fileOption); } public List<File> sstables = Lists.newArrayList(); public FileHistory history = null; private final String prompt = "\u001B[1;33mcqlsh\u001B[33m> \u001B[0m"; public CFMetaData metadata = null; private boolean done = false; ConsoleReader console; String innerBuffer; boolean inner = false; boolean paging = true; // TODO: Make configurable? int pageSize = 100; public Cqlsh() { try { history = new FileHistory(new File(System.getProperty("user.home"), ".sstable-tools-cqlsh")); console = new ConsoleReader(); console.setPrompt(prompt); console.setHistory(history); console.setHistoryEnabled(true); console.addCompleter(new FileNameCompleter()); console.setHandleUserInterrupt(true); } catch (Exception e) { e.printStackTrace(); } } public void startShell() throws Exception { try { String line = null; while (!done && (line = console.readLine()) != null) { evalLine(line); } if (line == null) { done = true; } } catch (IOException e) { System.err.println("Error in console session: " + e.getMessage()); System.exit(-4); } } public void doUse(String command) throws Exception { String rest = command.substring(4); // "USE " Pattern p = Pattern.compile("((\"[^\"]+\")|[^\" ]+)"); Matcher m = p.matcher(rest); this.sstables = Lists.newArrayList(); while (m.find()) { String arg = m.group().replace("\"", ""); File sstable = new File(arg); if (sstable.exists() && sstable.isFile()) { this.sstables.add(sstable); } else { try { if (sstable.exists()) { PathMatcher matcher = FileSystems.getDefault().getPathMatcher("glob:**/*-Data.db"); Files.walkFileTree(Paths.get(arg), Sets.newHashSet(), 1, new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException { if (matcher.matches(path)) { sstables.add(path.toFile()); } return FileVisitResult.CONTINUE; } public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException { return FileVisitResult.CONTINUE; } }); } else { System.out.println("Cannot find " + sstable.getAbsolutePath()); } } catch (Exception e) { e.printStackTrace(); } } } for (File f : sstables) { System.out.println("Using: " + f.getAbsolutePath()); } if (!sstables.isEmpty()) { metadata = CassandraUtils.tableFromBestSource(sstables.get(0)); } } public void doDump(String command) throws Exception { if(sstables.isEmpty()) { System.out.println(MISSING_SSTABLES); return; } Query query; if (command.length() > 5) { query = getQuery("select * from sstables " + command.substring(5)); } else { query = getQuery("select * from sstables"); } Stream<UnfilteredRowIterator> partitions = CassandraUtils.asStream(query.getScanner()); partitions.forEach(partition -> { if(!partition.partitionLevelDeletion().isLive()) { System.out.println("[" + metadata.getKeyValidator().getString(partition.partitionKey().getKey()) + "] " + partition.partitionLevelDeletion()); } if (!partition.staticRow().isEmpty()) { System.out.println( "[" + metadata.getKeyValidator().getString(partition.partitionKey().getKey()) + "] " + partition.staticRow().toString(metadata, true)); } partition.forEachRemaining(row -> { System.out.println( "[" + metadata.getKeyValidator().getString(partition.partitionKey().getKey()) + "] " + row.toString(metadata, true)); }); }); System.out.println(); } public void doQuery(String command) throws Exception { Query q = getQuery(command); System.out.println(); if (q == null) { System.out.println(MISSING_SSTABLES); } else if (paging) { ResultSetData resultData = getQuery(command).getResults(pageSize); TableTransformer.dumpResults(metadata, resultData.getResultSet(), System.out); boolean terminated = false; if (resultData.getPagingData().hasMorePages()) { console.setHistoryEnabled(false); console.setPrompt(""); while (resultData.getPagingData().hasMorePages()) { System.out.printf("%n try { String input = console.readLine(); if (input == null) { done = true; terminated = true; break; } } catch (UserInterruptException uie) { // User interrupted, stop paging. terminated = true; break; } resultData = getQuery(command).getResults(pageSize, resultData.getPagingData()); TableTransformer.dumpResults(metadata, resultData.getResultSet(), System.out); } } if (!terminated) { System.out.printf("%n(%s rows)%n", resultData.getPagingData().getRowCount()); } console.setPrompt(prompt); console.setHistoryEnabled(true); } else { ResultSetData resultData = getQuery(command).getResults(); TableTransformer.dumpResults(metadata, resultData.getResultSet(), System.out); System.out.printf("%n(%s rows)%n", resultData.getPagingData().getRowCount()); } } public void doCreate(String command) throws Exception { innerBuffer = command; inner = true; history.removeLast(); console.setHistoryEnabled(false); console.setPrompt("... "); try { while (inner) { try { ParsedStatement statement = QueryProcessor.parseStatement(innerBuffer); inner = false; history.add(innerBuffer); if (statement instanceof CreateTableStatement.RawStatement) { CassandraUtils.cqlOverride = innerBuffer; } else if (statement instanceof CreateTypeStatement) { try { // TODO work around type mess System.out.println(CassandraUtils.callPrivate(statement, "createType")); } catch (Exception e) { e.printStackTrace(); } } //CreateTableStatement$RawStatement } catch (SyntaxException e) { if (!innerBuffer.trim().endsWith(";")) { String line = console.readLine(); if (!inner) { evalLine(line); } else { innerBuffer += " " + line; } } else { inner = false; System.out.println(TableTransformer.ANSI_RED + e.getMessage() + TableTransformer.ANSI_RESET); } } } } finally { console.setHistoryEnabled(true); console.setPrompt(prompt); innerBuffer = ""; inner = false; } } public void doPagingConfig(String command) throws Exception { String mode = command.substring(6).trim().toLowerCase(); // trim all semicolons. while (mode.endsWith(";")) { mode = mode.substring(0, mode.length()); } mode = mode.trim(); switch (mode) { case "": if (paging) { System.out.printf(PAGING_IS_ENABLED, pageSize); } else { System.out.println(PAGING_IS_DISABLED); } break; case "on": if (paging) { System.err.println(QUERY_PAGING_ALREADY_ENABLED); } else { paging = true; System.out.printf(QUERY_PAGING_ENABLED, pageSize); } break; case "off": if (!paging) { System.err.println(QUERY_PAGING_ALREADY_DISABLED); } else { paging = false; System.out.println(QUERY_PAGING_DISABLED); } break; default: try { pageSize = Integer.parseInt(mode); paging = true; System.out.printf(QUERY_PAGING_ENABLED, pageSize); } catch (NumberFormatException e) { System.err.println(IMPROPER_PAGING_COMMAND); } } } public Query getQuery(String command) throws Exception { SelectStatement.RawStatement statement = (SelectStatement.RawStatement) QueryProcessor.parseStatement(command); Query query; if (statement.columnFamily().matches("sstables?")) { if(sstables.isEmpty()) { return null; } metadata = CassandraUtils.tableFromBestSource(sstables.get(0)); return new Query(command, sstables, metadata); } else { File path = new File(statement.columnFamily()); if (!path.exists()) { throw new FileNotFoundException(path.getAbsolutePath()); } metadata = CassandraUtils.tableFromBestSource(path); return new Query(command, Collections.singleton(path), metadata); } } public void evalLine(String line) throws Exception { // TODO: Handle semi-colons in quoted identifers. String cmds[] = line.split(";"); for (String command : cmds) { command = command.trim(); if (command.isEmpty()) { continue; } else if (command.equals("exit") || command.equals("quit")) { done = true; continue; } else if (command.toLowerCase().trim().startsWith("describe schema")) { if(CassandraUtils.cqlOverride != null) { System.out.println(CassandraUtils.cqlOverride); } else if (metadata != null) { System.out.println(metadata); } else { System.err.format("%sNo current metadata set, use a CREATE TABLE statement to set%s%n", TableTransformer.ANSI_RED, TableTransformer.ANSI_RESET); } continue; } else if (command.toLowerCase().trim().startsWith("describe sstable")) { System.out.println(); for(File f : sstables) { System.out.println("\u001B[1;34m" + f.getAbsolutePath()); System.out.println(TableTransformer.ANSI_CYAN + Strings.repeat("=", f.getAbsolutePath().length()) + TableTransformer.ANSI_RESET); CassandraUtils.printStats(f.getAbsolutePath(), System.out, true); System.out.println(); } continue; } else if (command.toLowerCase().startsWith("use ")) { doUse(command); continue; } else if (command.toLowerCase().startsWith("dump")) { doDump(command); continue; } else if (command.toLowerCase().equals("help")) { try { System.out.println(Resources.toString(Resources.getResource("cqlsh-help"), Charsets.UTF_8)); } catch (IOException e) { e.printStackTrace(); System.exit(-5); } continue; } else if (command.length() >= 6) { String queryType = command.substring(0, 6).toLowerCase(); switch (queryType) { case "select": doQuery(command); continue; case "create": doCreate(command); continue; case "update": case "insert": case "delete": System.err.format("%sQuery '%s' is not supported since this tool is read-only.%s%n", TableTransformer.ANSI_RED, command, TableTransformer.ANSI_RESET); continue; case "paging": doPagingConfig(command); continue; } } System.err.format("%sUnknown command: %s%s%n", TableTransformer.ANSI_RED, command, TableTransformer.ANSI_RESET); } } public static void main(String args[]) { CommandLineParser parser = new PosixParser(); CommandLine cmd = null; try { cmd = parser.parse(options, args); } catch (ParseException e) { System.err.format("%sFailure parsing arguments: %s%s%n%n", TableTransformer.ANSI_RED, e.getMessage(), TableTransformer.ANSI_RESET); try (PrintWriter errWriter = new PrintWriter(System.err, true)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(errWriter, 120, "cqlsh sstable [sstable ...]", String.format("%nOffline CQL Shell for Apache Cassandra 3.x%nOptions:"), options, 2, 1, "", true); } finally { System.exit(-1); } } final Cqlsh sh = new Cqlsh(); String schemaPath = cmd.getOptionValue(SCHEMA_OPTION); if (schemaPath != null) { try (InputStream schemaStream = new FileInputStream(new File(schemaPath))) { sh.metadata = CassandraUtils.tableFromCQL(schemaStream); } catch (IOException e) { System.err.println("Error reading schema metadata: " + e.getMessage()); System.exit(-2); } System.setProperty("sstabletools.schema", schemaPath); } List<File> sstables = Lists.newArrayList(); for (String sstable : cmd.getArgs()) { File file = new File(sstable); if (!file.exists()) { System.err.println("Non-existant sstable file provided: " + sstable); System.exit(-3); } sstables.add(file); } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { try { sh.history.flush(); } catch (IOException e) { System.err.println("Couldn't flush history on shutdown. Reason:" + e.getMessage()); } } }); String cqlFilePath = cmd.getOptionValue(FILE_OPTION); if (cqlFilePath != null) { try (Scanner s = new Scanner(new FileInputStream(cqlFilePath))) { while (s.hasNextLine()) { try { sh.evalLine(s.nextLine()); } catch (Exception e) { e.printStackTrace(); break; } } } catch (FileNotFoundException ex) { System.err.println("Cannot find " + cqlFilePath); System.exit(-4); } } else { while (!sh.done) { try { sh.startShell(); } catch (UserInterruptException e) { } catch (Exception e) { e.printStackTrace(); } } try { sh.history.flush(); } catch (IOException e) { } sh.console.shutdown(); } } }
package com.gildedrose; import static java.lang.Math.max; import static java.lang.Math.min; class GildedRose { private static final int QUALITY_FLOOR = 0; private static final int QUALITY_CEILING = 50; private static final String AGED_BRIE = "Aged Brie"; private static final String BACKSTAGE_PASSES_TO_A_TAFKAL80ETC_CONCERT = "Backstage passes to a TAFKAL80ETC concert"; private static final String SULFURAS_HAND_OF_RAGNAROS = "Sulfuras, Hand of Ragnaros"; Item[] items; public GildedRose(Item[] items) { this.items = items; for (Item item : items) { item.quality = (item.quality < 0) ? 0 : item.quality; } } public void updateQuality() { for (Item item : items) { updateItem(item); } } private void updateItem(Item item) { if (isAgedBrie(item) || isBackstagePass(item)) { incrementQuality(item); if (isBackstagePass(item)) { if (item.sellIn < 11) { incrementQuality(item); } if (item.sellIn < 6) { incrementQuality(item); } } } else { decrementQuality(item); } if (!isSulfurasHandOfRagnaros(item)) { decrementDaysRemainingToSell(item); } if (pastSellBy(item)) { if (!isAgedBrie(item)) { if (!isBackstagePass(item)) { decrementQuality(item); } else { makeWorthless(item); } } else { incrementQuality(item); } } } private boolean pastSellBy(Item item) { return item.sellIn < 0; } private void decrementDaysRemainingToSell(Item item) { item.sellIn = item.sellIn - 1; } private boolean isSulfurasHandOfRagnaros(Item item) { return item.name.equals(SULFURAS_HAND_OF_RAGNAROS); } private boolean isAgedBrie(Item item) { return item.name.equals(AGED_BRIE); } private boolean isBackstagePass(Item item) { return item.name.equals(BACKSTAGE_PASSES_TO_A_TAFKAL80ETC_CONCERT); } private void makeWorthless(Item item) { item.quality = item.quality - item.quality; } private void incrementQuality(Item item) { item.quality = min(QUALITY_CEILING, item.quality + 1); } private void decrementQuality(Item item) { if (!isSulfurasHandOfRagnaros(item)) { item.quality = max(QUALITY_FLOOR, item.quality - 1); } } }
package liquibase.sqlgenerator.core; import liquibase.database.Database; import liquibase.database.typeconversion.TypeConverterFactory; import liquibase.database.core.SybaseDatabase; import liquibase.exception.ValidationErrors; import liquibase.sql.Sql; import liquibase.sql.UnparsedSql; import liquibase.sqlgenerator.SqlGenerator; import liquibase.sqlgenerator.SqlGeneratorChain; import liquibase.statement.core.CreateDatabaseChangeLogTableStatement; public class CreateDatabaseChangeLogTableGeneratorSybase implements SqlGenerator<CreateDatabaseChangeLogTableStatement> { public int getPriority() { return PRIORITY_DATABASE; } public boolean supports(CreateDatabaseChangeLogTableStatement statement, Database database) { return database instanceof SybaseDatabase; } public ValidationErrors validate(CreateDatabaseChangeLogTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { return new ValidationErrors(); } public Sql[] generateSql(CreateDatabaseChangeLogTableStatement statement, Database database, SqlGeneratorChain sqlGeneratorChain) { return new Sql[] { new UnparsedSql("CREATE TABLE " + database.escapeTableName(database.getDefaultSchemaName(), database.getDatabaseChangeLogTableName()) + " (ID VARCHAR(150) NOT NULL, " + "AUTHOR VARCHAR(150) NOT NULL, " + "FILENAME VARCHAR(255) NOT NULL, " + "DATEEXECUTED " + TypeConverterFactory.getInstance().findTypeConverter(database).getDateTimeType() + " NOT NULL, " + "ORDEREXECUTED INT NOT NULL UNIQUE, " + "EXECTYPE VARCHAR(10) NOT NULL, " + "MD5SUM VARCHAR(35) NULL, " + "DESCRIPTION VARCHAR(255) NULL, " + "COMMENTS VARCHAR(255) NULL, " + "TAG VARCHAR(255) NULL, " + "LIQUIBASE VARCHAR(20) NULL, " + "PRIMARY KEY(ID, AUTHOR, FILENAME))") }; //To change body of implemented methods use File | Settings | File Templates. } }
package com.github.maven_nar; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; import java.util.ListIterator; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Parameter; import org.apache.tools.ant.types.Environment.Variable; import org.codehaus.plexus.util.StringUtils; import com.github.maven_nar.cpptasks.CCTask; import com.github.maven_nar.cpptasks.CompilerDef; import com.github.maven_nar.cpptasks.LinkerDef; import com.github.maven_nar.cpptasks.types.SystemIncludePath; import com.google.common.collect.Sets; public class Msvc { @Parameter private File home; private AbstractNarMojo mojo; private final Set<String> paths = new LinkedHashSet<String>(); @Parameter private String version; @Parameter private File windowsSdkHome; @Parameter private String windowsSdkVersion; @Parameter private String tempPath; private File windowsHome; private String toolPathWindowsSDK; private String toolPathLinker; private List<File> sdkIncludes = new ArrayList<>(); private List<File> sdkLibs = new ArrayList<>(); private Set<String> libsRequired = Sets.newHashSet("ucrt", "um", "shared", "winrt"); private boolean addIncludePath(final CCTask task, final File home, final String subDirectory) throws MojoExecutionException { if (home == null) { return false; } final File file = new File(home, subDirectory); if (file.exists()) return addIncludePathToTask(task, file); return false; } private boolean addIncludePathToTask(final CCTask task, final File file) throws MojoExecutionException { try { final SystemIncludePath includePath = task.createSysIncludePath(); final String fullPath = file.getCanonicalPath(); includePath.setPath(fullPath); return true; } catch (final IOException e) { throw new MojoExecutionException("Unable to add system include: " + file.getAbsolutePath(), e); } } private boolean addPath(final File home, final String path) { if (home != null) { final File directory = new File(home, path); if (directory.exists()) { try { final String fullPath = directory.getCanonicalPath(); this.paths.add(fullPath); return true; } catch (final IOException e) { throw new IllegalArgumentException("Unable to get path: " + directory, e); } } } return false; } public void configureCCTask(final CCTask task) throws MojoExecutionException { if (OS.WINDOWS.equals(mojo.getOS()) && "msvc".equalsIgnoreCase(mojo.getLinker().getName())) { addIncludePath(task, this.home, "VC/include"); addIncludePath(task, this.home, "VC/atlmfc/include"); if (compareVersion(this.windowsSdkVersion, "7.1A") <= 0) { addIncludePath(task, this.windowsSdkHome, "include"); } else { for (File sdkInclude : sdkIncludes) addIncludePathToTask(task, sdkInclude); } task.addEnv(getPathVariable()); // TODO: supporting running with clean environment - addEnv sets // newEnvironemnt by default // task.setNewenvironment(false); Variable envVariable = new Variable(); // cl needs SystemRoot env var set, otherwise D8037 is raised (bogus // message) envVariable.setKey("SystemRoot"); envVariable.setValue(this.windowsHome.getAbsolutePath()); task.addEnv(envVariable); // cl needs TMP otherwise D8050 is raised c1xx.dll envVariable = new Variable(); envVariable.setKey("TMP"); envVariable.setValue(getTempPath()); task.addEnv(envVariable); } } public void configureLinker(final LinkerDef linker) throws MojoExecutionException { final String os = mojo.getOS(); if (os.equals(OS.WINDOWS) && "msvc".equalsIgnoreCase(mojo.getLinker().getName())) { final String arch = mojo.getArchitecture(); // Visual Studio if ("x86".equals(arch)) { linker.addLibraryDirectory(this.home, "VC/lib"); linker.addLibraryDirectory(this.home, "VC/atlmfc/lib"); } else { linker.addLibraryDirectory(this.home, "VC/lib/" + arch); linker.addLibraryDirectory(this.home, "VC/atlmfc/lib/" + arch); } // Windows SDK String sdkArch = arch; if ("amd64".equals(arch)) { sdkArch = "x64"; } // 6 lib ?+ lib/x86 or lib/x64 if (compareVersion(this.windowsSdkVersion, "8.0") < 0) { if ("x86".equals(arch)) { linker.addLibraryDirectory(this.windowsSdkHome, "lib"); } else { linker.addLibraryDirectory(this.windowsSdkHome, "lib/" + sdkArch); } } else for (File sdkLib : sdkLibs) linker.addLibraryDirectory(sdkLib, sdkArch); } } private String getTempPath(){ if( null == tempPath ){ tempPath = System.getenv("TMP"); if( null == tempPath ) tempPath = System.getenv("TEMP"); if( null == tempPath ) tempPath = "C:\\Temp"; } return tempPath; } public Variable getPathVariable() { if (this.paths.isEmpty()) { return null; } final Variable pathVariable = new Variable(); pathVariable.setKey("PATH"); pathVariable.setValue(StringUtils.join(this.paths.iterator(), File.pathSeparator)); return pathVariable; } public String getVersion() { return this.version; } public String getWindowsSdkVersion() { return this.windowsSdkVersion; } private void init() throws MojoFailureException, MojoExecutionException { final String mojoOs = this.mojo.getOS(); if (NarUtil.isWindows() && OS.WINDOWS.equals(mojoOs)) { windowsHome = new File(System.getenv("SystemRoot")); initVisualStudio(); initWindowsSdk(); initPath(); } else { this.version = ""; this.windowsSdkVersion = ""; } } private void initPath() throws MojoExecutionException { final String mojoArchitecture = this.mojo.getArchitecture(); final String osArchitecture = NarUtil.getArchitecture(null); // 32 bit build on 64 bit OS can be built with 32 bit tool, or 64 bit tool // in amd64_x86 - currently defaulting to prefer 64 bit tools - match os final boolean matchMojo = false; // TODO: toolset architecture // match os - os x86 mojo(x86 / x86_amd64); os x64 mojo(amd64_x86 / amd64); // 32bit - force 32 on 64bit mojo(x86 / x86_amd64) // match mojo - os x86 is as above; os x64 mojo (x86 / amd64) // Cross tools first if necessary, platform tools second, more generic tools // later if (!osArchitecture.equals(mojoArchitecture) && !matchMojo) { if (!addPath(this.home, "VC/bin/" + osArchitecture + "_" + mojoArchitecture)) { throw new MojoExecutionException("Unable to find compiler for architecture " + mojoArchitecture + ".\n" + new File(this.home, "VC/bin/" + osArchitecture + "_" + mojoArchitecture)); } toolPathLinker = new File(this.home, "VC/bin/" + osArchitecture + "_" + mojoArchitecture).getAbsolutePath(); } if (null == toolPathLinker) { if ("amd64".equals(mojoArchitecture)) toolPathLinker = new File(this.home, "VC/bin/amd64").getAbsolutePath(); else toolPathLinker = new File(this.home, "VC/bin").getAbsolutePath(); } if ("amd64".equals(osArchitecture) && !matchMojo) { addPath(this.home, "VC/bin/amd64"); } else { addPath(this.home, "VC/bin"); } addPath(this.home, "VC/VCPackages"); addPath(this.home, "Common7/Tools"); addPath(this.home, "Common7/IDE"); // 64 bit tools if present are preferred if (compareVersion(this.windowsSdkVersion, "7.1A") <= 0) { if ("amd64".equals(osArchitecture) && !matchMojo) { addPath(this.windowsSdkHome, "bin/x64"); } addPath(this.windowsSdkHome, "bin"); } else { if ("amd64".equals(osArchitecture) && !matchMojo) { addPath(this.windowsSdkHome, "bin/x64"); } addPath(this.windowsSdkHome, "bin/x86"); } if ("amd64".equals(mojoArchitecture)) { toolPathWindowsSDK = new File(this.windowsSdkHome, "bin/x64").getAbsolutePath(); } else if (compareVersion(this.windowsSdkVersion, "7.1A") <= 0) { toolPathWindowsSDK = new File(this.windowsSdkHome, "bin").getAbsolutePath(); } else { toolPathWindowsSDK = new File(this.windowsSdkHome, "bin/x86").getAbsolutePath(); } // clearing the path, add back the windows system folders addPath(this.windowsHome, "System32"); addPath(this.windowsHome, ""); addPath(this.windowsHome, "System32/wbem"); } private void initVisualStudio() throws MojoFailureException, MojoExecutionException { mojo.getLog().debug(" -- Searching for usable VisualStudio "); if (this.version != null && this.version.trim().length() > 1) { String internalVersion; Pattern r = Pattern.compile("(\\d+)\\.*(\\d)"); Matcher matcher = r.matcher(this.version); if (matcher.find()) { internalVersion = matcher.group(1) + matcher.group(2); this.version = matcher.group(1) + "." + matcher.group(2); } else { throw new MojoExecutionException("msvc.version must be the internal version in the form 10.0 or 120"); } if (this.home == null) { final String commontToolsVar = System.getenv("VS" + internalVersion + "COMNTOOLS"); if (commontToolsVar != null && commontToolsVar.trim().length() > 0) { final File commonToolsDirectory = new File(commontToolsVar); if (commonToolsDirectory.exists()) { this.home = commonToolsDirectory.getParentFile().getParentFile(); } } // TODO: else Registry might be more reliable but adds dependency to be // able to acccess - HKLM\SOFTWARE\Microsoft\Visual Studio\Major.Minor:InstallDir } mojo.getLog() .debug(String.format(" VisualStudio %1s (%2s) found %3s ", this.version, internalVersion, this.home)); } else { this.version = ""; for (final Entry<String, String> entry : System.getenv().entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); final Pattern versionPattern = Pattern.compile("VS(\\d+)(\\d)COMNTOOLS"); final Matcher matcher = versionPattern.matcher(key); if (matcher.matches()) { final String version = matcher.group(1) + "." + matcher.group(2); if (version.compareTo(this.version) > 0) { final File commonToolsDirectory = new File(value); if (commonToolsDirectory.exists()) { this.version = version; this.home = commonToolsDirectory.getParentFile().getParentFile(); mojo.getLog().debug( String.format(" VisualStudio %1s (%2s) found %3s ", this.version, matcher.group(1) + matcher.group(2), this.home)); } } } } if (this.version.length() == 0) { final TextStream out = new StringTextStream(); final TextStream err = new StringTextStream(); final TextStream dbg = new StringTextStream(); NarUtil.runCommand("link", new String[] { "/?" }, null, null, out, err, dbg, null, true); final Pattern p = Pattern.compile("(\\d+\\.\\d+)\\.\\d+(\\.\\d+)?"); final Matcher m = p.matcher(out.toString()); if (m.find()) { this.version = m.group(1); mojo.getLog().debug( String.format(" VisualStudio Not found but link runs and reports version %1s (%2s)", this.version, m.group(0))); } else { throw new MojoExecutionException( "msvc.version not specified and no VS<Version>COMNTOOLS environment variable can be found"); } } } } private final Comparator<File> versionComparator = new Comparator<File>() { @Override public int compare(File o1, File o2) { // will be sorted smallest first, so we need to invert the order of // the objects String firstDir = o2.getName(), secondDir = o1.getName(); if (firstDir.charAt(0) == 'v') { // remove 'v' and 'A' at the end firstDir = firstDir.substring(1, firstDir.length() - 1); secondDir = secondDir.substring(1, secondDir.length() - 1); } // impossible that two dirs are the same String[] firstVersionString = firstDir.split("\\."), secondVersionString = secondDir.split("\\."); int maxIdx = Math.min(firstVersionString.length, secondVersionString.length); int deltaVer; try { for (int i = 0; i < maxIdx; i++) if ((deltaVer = Integer.parseInt(firstVersionString[i]) - Integer.parseInt(secondVersionString[i])) != 0) return deltaVer; } catch (NumberFormatException e) { return firstDir.compareTo(secondDir); } if (firstVersionString.length > maxIdx) // 10.0.150 > 10.0 return 1; else if (secondVersionString.length > maxIdx) // 10.0 < 10.0.150 return -1; return 0; // impossible that they are the same } }; private boolean foundSDK = false; private void initWindowsSdk() throws MojoExecutionException { if(this.windowsSdkVersion != null && this.windowsSdkVersion.trim().equals("")) this.windowsSdkVersion = null; mojo.getLog().debug(" -- Searching for usable WindowSDK "); // newer first: 10 -> 8.1 -> 8.0 -> 7.1 and look for libs specified for (final File directory : Arrays.asList( new File("C:/Program Files (x86)/Windows Kits"), new File("C:/Program Files (x86)/Microsoft SDKs/Windows"), new File("C:/Program Files/Windows Kits"), new File("C:/Program Files/Microsoft SDKs/Windows") )) { if (directory.exists()) { final File[] kitDirectories = directory.listFiles(); Arrays.sort(kitDirectories, versionComparator); if (kitDirectories != null) { for (final File kitDirectory : kitDirectories) { if (new File(kitDirectory, "Include").exists()) { // legacy SDK String kitVersion = kitDirectory.getName(); if (kitVersion.charAt(0) == 'v') { kitVersion = kitVersion.substring(1); } if (this.windowsSdkVersion!=null && compareVersion(kitVersion,this.windowsSdkVersion)>0) continue; // skip versions higher than the previous version mojo.getLog() .debug(String.format(" WindowSDK %1s found %2s", kitVersion, kitDirectory.getAbsolutePath())); if (kitVersion.matches("\\d+\\.\\d+?[A-Z]?")) { // windows <= 8.1 legacySDK(kitDirectory); } else if (kitVersion.matches("\\d+?")) { // windows 10 SDK supports addNewSDKLibraries(kitDirectory); } } } if (libsRequired.size() == 0) // need it here to break out of the outer loop break; } } } if (!foundSDK) throw new MojoExecutionException("msvc.windowsSdkVersion not specified and versions cannot be found"); mojo.getLog().debug(String.format(" Using WindowSDK %1s found %2s", this.windowsSdkVersion, this.windowsSdkHome)); } private void addNewSDKLibraries(final File kitDirectory) { // multiple installs List<File> kitVersionDirectories = Arrays.asList(new File(kitDirectory, "Include").listFiles()); Collections.sort(kitVersionDirectories, versionComparator); ListIterator<File> kitVersionDirectoriesIt = kitVersionDirectories.listIterator(); File kitVersionDirectory = null; while (kitVersionDirectoriesIt.hasNext() && (kitVersionDirectory = kitVersionDirectoriesIt.next()) != null) { if (new File(kitVersionDirectory, "ucrt").exists()) { break; } } if (kitVersionDirectory != null) { String version = kitVersionDirectory.getName(); mojo.getLog().debug(String.format(" Latest Win %1s KitDir at %2s", kitVersionDirectory.getName(), kitVersionDirectory.getAbsolutePath())); // add the libraries found: File includeDir = new File(kitDirectory, "Include/" + version); File libDir = new File(kitDirectory, "Lib/" + version); addSDKLibs(includeDir, libDir); } } private void setKit(File home) { if (!foundSDK) { if(this.windowsSdkVersion==null) this.windowsSdkVersion = home.getName(); if(this.windowsSdkHome==null) this.windowsSdkHome = home; foundSDK=true; } } private void legacySDK(final File kitDirectory) { File includeDir = new File(kitDirectory, "Include"); if(includeDir.exists()){ File libDir = new File(kitDirectory, "Lib"); File usableLibDir = null; for( final File libSubDir : libDir.listFiles()){ final File um = new File(libSubDir,"um"); if( um.exists()) usableLibDir = libSubDir; } if( null == usableLibDir ) usableLibDir = libDir.listFiles()[0]; addSDKLibs(includeDir, usableLibDir); setKit(kitDirectory); } } private void addSDKLibs(File includeDir, File libdir) { final File[] libs = includeDir.listFiles(); for (final File libIncludeDir : libs) { // <libName> <include path> <lib path> if (libsRequired.remove(libIncludeDir.getName())) { mojo.getLog().debug(String.format(" Using directory %1s for library %2s", libIncludeDir.getAbsolutePath(), libIncludeDir.getName())); sdkIncludes.add(libIncludeDir); sdkLibs.add(new File(libdir, libIncludeDir.getName())); } } } public void setMojo(final AbstractNarMojo mojo) throws MojoFailureException, MojoExecutionException { if (mojo != this.mojo) { this.mojo = mojo; init(); } } @Override public String toString() { return this.home + "\n" + this.windowsSdkHome; } public String getToolPath() { return this.toolPathLinker; } public String getSDKToolPath() { return this.toolPathWindowsSDK; } public void setToolPath(CompilerDef compilerDef, String name) { if ("res".equals(name) || "mc".equals(name) || "idl".equals(name)) { compilerDef.setToolPath(this.toolPathWindowsSDK); } else { compilerDef.setToolPath(this.toolPathLinker); } } public int compareVersion(Object o1, Object o2) { String version1 = (String) o1; String version2 = (String) o2; VersionTokenizer tokenizer1 = new VersionTokenizer(version1); VersionTokenizer tokenizer2 = new VersionTokenizer(version2); int number1 = 0, number2 = 0; String suffix1 = "", suffix2 = ""; while (tokenizer1.MoveNext()) { if (!tokenizer2.MoveNext()) { do { number1 = tokenizer1.getNumber(); suffix1 = tokenizer1.getSuffix(); if (number1 != 0 || suffix1.length() != 0) { // Version one is longer than number two, and non-zero return 1; } } while (tokenizer1.MoveNext()); // Version one is longer than version two, but zero return 0; } number1 = tokenizer1.getNumber(); suffix1 = tokenizer1.getSuffix(); number2 = tokenizer2.getNumber(); suffix2 = tokenizer2.getSuffix(); if (number1 < number2) { // Number one is less than number two return -1; } if (number1 > number2) { // Number one is greater than number two return 1; } boolean empty1 = suffix1.length() == 0; boolean empty2 = suffix2.length() == 0; if (empty1 && empty2) continue; // No suffixes if (empty1) return 1; // First suffix is empty (1.2 > 1.2b) if (empty2) return -1; // Second suffix is empty (1.2a < 1.2) // Lexical comparison of suffixes int result = suffix1.compareTo(suffix2); if (result != 0) return result; } if (tokenizer2.MoveNext()) { do { number2 = tokenizer2.getNumber(); suffix2 = tokenizer2.getSuffix(); if (number2 != 0 || suffix2.length() != 0) { // Version one is longer than version two, and non-zero return -1; } } while (tokenizer2.MoveNext()); // Version two is longer than version one, but zero return 0; } return 0; } // VersionTokenizer.java class VersionTokenizer { private final String _versionString; private final int _length; private int _position; private int _number; private String _suffix; private boolean _hasValue; public int getNumber() { return _number; } public String getSuffix() { return _suffix; } public boolean hasValue() { return _hasValue; } public VersionTokenizer(String versionString) { if (versionString == null) throw new IllegalArgumentException("versionString is null"); _versionString = versionString; _length = versionString.length(); } public boolean MoveNext() { _number = 0; _suffix = ""; _hasValue = false; // No more characters if (_position >= _length) return false; _hasValue = true; while (_position < _length) { char c = _versionString.charAt(_position); if (c < '0' || c > '9') break; _number = _number * 10 + (c - '0'); _position++; } int suffixStart = _position; while (_position < _length) { char c = _versionString.charAt(_position); if (c == '.') break; _position++; } _suffix = _versionString.substring(suffixStart, _position); if (_position < _length) _position++; return true; } } }
package com.github.maven_nar; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashSet; import java.util.List; import java.util.ListIterator; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.maven.artifact.versioning.DefaultArtifactVersion; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Parameter; import org.apache.tools.ant.types.Environment.Variable; import org.codehaus.plexus.util.StringUtils; import com.github.maven_nar.cpptasks.CCTask; import com.github.maven_nar.cpptasks.CompilerDef; import com.github.maven_nar.cpptasks.LinkerDef; import com.github.maven_nar.cpptasks.types.SystemIncludePath; import com.google.common.collect.Sets; public class Msvc { @Parameter private File home; private AbstractNarMojo mojo; private final Set<String> paths = new LinkedHashSet<>(); /** * VisualStudio Linker version. Required. The values should be: * <ul> * <li>7.1 for VS 2003</li> * <li>8.0 for VS 2005</li> * <li>9.0 for VS 2008</li> * <li>10.0 for VS 2010</li> * <li>11.0 for VS 2012</li> * <li>12.00 for VS 2013</li> * <li>14.0 for VS 2015</li> * <li>15.0 for VS 2017</li> * </ul> */ @Parameter(defaultValue = "") private String version; @Parameter private File windowsSdkHome; @Parameter private String windowsSdkVersion; @Parameter private String tempPath; private File windowsHome; private String toolPathWindowsSDK; private String toolPathLinker; private List<File> sdkIncludes = new ArrayList<>(); private List<File> sdkLibs = new ArrayList<>(); private Set<String> libsRequired = Sets.newHashSet("ucrt", "um", "shared", "winrt"); @Parameter(defaultValue = "false") private boolean force_requested_arch; private boolean addIncludePath(final CCTask task, final File home, final String subDirectory) throws MojoExecutionException { if (home == null) { return false; } final File file = new File(home, subDirectory); if (file.exists()) return addIncludePathToTask(task, file); return false; } private boolean addIncludePathToTask(final CCTask task, final File file) throws MojoExecutionException { try { final SystemIncludePath includePath = task.createSysIncludePath(); final String fullPath = file.getCanonicalPath(); includePath.setPath(fullPath); return true; } catch (final IOException e) { throw new MojoExecutionException("Unable to add system include: " + file.getAbsolutePath(), e); } } private boolean addPath(final File home, final String path) { if (home != null) { final File directory = new File(home, path); if (directory.exists()) { try { final String fullPath = directory.getCanonicalPath(); paths.add(fullPath); return true; } catch (final IOException e) { throw new IllegalArgumentException("Unable to get path: " + directory, e); } } } return false; } static boolean isMSVC(final AbstractNarMojo mojo) { return isMSVC(mojo.getLinker().getName()); } static boolean isMSVC(final String name) { return "msvc".equalsIgnoreCase(name); } public void configureCCTask(final CCTask task) throws MojoExecutionException { if (OS.WINDOWS.equals(mojo.getOS()) && isMSVC(mojo)) { addIncludePath(task, home, "VC/include"); addIncludePath(task, home, "VC/atlmfc/include"); if (compareVersion(windowsSdkVersion, "7.1A") <= 0) { if (version.equals("8.0")) { // For VS 2005 the version of SDK is 2.0, but it needs more paths for (File sdkInclude : sdkIncludes) { addIncludePathToTask(task, sdkInclude); mojo.getLog().debug(" configureCCTask add to Path-- " + sdkInclude.getAbsolutePath()); } } else { addIncludePath(task, windowsSdkHome, "include"); } } else { for (File sdkInclude : sdkIncludes) { addIncludePathToTask(task, sdkInclude); } } task.addEnv(getPathVariable()); // TODO: supporting running with clean environment - addEnv sets // newEnvironemnt by default // task.setNewenvironment(false); Variable envVariable = new Variable(); // cl needs SystemRoot env var set, otherwise D8037 is raised (bogus // message) envVariable.setKey("SystemRoot"); envVariable.setValue(windowsHome.getAbsolutePath()); task.addEnv(envVariable); // cl needs TMP otherwise D8050 is raised c1xx.dll envVariable = new Variable(); envVariable.setKey("TMP"); envVariable.setValue(getTempPath()); task.addEnv(envVariable); final String envInclude = System.getenv("INCLUDE"); if (envInclude != null) { for (final String path : envInclude.split(";")) { addIncludePathToTask(task, new File(path)); } } } } public void configureLinker(final LinkerDef linker) throws MojoExecutionException { final String os = mojo.getOS(); if (os.equals(OS.WINDOWS) && isMSVC(mojo)) { final String arch = mojo.getArchitecture(); // Visual Studio if ("x86".equals(arch)) { linker.addLibraryDirectory(home, "VC/lib"); linker.addLibraryDirectory(home, "VC/atlmfc/lib"); } else { linker.addLibraryDirectory(home, "VC/lib/" + arch); linker.addLibraryDirectory(home, "VC/atlmfc/lib/" + arch); } // Windows SDK String sdkArch = arch; if ("amd64".equals(arch)) { sdkArch = "x64"; } // 6 lib ?+ lib/x86 or lib/x64 if (compareVersion(windowsSdkVersion, "8.0") < 0) { if ("x86".equals(arch)) { linker.addLibraryDirectory(windowsSdkHome, "lib"); } else { linker.addLibraryDirectory(windowsSdkHome, "lib/" + sdkArch); } } else { for (File sdkLib : sdkLibs) { linker.addLibraryDirectory(sdkLib, sdkArch); } } final String envLib = System.getenv("LIB"); if (envLib != null) { for (final String path : envLib.split(";")) { linker.addLibraryDirectory(new File(path)); } } } } private String getTempPath(){ if (null == tempPath) { tempPath = System.getenv("TMP"); if (tempPath == null) tempPath = System.getenv("TEMP"); if (tempPath == null) tempPath = "C:\\Temp"; } return tempPath; } public Variable getPathVariable() { if (paths.isEmpty()) return null; final Variable pathVariable = new Variable(); pathVariable.setKey("PATH"); pathVariable.setValue(StringUtils.join(paths.iterator(), File.pathSeparator)); return pathVariable; } public String getVersion() { return version; } public String getWindowsSdkVersion() { return windowsSdkVersion; } private void init() throws MojoFailureException, MojoExecutionException { final String mojoOs = mojo.getOS(); if (NarUtil.isWindows() && OS.WINDOWS.equals(mojoOs) && isMSVC(mojo)) { windowsHome = new File(System.getenv("SystemRoot")); initVisualStudio(); if (version.equals("8.0")) { // VS 2005 works with build in Windows SDK initWindowsSdk8(); initPath8(); } else { initWindowsSdk(); initPath(); } } else { version = ""; windowsSdkVersion = ""; windowsHome = null; } } private void initPath() throws MojoExecutionException { final String mojoArchitecture = mojo.getArchitecture(); final String osArchitecture = NarUtil.getArchitecture(null); // 32 bit build on 64 bit OS can be built with 32 bit tool, or 64 bit tool // in amd64_x86 - currently defaulting to prefer 64 bit tools - match os final boolean matchMojo = false; // TODO: toolset architecture // match os - os x86 mojo(x86 / x86_amd64); os x64 mojo(amd64_x86 / amd64); // 32bit - force 32 on 64bit mojo(x86 / x86_amd64) // match mojo - os x86 is as above; os x64 mojo (x86 / amd64) // Cross tools first if necessary, platform tools second, more generic tools // later if (force_requested_arch) { if ("amd64".equals(mojoArchitecture) && !matchMojo) { addPath(home, "VC/bin/amd64"); toolPathLinker = new File(home, "VC/bin/amd64").getAbsolutePath(); } else { addPath(home, "VC/bin"); toolPathLinker = new File(home, "VC/bin").getAbsolutePath(); } } else if (!osArchitecture.equals(mojoArchitecture) && !matchMojo) { if (!addPath(home, "VC/bin/" + osArchitecture + "_" + mojoArchitecture)) { throw new MojoExecutionException("Unable to find compiler for architecture " + mojoArchitecture + ".\n" + new File(home, "VC/bin/" + osArchitecture + "_" + mojoArchitecture)); } toolPathLinker = new File(home, "VC/bin/" + osArchitecture + "_" + mojoArchitecture).getAbsolutePath(); } if (null == toolPathLinker) { if ("amd64".equals(mojoArchitecture)) { toolPathLinker = new File(home, "VC/bin/amd64").getAbsolutePath(); if (!new File(toolPathLinker).exists()) { final String envVCToolsInstallDir = System.getenv("VCToolsInstallDir"); if (envVCToolsInstallDir != null) { toolPathLinker = new File(envVCToolsInstallDir, "bin/HostX64/x64").getAbsolutePath(); } } } else { toolPathLinker = new File(home, "VC/bin").getAbsolutePath(); } } if ("amd64".equals(osArchitecture) && !matchMojo) { addPath(home, "VC/bin/amd64"); } else { addPath(home, "VC/bin"); } addPath(home, "VC/VCPackages"); addPath(home, "Common7/Tools"); addPath(home, "Common7/IDE"); // 64 bit tools if present are preferred if (compareVersion(windowsSdkVersion, "7.1A") <= 0) { if ("amd64".equals(osArchitecture) && !matchMojo) { addPath(windowsSdkHome, "bin/x64"); } addPath(windowsSdkHome, "bin"); } else { if ("amd64".equals(osArchitecture) && !matchMojo) { addPath(windowsSdkHome, "bin/x64"); } addPath(windowsSdkHome, "bin/x86"); } if ("amd64".equals(mojoArchitecture)) { toolPathWindowsSDK = new File(windowsSdkHome, "bin/x64").getAbsolutePath(); } else if (compareVersion(windowsSdkVersion, "7.1A") <= 0) { toolPathWindowsSDK = new File(windowsSdkHome, "bin").getAbsolutePath(); } else { toolPathWindowsSDK = new File(windowsSdkHome, "bin/x86").getAbsolutePath(); } // clearing the path, add back the windows system folders addPath(windowsHome, "System32"); addPath(windowsHome, ""); addPath(windowsHome, "System32/wbem"); } private void initPath8() throws MojoExecutionException { final String mojoArchitecture = mojo.getArchitecture(); final String osArchitecture = NarUtil.getArchitecture(null); // 32 bit build on 64 bit OS can be built with 32 bit tool, or 64 bit tool // in amd64_x86 - currently defaulting to prefer 64 bit tools - match os final boolean matchMojo = false; // TODO: toolset architecture // match os - os x86 mojo(x86 / x86_amd64); os x64 mojo(amd64_x86 / amd64); // 32bit - force 32 on 64bit mojo(x86 / x86_amd64) // match mojo - os x86 is as above; os x64 mojo (x86 / amd64) // Cross tools first if necessary, platform tools second, more generic tools // later if (force_requested_arch) { if ("amd64".equals(mojoArchitecture) && !matchMojo) { addPath(home, "VC/bin/amd64"); toolPathLinker = new File(home, "VC/bin/amd64").getAbsolutePath(); } else { addPath(home, "VC/bin"); toolPathLinker = new File(home, "VC/bin").getAbsolutePath(); } } else if (!osArchitecture.equals(mojoArchitecture) && !matchMojo) { if (!addPath(home, "VC/bin/" + osArchitecture + "_" + mojoArchitecture)) { throw new MojoExecutionException("Unable to find compiler for architecture " + mojoArchitecture + ".\n" + new File(home, "VC/bin/" + osArchitecture + "_" + mojoArchitecture)); } toolPathLinker = new File(home, "VC/bin/" + osArchitecture + "_" + mojoArchitecture).getAbsolutePath(); } if (null == toolPathLinker) { if ("amd64".equals(mojoArchitecture)) toolPathLinker = new File(home, "VC/bin/amd64").getAbsolutePath(); else toolPathLinker = new File(home, "VC/bin").getAbsolutePath(); } if ("amd64".equals(osArchitecture) && !matchMojo) { addPath(home, "VC/bin/amd64"); } else { addPath(home, "VC/bin"); } // clearing the path, add back the windows system folders addPath(windowsHome, "System32"); addPath(windowsHome, ""); addPath(windowsHome, "System32/wbem"); } private void initVisualStudio() throws MojoFailureException, MojoExecutionException { mojo.getLog().debug(" -- Searching for usable VisualStudio "); mojo.getLog().debug("Linker version is " + version); if (version != null && version.trim().length() > 1) { String internalVersion; Pattern r = Pattern.compile("(\\d+)\\.*(\\d)"); Matcher matcher = r.matcher(version); if (matcher.find()) { internalVersion = matcher.group(1) + matcher.group(2); version = matcher.group(1) + "." + matcher.group(2); } else { throw new MojoExecutionException("msvc.version must be the internal version in the form 10.0 or 120"); } if (home == null) { final String commontToolsVar = System.getenv("VS" + internalVersion + "COMNTOOLS"); if (commontToolsVar != null && commontToolsVar.trim().length() > 0) { final File commonToolsDirectory = new File(commontToolsVar); if (commonToolsDirectory.exists()) { home = commonToolsDirectory.getParentFile().getParentFile(); } } // TODO: else Registry might be more reliable but adds dependency to be // able to acccess - HKLM\SOFTWARE\Microsoft\Visual Studio\Major.Minor:InstallDir } mojo.getLog() .debug(String.format(" VisualStudio %1s (%2s) found %3s ", version, internalVersion, home)); } else { version = ""; for (final Entry<String, String> entry : System.getenv().entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); final Pattern versionPattern = Pattern.compile("VS(\\d+)(\\d)COMNTOOLS"); final Matcher matcher = versionPattern.matcher(key); if (matcher.matches()) { final String version = matcher.group(1) + "." + matcher.group(2); if (versionStringComparator.compare(version, version) > 0) { final File commonToolsDirectory = new File(value); if (commonToolsDirectory.exists()) { this.version = version; home = commonToolsDirectory.getParentFile().getParentFile(); mojo.getLog().debug( String.format(" VisualStudio %1s (%2s) found %3s ", version, matcher.group(1) + matcher.group(2), home)); } } } } if (version.length() == 0) { final TextStream out = new StringTextStream(); final TextStream err = new StringTextStream(); final TextStream dbg = new StringTextStream(); NarUtil.runCommand("link", new String[] { "/?" }, null, null, out, err, dbg, null, true); final Pattern p = Pattern.compile("(\\d+\\.\\d+)\\.\\d+(\\.\\d+)?"); final Matcher m = p.matcher(out.toString()); if (m.find()) { version = m.group(1); mojo.getLog().debug( String.format(" VisualStudio Not found but link runs and reports version %1s (%2s)", version, m.group(0))); } else { throw new MojoExecutionException( "msvc.version not specified and no VS<Version>COMNTOOLS environment variable can be found"); } } } } private final Comparator<String> versionStringComparator = new Comparator<String>() { @Override public int compare(String o1, String o2) { DefaultArtifactVersion version1 = new DefaultArtifactVersion(o1); DefaultArtifactVersion version2 = new DefaultArtifactVersion(o2); return version1.compareTo(version2); } }; private final Comparator<File> versionComparator = new Comparator<File>() { @Override public int compare(File o1, File o2) { // will be sorted smallest first, so we need to invert the order of // the objects String firstDir = o2.getName(), secondDir = o1.getName(); if (firstDir.charAt(0) == 'v') { // remove 'v' and 'A' at the end firstDir = firstDir.substring(1, firstDir.length() - 1); secondDir = secondDir.substring(1, secondDir.length() - 1); } // impossible that two dirs are the same String[] firstVersionString = firstDir.split("\\."), secondVersionString = secondDir.split("\\."); int maxIdx = Math.min(firstVersionString.length, secondVersionString.length); int deltaVer; try { for (int i = 0; i < maxIdx; i++) if ((deltaVer = Integer.parseInt(firstVersionString[i]) - Integer.parseInt(secondVersionString[i])) != 0) return deltaVer; } catch (NumberFormatException e) { return firstDir.compareTo(secondDir); } if (firstVersionString.length > maxIdx) // 10.0.150 > 10.0 return 1; else if (secondVersionString.length > maxIdx) // 10.0 < 10.0.150 return -1; return 0; // impossible that they are the same } }; private boolean foundSDK = false; private void initWindowsSdk() throws MojoExecutionException { if (windowsSdkVersion != null && windowsSdkVersion.trim().equals("")) windowsSdkVersion = null; mojo.getLog().debug(" -- Searching for usable WindowSDK "); // newer first: 10 -> 8.1 -> 8.0 -> 7.1 and look for libs specified for (final File directory : Arrays.asList( new File("C:/Program Files (x86)/Windows Kits"), new File("C:/Program Files (x86)/Microsoft SDKs/Windows"), new File("C:/Program Files/Windows Kits"), new File("C:/Program Files/Microsoft SDKs/Windows") )) { if (directory.exists()) { final File[] kitDirectories = directory.listFiles(); Arrays.sort(kitDirectories, versionComparator); if (kitDirectories != null) { for (final File kitDirectory : kitDirectories) { if (new File(kitDirectory, "Include").exists()) { // legacy SDK String kitVersion = kitDirectory.getName(); if (kitVersion.charAt(0) == 'v') { kitVersion = kitVersion.substring(1); } if (windowsSdkVersion != null && compareVersion(kitVersion, windowsSdkVersion) != 0) continue; // skip versions not identical to exact version mojo.getLog() .debug(String.format(" WindowSDK %1s found %2s", kitVersion, kitDirectory.getAbsolutePath())); if (kitVersion.matches("\\d+\\.\\d+?[A-Z]?")) { // windows <= 8.1 legacySDK(kitDirectory); } else if (kitVersion.matches("\\d+?")) { // windows 10 SDK supports addNewSDKLibraries(kitDirectory); } } } if (libsRequired.size() == 0) // need it here to break out of the outer loop break; } } } if (!foundSDK) { // Search for SDK with lower versions for (final File directory : Arrays.asList( new File("C:/Program Files (x86)/Windows Kits"), new File("C:/Program Files (x86)/Microsoft SDKs/Windows"), new File("C:/Program Files/Windows Kits"), new File("C:/Program Files/Microsoft SDKs/Windows") )) { if (directory.exists()) { final File[] kitDirectories = directory.listFiles(); Arrays.sort(kitDirectories, versionComparator); if (kitDirectories != null) { for (final File kitDirectory : kitDirectories) { if (new File(kitDirectory, "Include").exists()) { // legacy SDK String kitVersion = kitDirectory.getName(); if (kitVersion.charAt(0) == 'v') { kitVersion = kitVersion.substring(1); } if (windowsSdkVersion != null && compareVersion(kitVersion, windowsSdkVersion) > 0) { continue; // skip versions higher than the previous version } mojo.getLog().debug(String.format(" WindowSDK %1s found %2s", kitVersion, kitDirectory.getAbsolutePath())); if (kitVersion.matches("\\d+\\.\\d+?[A-Z]?")) { // windows <= 8.1 legacySDK(kitDirectory); } else if (kitVersion.matches("\\d+?")) { // windows 10 SDK supports addNewSDKLibraries(kitDirectory); } } } if (libsRequired.size() == 0) // need it here to break out of the outer loop break; } } } } if (!foundSDK) throw new MojoExecutionException("msvc.windowsSdkVersion not specified and versions cannot be found"); mojo.getLog().debug(String.format(" Using WindowSDK %1s found %2s", windowsSdkVersion, windowsSdkHome)); } private void addNewSDKLibraries(final File kitDirectory) { // multiple installs List<File> kitVersionDirectories = Arrays.asList(new File(kitDirectory, "Include").listFiles()); Collections.sort(kitVersionDirectories, versionComparator); ListIterator<File> kitVersionDirectoriesIt = kitVersionDirectories.listIterator(); File kitVersionDirectory = null; while (kitVersionDirectoriesIt.hasNext() && (kitVersionDirectory = kitVersionDirectoriesIt.next()) != null) { if (new File(kitVersionDirectory, "ucrt").exists()) { break; } } if (kitVersionDirectory != null) { String version = kitVersionDirectory.getName(); mojo.getLog().debug(String.format(" Latest Win %1s KitDir at %2s", kitVersionDirectory.getName(), kitVersionDirectory.getAbsolutePath())); // add the libraries found: File includeDir = new File(kitDirectory, "Include/" + version); File libDir = new File(kitDirectory, "Lib/" + version); addSDKLibs(includeDir, libDir); setKit(kitDirectory); } } private void setKit(File home) { if (!foundSDK) { if (windowsSdkVersion == null) windowsSdkVersion = home.getName(); if (windowsSdkHome == null) windowsSdkHome = home; foundSDK = true; } } private void legacySDK(final File kitDirectory) { File includeDir = new File(kitDirectory, "Include"); File libDir = new File(kitDirectory, "Lib"); if (includeDir.exists() && libDir.exists()){ File usableLibDir = null; for (final File libSubDir : libDir.listFiles()) { final File um = new File(libSubDir,"um"); if (um.exists()) usableLibDir = libSubDir; } if (usableLibDir == null) usableLibDir = libDir.listFiles()[0]; addSDKLibs(includeDir, usableLibDir); setKit(kitDirectory); } } private void addSDKLibs(File includeDir, File libdir) { final File[] libs = includeDir.listFiles(); for (final File libIncludeDir : libs) { // <libName> <include path> <lib path> if (libsRequired.remove(libIncludeDir.getName())) { mojo.getLog().debug(String.format(" Using directory %1s for library %2s", libIncludeDir.getAbsolutePath(), libIncludeDir.getName())); sdkIncludes.add(libIncludeDir); sdkLibs.add(new File(libdir, libIncludeDir.getName())); } } } private void initWindowsSdk8() throws MojoExecutionException { final String osArchitecture = NarUtil.getArchitecture(null); //VS 2005 - The SDK files are included in the VS installation- File VCINSTALLDIR = new File (home,"VC"); //File VSLibDir = new File(VCINSTALLDIR.getAbsolutePath()+File.separator+ "lib" , osArchitecture); File PlatformSDKIncludeDir = new File(VCINSTALLDIR.getAbsolutePath()+ File.separator+ "PlatformSDK", "include"); File SDKIncludeDir = new File(VCINSTALLDIR.getAbsolutePath()+ File.separator+ "SDK"+ File.separator+ "v2.0", "include"); sdkIncludes.add(PlatformSDKIncludeDir); sdkIncludes.add(SDKIncludeDir); windowsSdkHome = home; } public void setMojo(final AbstractNarMojo mojo) throws MojoFailureException, MojoExecutionException { if (this.mojo != mojo) { this.mojo = mojo; init(); } } @Override public String toString() { return "VS Home-"+ home + "\nSDKHome-" + windowsSdkHome; } public String getToolPath() { return toolPathLinker; } public String getSDKToolPath() { return toolPathWindowsSDK; } public void setToolPath(CompilerDef compilerDef, String name) { if ("res".equals(name) || "mc".equals(name) || "idl".equals(name)) { compilerDef.setToolPath(toolPathWindowsSDK); } else { compilerDef.setToolPath(toolPathLinker); } } public int compareVersion(Object o1, Object o2) { String version1 = (String) o1; String version2 = (String) o2; VersionTokenizer tokenizer1 = new VersionTokenizer(version1); VersionTokenizer tokenizer2 = new VersionTokenizer(version2); int number1 = 0, number2 = 0; String suffix1 = "", suffix2 = ""; while (tokenizer1.MoveNext()) { if (!tokenizer2.MoveNext()) { do { number1 = tokenizer1.getNumber(); suffix1 = tokenizer1.getSuffix(); if (number1 != 0 || suffix1.length() != 0) { // Version one is longer than number two, and non-zero return 1; } } while (tokenizer1.MoveNext()); // Version one is longer than version two, but zero return 0; } number1 = tokenizer1.getNumber(); suffix1 = tokenizer1.getSuffix(); number2 = tokenizer2.getNumber(); suffix2 = tokenizer2.getSuffix(); if (number1 < number2) { // Number one is less than number two return -1; } if (number1 > number2) { // Number one is greater than number two return 1; } boolean empty1 = suffix1.length() == 0; boolean empty2 = suffix2.length() == 0; if (empty1 && empty2) continue; // No suffixes if (empty1) return 1; // First suffix is empty (1.2 > 1.2b) if (empty2) return -1; // Second suffix is empty (1.2a < 1.2) // Lexical comparison of suffixes int result = suffix1.compareTo(suffix2); if (result != 0) return result; } if (tokenizer2.MoveNext()) { do { number2 = tokenizer2.getNumber(); suffix2 = tokenizer2.getSuffix(); if (number2 != 0 || suffix2.length() != 0) { // Version one is longer than version two, and non-zero return -1; } } while (tokenizer2.MoveNext()); // Version two is longer than version one, but zero return 0; } return 0; } // VersionTokenizer.java class VersionTokenizer { private final String _versionString; private final int _length; private int _position; private int _number; private String _suffix; private boolean _hasValue; public int getNumber() { return _number; } public String getSuffix() { return _suffix; } public boolean hasValue() { return _hasValue; } public VersionTokenizer(String versionString) { if (versionString == null) throw new IllegalArgumentException("versionString is null"); _versionString = versionString; _length = versionString.length(); } public boolean MoveNext() { _number = 0; _suffix = ""; _hasValue = false; // No more characters if (_position >= _length) return false; _hasValue = true; while (_position < _length) { char c = _versionString.charAt(_position); if (c < '0' || c > '9') break; _number = _number * 10 + (c - '0'); _position++; } int suffixStart = _position; while (_position < _length) { char c = _versionString.charAt(_position); if (c == '.') break; _position++; } _suffix = _versionString.substring(suffixStart, _position); if (_position < _length) _position++; return true; } } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:19-06-26"); this.setApiVersion("15.2.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:18-12-03"); this.setApiVersion("14.9.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:20-01-12"); this.setApiVersion("15.15.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:18-03-18"); this.setApiVersion("3.3.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:22-03-07"); this.setApiVersion("18.0.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
// This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platfroms allow them to do with // text. // This program is free software: you can redistribute it and/or modify // published by the Free Software Foundation, either version 3 of the // This program is distributed in the hope that it will be useful, // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // @ignore package com.kaltura.client; import com.kaltura.client.utils.request.ConnectionConfiguration; import com.kaltura.client.types.BaseResponseProfile; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") public class Client extends ClientBase { public Client(ConnectionConfiguration config) { super(config); this.setClientTag("java:18-12-12"); this.setApiVersion("14.10.0"); this.clientConfiguration.put("format", 1); // JSON } /** * @param clientTag */ public void setClientTag(String clientTag){ this.clientConfiguration.put("clientTag", clientTag); } /** * @return String */ public String getClientTag(){ if(this.clientConfiguration.containsKey("clientTag")){ return(String) this.clientConfiguration.get("clientTag"); } return null; } /** * @param apiVersion */ public void setApiVersion(String apiVersion){ this.clientConfiguration.put("apiVersion", apiVersion); } /** * @return String */ public String getApiVersion(){ if(this.clientConfiguration.containsKey("apiVersion")){ return(String) this.clientConfiguration.get("apiVersion"); } return null; } /** * @param partnerId Impersonated partner id */ public void setPartnerId(Integer partnerId){ this.requestConfiguration.put("partnerId", partnerId); } /** * Impersonated partner id * * @return Integer */ public Integer getPartnerId(){ if(this.requestConfiguration.containsKey("partnerId")){ return(Integer) this.requestConfiguration.get("partnerId"); } return 0; } /** * @param ks Kaltura API session */ public void setKs(String ks){ this.requestConfiguration.put("ks", ks); } /** * Kaltura API session * * @return String */ public String getKs(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param sessionId Kaltura API session */ public void setSessionId(String sessionId){ this.requestConfiguration.put("ks", sessionId); } /** * Kaltura API session * * @return String */ public String getSessionId(){ if(this.requestConfiguration.containsKey("ks")){ return(String) this.requestConfiguration.get("ks"); } return null; } /** * @param responseProfile Response profile - this attribute will be automatically unset after every API call. */ public void setResponseProfile(BaseResponseProfile responseProfile){ this.requestConfiguration.put("responseProfile", responseProfile); } /** * Response profile - this attribute will be automatically unset after every API call. * * @return BaseResponseProfile */ public BaseResponseProfile getResponseProfile(){ if(this.requestConfiguration.containsKey("responseProfile")){ return(BaseResponseProfile) this.requestConfiguration.get("responseProfile"); } return null; } }
package at.ac.tuwien.dsg.myx.monitor.aggregator; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import at.ac.tuwien.dsg.myx.monitor.Bootstrap; public class MyxMonitoringAggregator extends Bootstrap { public static final String ARCHITECTURE_FILE_NAME = "myx-monitor-aggregator.xml"; public static final String STRUCTURE_NAME = "aggregator"; public static void main(String[] args) { List<String> realArgs = Arrays.asList(args); String architectureFilePath = null; // check if the architecture file is available in the working directory String workingDir = System.getProperty("user.dir"); if (workingDir != null) { File xmlFile = new File(new File(workingDir), ARCHITECTURE_FILE_NAME); if (xmlFile.exists()) { architectureFilePath = xmlFile.getPath(); } } // check if the architecture file is available as a resource if (architectureFilePath == null) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); URL url = classLoader.getResource(ARCHITECTURE_FILE_NAME); if (url != null) { architectureFilePath = url.getPath(); } } List<String> adaptedArgs = new ArrayList<>(); // if an architecture file was found we add it to the arguments if (architectureFilePath != null) { adaptedArgs.add(architectureFilePath); } // add the structure name if none was given if (!realArgs.contains("-s") && !realArgs.contains("--structure")) { adaptedArgs.add("--structure"); adaptedArgs.add(STRUCTURE_NAME); } adaptedArgs.addAll(realArgs); // call the myx-monitor bootstrap new MyxMonitoringAggregator().run(adaptedArgs.toArray(new String[0])); } @Override protected void usage() { System.err.println("Usage:"); System.err .println(" java " + this.getClass().getName() + " [file] [-s|--structure structureName] [-i|--id architectureRuntimeId] [-d|--event-dispatcher className] [-e|--event-manager className] [-c|--event-manager-connection-string connectionString]"); System.err.println(); System.err.println(" where:"); System.err.println(" file: the name of the xADL file to bootstrap, default: " + ARCHITECTURE_FILE_NAME); System.err.println(" -s structureName: the name of the structure to bootstrap, default: " + STRUCTURE_NAME); System.err.println(" -i architectureInstanceId: the architecture runtime id"); System.err.println(" -d className: the event dispatcher class name that should be instantiated"); System.err.println(" -e className: the event manager class name that should be used to propagate events"); System.err.println(" -c connectionString: the connection string that should be used to propate events"); System.err.println(); System.exit(-2); } }
package model.item; /** * NOTHING IN HERE IS IMPLEMENTED */ class EquipmentManager { private Helmet helmet; private ChestPiece chestPiece; private Leggings leggings; private Boots boots; private Gloves gloves; private Shield shield; private Weapon weapon; public Helmet equipHelmet(Helmet helmet){ Helmet conflict = unequipHelmet(); this.helmet = helmet; return conflict; } public ChestPiece equipChestPiece(ChestPiece chestpiece){ ChestPiece conflict = unequipChestPiece(); this.chestPiece = chestpiece; return conflict; } public Leggings equipLeggings(Leggings leggings){ Leggings conflict = unequipLeggings(); this.leggings = leggings; return conflict; } public Boots equipBoots(Boots boots){ Boots conflict = unequipBoots(); this.boots = boots; return conflict; } public Gloves equipGloves(Gloves gloves){ Gloves conflict = unequipGloves(); this.gloves = gloves; return conflict; } public Shield equipShield(Shield shield){ Shield conflict = unequipShield(); this.shield = shield; return conflict; } public Weapon equipWeapon(Weapon weapon){ Weapon conflict = unequipWeapon(); this.weapon = weapon; return conflict; } public Helmet unequipHelmet() { Helmet helmet = this.helmet; this.helmet = null; return helmet; } public ChestPiece unequipChestPiece() { ChestPiece chestPiece = this.chestPiece; this.chestPiece = null; return chestPiece; } public Leggings unequipLeggings() { Leggings leggings = this.leggings; this.leggings = null; return leggings; } public Boots unequipBoots() { Boots boots = this.boots; this.boots = null; return boots; } public Gloves unequipGloves() { Gloves gloves = this.gloves; this.gloves = null; return gloves; } public Shield unequipShield() { Shield shield = this.shield; this.shield = null; return shield; } public Weapon unequipWeapon() { Weapon weapon = this.weapon; this.weapon = null; return weapon; } }
package common.domain; public class Letter { /** Must only be accessed from within getNewId() */ private static int lastId = 0; private char letter; private int id; public Letter(char value) { this.letter = value; this.id = getNewId(); } public char getValue() { return letter; } public int getId() { return id; } /** * Generates new id: should be called in constructor. */ protected static int getNewId() { return lastId++; } public String toString() { return "letter='" + letter + "', id=" + id; } }